code
stringlengths
31
1.05M
apis
list
extract_api
stringlengths
97
1.91M
# Copyright 2018 <NAME> @imsrgadich # # 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 tensorflow as tf import numpy as np from gpflow.decors import params_as_tensors from gpflow.params import Parameter from gpflow.kernels import Kernel,RBF,Cosine from gpflow import transforms, autoflow,settings class SpectralMixture(Kernel): def __init__(self, num_mixtures=1, mixture_weights=None,\ mixture_scales=None,mixture_means=None,\ input_dim=1,active_dims=None,name=None): """ - num_mixtures is the number of mixtures; denoted as Q in Wilson 2013. - mixture_weights - mixture_variance is - mixture_means is the list (or array) of means of the mixtures. - input_dim is the dimension of the input to the kernel. - active_dims is the dimension of the X which needs to be used. References: http://hips.seas.harvard.edu/files/wilson-extrapolation-icml-2013_0.pdf http://www.cs.cmu.edu/~andrewgw/typo.pdf """ super().__init__(input_dim,active_dims,name=name) # Q(num_of_mixtures)=1 then SM kernel is SE Kernel. if num_mixtures == 1: print("Using default mixture = 1") # number of mixtures is non trainable. self.num_mixtures = Parameter(num_mixtures,trainable=False) self.mixture_weights = Parameter(mixture_weights,transform=transforms.positive) self.mixture_scales = Parameter(mixture_scales,transform=transforms.positive) self.mixture_means = Parameter(mixture_means,transform=transforms.positive) @params_as_tensors def K(self, X1, X2=None): if self.mixture_weights == None or self.mixture_means == None \ or self.mixture_scales == None: raise RuntimeError('Parameters of spectral mixture kernel not initialized.\ Run `sm_kern_object.initialize_(train_x,train_y)`.') # initialization can only be done by user as it needs target data as well. if X2 is None: X2 = X1 # get absolute distances X1 = tf.transpose(tf.expand_dims(X1, -1), perm=[1, 0, 2]) # D x N1 x 1 X2 = tf.expand_dims(tf.transpose(X2, perm=[1, 0]), -2) # D x 1 x N2 r = tf.abs(tf.subtract(X1, X2)) # D x N1 x N2 cos_term = tf.multiply(tf.tensordot(self.mixture_means, r, axes=((1),(0))), 2. * np.pi) # num_mixtures x N1 x N2 scales_expand = tf.expand_dims(tf.expand_dims(self.mixture_scales, -2), -2) # D x 1 x 1 x num_mixtures r_tile = tf.tile(tf.expand_dims(r,-1),(1,1,1,self.num_mixtures)) # D x N1 x N2 x num_mixtures exp_term = tf.multiply(tf.transpose(tf.reduce_sum(tf.square(tf.multiply(r_tile, scales_expand)), 0)\ ,perm=[2, 0, 1]), -2. * np.pi ** 2) # num_mixtures x N1 x N2 weights = tf.expand_dims(tf.expand_dims(self.mixture_weights,-1),-1) weights = tf.tile(weights,(1,tf.shape(X1)[1],tf.shape(X2)[2])) return tf.reduce_sum(tf.multiply(weights,tf.multiply(tf.exp(exp_term),tf.cos(cos_term))),0) @params_as_tensors def Kdiag(self, X): # just the sum of weights. Weights represent the signal # variance. return tf.fill(tf.stack([tf.shape(X)[0]]),tf.reduce_sum(self.mixture_weights,0)) def sm_init(train_x, train_y, num_mixtures): """ For initialization of the parameters for the Spectral Mixture Kernel. :param train_x: input data :param train_y: target data :param num_mixtures: number of mixtures :return: param_name dimensions ---------- ---------- mixture weights| num_mixtures x 1 mixture means | num_mixtures x input_dim mixture scales | input_dim x num_mixtures """ assert isinstance(num_mixtures, int) assert train_x.shape[0] == train_y.shape[0] input_dim = np.shape(train_x)[1] # type: int if np.size(train_x.shape) == 1: train_x = np.expand_dims(train_x ,-1) if np.size(train_x.shape) == 2: train_x = np.expand_dims(train_x ,0) train_x_sort = np.copy(train_x) train_x_sort.sort(axis=1) max_dist = np.squeeze(train_x_sort[: ,-1, :] - train_x_sort[: ,0, :]) min_dist_sort = np.squeeze(np.abs(train_x_sort[: ,1:, :] - train_x_sort[: ,:-1, :])) min_dist = np.zeros([input_dim] ,dtype=float) # min of each data column could be zero. Hence, picking minimum which is not zero for ind in np.arange(input_dim): try: min_dist[ind] = min_dist_sort[np.amin(np.where(min_dist_sort[:,ind] > 0), axis=1), ind] except: min_dist[ind] = min_dist_sort[np.amin(np.where(min_dist_sort > 0), axis=1)] # for random restarts during batch processing. We need to initialize at every # batch. Lock the seed here. seed= np.random.randint(low=1 ,high=2**31) np.random.seed(seed) # Inverse of lengthscales should be drawn from truncated Gaussian |N(0, max_dist^2)| # dim: Q x D # mixture_scales = tf.multiply(,tf.cast(max_dist,dtype=tf.float32)**(-1) mixture_scales = (np.multiply(np.abs(np.random.randn(num_mixtures,input_dim)), np.expand_dims(max_dist ,axis=0)))**(-1) # Draw means from Unif(0, 0.5 / minimum distance between two points), dim: Q x D # the nyquist is half of maximum frequency. TODO nyquist = np.divide(0.5,min_dist) mixture_means = np.multiply(np.random.rand(num_mixtures,input_dim),\ np.expand_dims(nyquist,0)) mixture_means[0,:] = 0 # Mixture weights should be roughly the std of the y values divided by # the number of mixtures # dim: 1 x Q mixture_weights= np.divide(np.std(train_y,axis=0),num_mixtures)*np.ones(num_mixtures) return mixture_weights, mixture_means, mixture_scales.T
[ "tensorflow.reduce_sum", "numpy.random.seed", "numpy.abs", "numpy.ones", "numpy.shape", "tensorflow.multiply", "numpy.random.randint", "numpy.arange", "gpflow.params.Parameter", "numpy.copy", "tensorflow.subtract", "numpy.std", "numpy.random.randn", "tensorflow.exp", "numpy.divide", "n...
[((4898, 4914), 'numpy.copy', 'np.copy', (['train_x'], {}), '(train_x)\n', (4905, 4914), True, 'import numpy as np\n'), ((4961, 5019), 'numpy.squeeze', 'np.squeeze', (['(train_x_sort[:, -1, :] - train_x_sort[:, 0, :])'], {}), '(train_x_sort[:, -1, :] - train_x_sort[:, 0, :])\n', (4971, 5019), True, 'import numpy as np\n'), ((5125, 5159), 'numpy.zeros', 'np.zeros', (['[input_dim]'], {'dtype': 'float'}), '([input_dim], dtype=float)\n', (5133, 5159), True, 'import numpy as np\n'), ((5262, 5282), 'numpy.arange', 'np.arange', (['input_dim'], {}), '(input_dim)\n', (5271, 5282), True, 'import numpy as np\n'), ((5628, 5666), 'numpy.random.randint', 'np.random.randint', ([], {'low': '(1)', 'high': '(2 ** 31)'}), '(low=1, high=2 ** 31)\n', (5645, 5666), True, 'import numpy as np\n'), ((5669, 5689), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (5683, 5689), True, 'import numpy as np\n'), ((6193, 6217), 'numpy.divide', 'np.divide', (['(0.5)', 'min_dist'], {}), '(0.5, min_dist)\n', (6202, 6217), True, 'import numpy as np\n'), ((1812, 1852), 'gpflow.params.Parameter', 'Parameter', (['num_mixtures'], {'trainable': '(False)'}), '(num_mixtures, trainable=False)\n', (1821, 1852), False, 'from gpflow.params import Parameter\n'), ((1883, 1940), 'gpflow.params.Parameter', 'Parameter', (['mixture_weights'], {'transform': 'transforms.positive'}), '(mixture_weights, transform=transforms.positive)\n', (1892, 1940), False, 'from gpflow.params import Parameter\n'), ((1970, 2026), 'gpflow.params.Parameter', 'Parameter', (['mixture_scales'], {'transform': 'transforms.positive'}), '(mixture_scales, transform=transforms.positive)\n', (1979, 2026), False, 'from gpflow.params import Parameter\n'), ((2055, 2110), 'gpflow.params.Parameter', 'Parameter', (['mixture_means'], {'transform': 'transforms.positive'}), '(mixture_means, transform=transforms.positive)\n', (2064, 2110), False, 'from gpflow.params import Parameter\n'), ((4679, 4696), 'numpy.shape', 'np.shape', (['train_x'], {}), '(train_x)\n', (4687, 4696), True, 'import numpy as np\n'), ((4721, 4743), 'numpy.size', 'np.size', (['train_x.shape'], {}), '(train_x.shape)\n', (4728, 4743), True, 'import numpy as np\n'), ((4768, 4795), 'numpy.expand_dims', 'np.expand_dims', (['train_x', '(-1)'], {}), '(train_x, -1)\n', (4782, 4795), True, 'import numpy as np\n'), ((4804, 4826), 'numpy.size', 'np.size', (['train_x.shape'], {}), '(train_x.shape)\n', (4811, 4826), True, 'import numpy as np\n'), ((4851, 4877), 'numpy.expand_dims', 'np.expand_dims', (['train_x', '(0)'], {}), '(train_x, 0)\n', (4865, 4877), True, 'import numpy as np\n'), ((5052, 5108), 'numpy.abs', 'np.abs', (['(train_x_sort[:, 1:, :] - train_x_sort[:, :-1, :])'], {}), '(train_x_sort[:, 1:, :] - train_x_sort[:, :-1, :])\n', (5058, 5108), True, 'import numpy as np\n'), ((6249, 6288), 'numpy.random.rand', 'np.random.rand', (['num_mixtures', 'input_dim'], {}), '(num_mixtures, input_dim)\n', (6263, 6288), True, 'import numpy as np\n'), ((6345, 6371), 'numpy.expand_dims', 'np.expand_dims', (['nyquist', '(0)'], {}), '(nyquist, 0)\n', (6359, 6371), True, 'import numpy as np\n'), ((6590, 6611), 'numpy.ones', 'np.ones', (['num_mixtures'], {}), '(num_mixtures)\n', (6597, 6611), True, 'import numpy as np\n'), ((2681, 2703), 'tensorflow.expand_dims', 'tf.expand_dims', (['X1', '(-1)'], {}), '(X1, -1)\n', (2695, 2703), True, 'import tensorflow as tf\n'), ((2763, 2792), 'tensorflow.transpose', 'tf.transpose', (['X2'], {'perm': '[1, 0]'}), '(X2, perm=[1, 0])\n', (2775, 2792), True, 'import tensorflow as tf\n'), ((2832, 2851), 'tensorflow.subtract', 'tf.subtract', (['X1', 'X2'], {}), '(X1, X2)\n', (2843, 2851), True, 'import tensorflow as tf\n'), ((2900, 2948), 'tensorflow.tensordot', 'tf.tensordot', (['self.mixture_means', 'r'], {'axes': '(1, 0)'}), '(self.mixture_means, r, axes=(1, 0))\n', (2912, 2948), True, 'import tensorflow as tf\n'), ((3038, 3077), 'tensorflow.expand_dims', 'tf.expand_dims', (['self.mixture_scales', '(-2)'], {}), '(self.mixture_scales, -2)\n', (3052, 3077), True, 'import tensorflow as tf\n'), ((3199, 3220), 'tensorflow.expand_dims', 'tf.expand_dims', (['r', '(-1)'], {}), '(r, -1)\n', (3213, 3220), True, 'import tensorflow as tf\n'), ((3647, 3687), 'tensorflow.expand_dims', 'tf.expand_dims', (['self.mixture_weights', '(-1)'], {}), '(self.mixture_weights, -1)\n', (3661, 3687), True, 'import tensorflow as tf\n'), ((4046, 4084), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['self.mixture_weights', '(0)'], {}), '(self.mixture_weights, 0)\n', (4059, 4084), True, 'import tensorflow as tf\n'), ((5999, 6031), 'numpy.expand_dims', 'np.expand_dims', (['max_dist'], {'axis': '(0)'}), '(max_dist, axis=0)\n', (6013, 6031), True, 'import numpy as np\n'), ((6553, 6576), 'numpy.std', 'np.std', (['train_y'], {'axis': '(0)'}), '(train_y, axis=0)\n', (6559, 6576), True, 'import numpy as np\n'), ((5916, 5956), 'numpy.random.randn', 'np.random.randn', (['num_mixtures', 'input_dim'], {}), '(num_mixtures, input_dim)\n', (5931, 5956), True, 'import numpy as np\n'), ((3728, 3740), 'tensorflow.shape', 'tf.shape', (['X1'], {}), '(X1)\n', (3736, 3740), True, 'import tensorflow as tf\n'), ((3744, 3756), 'tensorflow.shape', 'tf.shape', (['X2'], {}), '(X2)\n', (3752, 3756), True, 'import tensorflow as tf\n'), ((3823, 3839), 'tensorflow.exp', 'tf.exp', (['exp_term'], {}), '(exp_term)\n', (3829, 3839), True, 'import tensorflow as tf\n'), ((3840, 3856), 'tensorflow.cos', 'tf.cos', (['cos_term'], {}), '(cos_term)\n', (3846, 3856), True, 'import tensorflow as tf\n'), ((3407, 3441), 'tensorflow.multiply', 'tf.multiply', (['r_tile', 'scales_expand'], {}), '(r_tile, scales_expand)\n', (3418, 3441), True, 'import tensorflow as tf\n'), ((4029, 4040), 'tensorflow.shape', 'tf.shape', (['X'], {}), '(X)\n', (4037, 4040), True, 'import tensorflow as tf\n'), ((5347, 5382), 'numpy.where', 'np.where', (['(min_dist_sort[:, ind] > 0)'], {}), '(min_dist_sort[:, ind] > 0)\n', (5355, 5382), True, 'import numpy as np\n'), ((5463, 5490), 'numpy.where', 'np.where', (['(min_dist_sort > 0)'], {}), '(min_dist_sort > 0)\n', (5471, 5490), True, 'import numpy as np\n')]
""" Refer to "scikit-learn" """ # Author: Kun <<EMAIL>> # License: xxx import os import numpy def configuration(parent_package="", top_path=None): from numpy.distutils.misc_util import Configuration libraries = [] if os.name == "posix": libraries.append("m") config = Configuration("cluster", parent_package, top_path) config.add_extension( "_dbscan_inner", sources=["_dbscan_inner.pyx"], include_dirs=[numpy.get_include()], language="c++", ) config.add_extension( "_hierarchical_fast", sources=["_hierarchical_fast.pyx"], language="c++", include_dirs=[numpy.get_include()], libraries=libraries, ) config.add_extension( "_k_means_common", sources=["_k_means_common.pyx"], include_dirs=[numpy.get_include()], libraries=libraries, ) config.add_extension( "_k_means_lloyd", sources=["_k_means_lloyd.pyx"], include_dirs=[numpy.get_include()], libraries=libraries, ) config.add_extension( "_k_means_elkan", sources=["_k_means_elkan.pyx"], include_dirs=[numpy.get_include()], libraries=libraries, ) config.add_extension( "_k_means_minibatch", sources=["_k_means_minibatch.pyx"], include_dirs=[numpy.get_include()], libraries=libraries, ) config.add_subpackage("tests") return config if __name__ == "__main__": from numpy.distutils.core import setup setup(**configuration(top_path="").todict())
[ "numpy.distutils.misc_util.Configuration", "numpy.get_include" ]
[((280, 330), 'numpy.distutils.misc_util.Configuration', 'Configuration', (['"""cluster"""', 'parent_package', 'top_path'], {}), "('cluster', parent_package, top_path)\n", (293, 330), False, 'from numpy.distutils.misc_util import Configuration\n'), ((423, 442), 'numpy.get_include', 'numpy.get_include', ([], {}), '()\n', (440, 442), False, 'import numpy\n'), ((586, 605), 'numpy.get_include', 'numpy.get_include', ([], {}), '()\n', (603, 605), False, 'import numpy\n'), ((730, 749), 'numpy.get_include', 'numpy.get_include', ([], {}), '()\n', (747, 749), False, 'import numpy\n'), ((872, 891), 'numpy.get_include', 'numpy.get_include', ([], {}), '()\n', (889, 891), False, 'import numpy\n'), ((1014, 1033), 'numpy.get_include', 'numpy.get_include', ([], {}), '()\n', (1031, 1033), False, 'import numpy\n'), ((1164, 1183), 'numpy.get_include', 'numpy.get_include', ([], {}), '()\n', (1181, 1183), False, 'import numpy\n')]
import click as ck import numpy as np import pandas as pd from collections import Counter from utils import Ontology, FUNC_DICT, NAMESPACES, read_fasta import logging import os logging.basicConfig(level=logging.INFO) @ck.command() @ck.option( '--go-file', '-gf', default='data-cafa3/go.obo', help='Gene Ontology file in OBO Format') @ck.option( '--data-file', '-df', default='data-cafa3/swissprot_exp.pkl', help='Uniprot KB, generated with uni2pandas.py') @ck.option( '--sim-file', '-sf', default='data-cafa3/swissprot_exp.sim', help='Sequence similarity generated with Diamond') def main(go_file, data_file, sim_file): go = Ontology(go_file, with_rels=True) logging.info('GO loaded') df = pd.read_pickle(data_file) proteins = set(df['proteins'].values) print("DATA FILE" ,len(df)) print("Loading CAFA3 data") targets, seqs = read_fasta('data-cafa3/CAFA3_targets/targets_all.fasta') sequences = {t: s for t, s in zip(targets, seqs)} nk_proteins = set() nk_files = ['bpo_all_type1.txt', 'mfo_all_type1.txt', 'cco_all_type1.txt'] for filename in nk_files: with open(f'data-cafa3/benchmark20171115/lists/{filename}') as f: proteins = f.read().splitlines() nk_proteins |= set(proteins) exp_annots = {} with open('data-cafa3/benchmark20171115/groundtruth/leafonly_all.txt') as f: for line in f: target_id, go_id = line.strip().split('\t') if target_id not in nk_proteins: continue if target_id not in exp_annots: exp_annots[target_id] = [] exp_annots[target_id].append(go_id) interpros = {} with open('data-cafa3/benchmark20171115/targets.fasta.tsv') as f: for line in f: it = line.strip().split('\t') t_id, ipr = it[0], it[11] if t_id not in interpros: interpros[t_id] = set() interpros[t_id].add(ipr) seqs = [] targets = [] exp_annotations = [] prop_annotations = [] iprs = [] for t_id, annots in exp_annots.items(): targets.append(t_id) exp_annotations.append(annots) seqs.append(sequences[t_id]) annot_set = set() for go_id in annots: annot_set |= go.get_anchestors(go_id) annots = list(annot_set) prop_annotations.append(annots) if t_id in interpros: iprs.append(interpros[t_id]) else: iprs.append(set()) test_df = pd.DataFrame({ 'proteins': targets, 'sequences': seqs, 'exp_annotations': exp_annotations, 'prop_annotations': prop_annotations, 'interpros': iprs }) print('Processing train and valid annotations') annotations = list() for ont in ['mf', 'bp', 'cc']: cnt = Counter() iprs = Counter() index = [] test_index = [] for i, row in enumerate(df.itertuples()): ok = False for term in row.prop_annotations: if go.get_namespace(term) == NAMESPACES[ont]: cnt[term] += 1 ok = True for ipr in row.interpros: iprs[ipr] += 1 if ok: index.append(i) for i, row in enumerate(test_df.itertuples()): ok = False for term in row.prop_annotations: if go.get_namespace(term) == NAMESPACES[ont]: ok = True if len(row.interpros) == 0: ok = False if ok: test_index.append(i) del cnt[FUNC_DICT[ont]] # Remove top term tdf = df.iloc[index] terms = list(cnt.keys()) interpros = list(iprs.keys()) print(f'Number of {ont} terms {len(terms)}') print(f'Number of {ont} iprs {len(iprs)}') print(f'Number of {ont} proteins {len(tdf)}') terms_df = pd.DataFrame({'gos': terms}) terms_df.to_pickle(f'data-cafa3/{ont}/terms.pkl') iprs_df = pd.DataFrame({'interpros': interpros}) iprs_df.to_pickle(f'data-cafa3/{ont}/interpros.pkl') # Split train/valid/test proteins = tdf['proteins'] prot_set = set(proteins) prot_idx = {v:k for k, v in enumerate(proteins)} sim = {} train_prots = set() with open(sim_file) as f: for line in f: it = line.strip().split('\t') p1, p2, score = it[0], it[1], float(it[2]) / 100.0 if p1 == p2: continue if score < 0.5: continue if p1 not in prot_set or p2 not in prot_set: continue if p1 not in sim: sim[p1] = [] if p2 not in sim: sim[p2] = [] sim[p1].append(p2) sim[p2].append(p1) used = set() def dfs(prots, prot): used.add(prot) if prot in sim: for p in sim[prot]: if p not in used: dfs(prots, p) prots.append(prot) groups = [] for p in proteins: group = [] if p not in used: dfs(group, p) groups.append(group) print(len(proteins), len(groups)) index = np.arange(len(groups)) np.random.seed(seed=0) np.random.shuffle(index) train_n = int(len(groups) * 0.9) train_index = [] valid_index = [] for idx in index[:train_n]: for prot in groups[idx]: train_index.append(prot_idx[prot]) for idx in index[train_n:]: for prot in groups[idx]: valid_index.append(prot_idx[prot]) train_index = np.array(train_index) valid_index = np.array(valid_index) train_df = tdf.iloc[train_index] train_df.to_pickle(f'data-cafa3/{ont}/train_data.pkl') valid_df = tdf.iloc[valid_index] valid_df.to_pickle(f'data-cafa3/{ont}/valid_data.pkl') ts_df = test_df.iloc[test_index] ts_df.to_pickle(f'data-cafa3/{ont}/test_data.pkl') print(f'Train/Valid proteins for {ont} {len(train_df)}/{len(valid_df)}') print(f'Test proteins for {ont} {len(ts_df)}') if __name__ == '__main__': main()
[ "pandas.DataFrame", "utils.Ontology", "numpy.random.seed", "logging.basicConfig", "click.option", "click.command", "logging.info", "utils.read_fasta", "numpy.array", "pandas.read_pickle", "collections.Counter", "numpy.random.shuffle" ]
[((178, 217), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO'}), '(level=logging.INFO)\n', (197, 217), False, 'import logging\n'), ((220, 232), 'click.command', 'ck.command', ([], {}), '()\n', (230, 232), True, 'import click as ck\n'), ((234, 338), 'click.option', 'ck.option', (['"""--go-file"""', '"""-gf"""'], {'default': '"""data-cafa3/go.obo"""', 'help': '"""Gene Ontology file in OBO Format"""'}), "('--go-file', '-gf', default='data-cafa3/go.obo', help=\n 'Gene Ontology file in OBO Format')\n", (243, 338), True, 'import click as ck\n'), ((344, 468), 'click.option', 'ck.option', (['"""--data-file"""', '"""-df"""'], {'default': '"""data-cafa3/swissprot_exp.pkl"""', 'help': '"""Uniprot KB, generated with uni2pandas.py"""'}), "('--data-file', '-df', default='data-cafa3/swissprot_exp.pkl',\n help='Uniprot KB, generated with uni2pandas.py')\n", (353, 468), True, 'import click as ck\n'), ((475, 601), 'click.option', 'ck.option', (['"""--sim-file"""', '"""-sf"""'], {'default': '"""data-cafa3/swissprot_exp.sim"""', 'help': '"""Sequence similarity generated with Diamond"""'}), "('--sim-file', '-sf', default='data-cafa3/swissprot_exp.sim', help\n ='Sequence similarity generated with Diamond')\n", (484, 601), True, 'import click as ck\n'), ((655, 688), 'utils.Ontology', 'Ontology', (['go_file'], {'with_rels': '(True)'}), '(go_file, with_rels=True)\n', (663, 688), False, 'from utils import Ontology, FUNC_DICT, NAMESPACES, read_fasta\n'), ((693, 718), 'logging.info', 'logging.info', (['"""GO loaded"""'], {}), "('GO loaded')\n", (705, 718), False, 'import logging\n'), ((729, 754), 'pandas.read_pickle', 'pd.read_pickle', (['data_file'], {}), '(data_file)\n', (743, 754), True, 'import pandas as pd\n'), ((888, 944), 'utils.read_fasta', 'read_fasta', (['"""data-cafa3/CAFA3_targets/targets_all.fasta"""'], {}), "('data-cafa3/CAFA3_targets/targets_all.fasta')\n", (898, 944), False, 'from utils import Ontology, FUNC_DICT, NAMESPACES, read_fasta\n'), ((2543, 2694), 'pandas.DataFrame', 'pd.DataFrame', (["{'proteins': targets, 'sequences': seqs, 'exp_annotations': exp_annotations,\n 'prop_annotations': prop_annotations, 'interpros': iprs}"], {}), "({'proteins': targets, 'sequences': seqs, 'exp_annotations':\n exp_annotations, 'prop_annotations': prop_annotations, 'interpros': iprs})\n", (2555, 2694), True, 'import pandas as pd\n'), ((2877, 2886), 'collections.Counter', 'Counter', ([], {}), '()\n', (2884, 2886), False, 'from collections import Counter\n'), ((2902, 2911), 'collections.Counter', 'Counter', ([], {}), '()\n', (2909, 2911), False, 'from collections import Counter\n'), ((4016, 4044), 'pandas.DataFrame', 'pd.DataFrame', (["{'gos': terms}"], {}), "({'gos': terms})\n", (4028, 4044), True, 'import pandas as pd\n'), ((4121, 4159), 'pandas.DataFrame', 'pd.DataFrame', (["{'interpros': interpros}"], {}), "({'interpros': interpros})\n", (4133, 4159), True, 'import pandas as pd\n'), ((5519, 5541), 'numpy.random.seed', 'np.random.seed', ([], {'seed': '(0)'}), '(seed=0)\n', (5533, 5541), True, 'import numpy as np\n'), ((5550, 5574), 'numpy.random.shuffle', 'np.random.shuffle', (['index'], {}), '(index)\n', (5567, 5574), True, 'import numpy as np\n'), ((5953, 5974), 'numpy.array', 'np.array', (['train_index'], {}), '(train_index)\n', (5961, 5974), True, 'import numpy as np\n'), ((5997, 6018), 'numpy.array', 'np.array', (['valid_index'], {}), '(valid_index)\n', (6005, 6018), True, 'import numpy as np\n')]
import sys import theano import numpy import collections import cPickle import lasagne sys.setrecursionlimit(50000) floatX=theano.config.floatX class WordPairClassifier(object): def __init__(self, config): self.config = config self.params = collections.OrderedDict() self.rng = numpy.random.RandomState(config["random_seed"]) word1_ids = theano.tensor.ivector('word1_ids') word2_ids = theano.tensor.ivector('word2_ids') label_ids = theano.tensor.ivector('label_ids') learningrate = theano.tensor.fscalar('learningrate') is_training = theano.tensor.iscalar('is_training') self.word_embedding_matrix_A = self.create_parameter_matrix('word_embedding_matrix_a', (config["n_words"], config["word_embedding_size_a"])) scores = self.construct_network(word1_ids, word2_ids, self.word_embedding_matrix_A, config["word_embedding_size_a"], self.config, "A") if config["late_fusion"] == True: self.word_embedding_matrix_B = self.create_parameter_matrix('word_embedding_matrix_b', (config["n_words"], config["word_embedding_size_b"])) scoresB = self.construct_network(word1_ids, word2_ids, self.word_embedding_matrix_B, config["word_embedding_size_b"], self.config, "B") gamma = theano.tensor.nnet.sigmoid(self.create_parameter_matrix('late_fusion_gamma', (1,)))[0] scores = gamma * scores + (1.0 - gamma) * scoresB cost = 0.0 label_ids_float = theano.tensor.cast(label_ids, 'float32') if config["cost"] == "mse": cost += ((scores - label_ids_float)*(scores - label_ids_float)).sum() elif config["cost"] == "hinge": difference = theano.tensor.abs_(scores - label_ids_float) se = (scores - label_ids_float)*(scores - label_ids_float) cost += theano.tensor.switch(theano.tensor.gt(difference, 0.4), se, 0.0).sum() predicted_labels = theano.tensor.switch(theano.tensor.ge(scores, 0.5), 1, 0) if config["update_embeddings"] == True: params_ = self.params else: params_ = self.params.copy() del params_['word_embedding_matrix_a'] if 'word_embedding_matrix_b' in params_: del params_['word_embedding_matrix_b'] if config["cost_l2"] > 0.0: for param in params_.values(): cost += config["cost_l2"] * theano.tensor.sum(param ** 2) gradients = theano.tensor.grad(cost, params_.values(), disconnected_inputs='ignore') if hasattr(lasagne.updates, config["optimisation_strategy"]): update_method = getattr(lasagne.updates, config["optimisation_strategy"]) else: raise ValueError("Optimisation strategy not implemented: " + str(config["optimisation_strategy"])) updates = update_method(gradients, params_.values(), learningrate) input_vars_test = [word1_ids, word2_ids, label_ids] input_vars_train = input_vars_test + [learningrate] output_vars = [cost, predicted_labels, scores] self.train = theano.function(input_vars_train, output_vars, updates=updates, on_unused_input='ignore', allow_input_downcast = True, givens=({is_training: numpy.cast['int32'](1)})) self.test = theano.function(input_vars_test, output_vars, on_unused_input='ignore', allow_input_downcast = True, givens=({is_training: numpy.cast['int32'](0)})) def construct_network(self, word1_ids, word2_ids, word_embedding_matrix, word_embedding_size, config, name): word1_embeddings = word_embedding_matrix[word1_ids] word2_embeddings = word_embedding_matrix[word2_ids] if config["gating"] == True: gating = theano.tensor.nnet.sigmoid(self.create_layer(word1_embeddings, word_embedding_size, word_embedding_size, name + "_gating")) word2_embeddings = word2_embeddings * gating if config["embedding_mapping_size"] > 0: word1_embeddings = theano.tensor.tanh(self.create_layer(word1_embeddings, word_embedding_size, config["embedding_mapping_size"], "word1_mapping_"+name)) word2_embeddings = theano.tensor.tanh(self.create_layer(word2_embeddings, word_embedding_size, config["embedding_mapping_size"], "word2_mapping_"+name)) word_embedding_size = config["embedding_mapping_size"] if config["embedding_combination"] == "concat": combination = theano.tensor.concatenate([word1_embeddings, word2_embeddings], axis=1) combination_size = 2*word_embedding_size elif config["embedding_combination"] == "multiply": combination = word1_embeddings * word2_embeddings combination_size = word_embedding_size elif config["embedding_combination"] == "add": combination = word1_embeddings + word2_embeddings combination_size = word_embedding_size else: raise ValueError("Unknown combination: " + config["embedding_combination"]) if config["hidden_layer_size"] > 0: combination = theano.tensor.tanh(self.create_layer(combination, combination_size, config["hidden_layer_size"], "hidden_"+name)) combination_size = config["hidden_layer_size"] scores = theano.tensor.nnet.sigmoid(self.create_layer(combination, combination_size, 1, "output_"+name)).reshape((word1_ids.shape[0],)) return scores def save(self, filename): dump = {} dump["config"] = self.config dump["params"] = {} for param_name in self.params: dump["params"][param_name] = self.params[param_name].get_value() f = file(filename, 'wb') cPickle.dump(dump, f, protocol=cPickle.HIGHEST_PROTOCOL) f.close() @staticmethod def load(filename, new_config=None, new_output_layer_size=None): f = file(filename, 'rb') dump = cPickle.load(f) f.close() model = WordPairClassifier(dump["config"]) for param_name in model.params: assert(param_name in dump["params"]) model.params[param_name].set_value(dump["params"][param_name]) return model def create_parameter_matrix(self, name, size): param_vals = numpy.asarray(self.rng.normal(loc=0.0, scale=0.1, size=size), dtype=floatX) self.params[name] = theano.shared(param_vals, name) return self.params[name] def create_layer(self, input_matrix, input_size, output_size, name): W = self.create_parameter_matrix(name + 'W', (input_size, output_size)) bias = self.create_parameter_matrix(name + 'bias', (output_size,)) result = theano.tensor.dot(input_matrix, W) + bias return result
[ "theano.tensor.fscalar", "theano.tensor.iscalar", "theano.tensor.concatenate", "theano.tensor.sum", "theano.tensor.dot", "theano.tensor.abs_", "theano.tensor.cast", "theano.tensor.ivector", "cPickle.load", "numpy.random.RandomState", "theano.tensor.gt", "cPickle.dump", "theano.shared", "th...
[((88, 116), 'sys.setrecursionlimit', 'sys.setrecursionlimit', (['(50000)'], {}), '(50000)\n', (109, 116), False, 'import sys\n'), ((263, 288), 'collections.OrderedDict', 'collections.OrderedDict', ([], {}), '()\n', (286, 288), False, 'import collections\n'), ((308, 355), 'numpy.random.RandomState', 'numpy.random.RandomState', (["config['random_seed']"], {}), "(config['random_seed'])\n", (332, 355), False, 'import numpy\n'), ((377, 411), 'theano.tensor.ivector', 'theano.tensor.ivector', (['"""word1_ids"""'], {}), "('word1_ids')\n", (398, 411), False, 'import theano\n'), ((432, 466), 'theano.tensor.ivector', 'theano.tensor.ivector', (['"""word2_ids"""'], {}), "('word2_ids')\n", (453, 466), False, 'import theano\n'), ((487, 521), 'theano.tensor.ivector', 'theano.tensor.ivector', (['"""label_ids"""'], {}), "('label_ids')\n", (508, 521), False, 'import theano\n'), ((545, 582), 'theano.tensor.fscalar', 'theano.tensor.fscalar', (['"""learningrate"""'], {}), "('learningrate')\n", (566, 582), False, 'import theano\n'), ((605, 641), 'theano.tensor.iscalar', 'theano.tensor.iscalar', (['"""is_training"""'], {}), "('is_training')\n", (626, 641), False, 'import theano\n'), ((1494, 1534), 'theano.tensor.cast', 'theano.tensor.cast', (['label_ids', '"""float32"""'], {}), "(label_ids, 'float32')\n", (1512, 1534), False, 'import theano\n'), ((5701, 5757), 'cPickle.dump', 'cPickle.dump', (['dump', 'f'], {'protocol': 'cPickle.HIGHEST_PROTOCOL'}), '(dump, f, protocol=cPickle.HIGHEST_PROTOCOL)\n', (5713, 5757), False, 'import cPickle\n'), ((5913, 5928), 'cPickle.load', 'cPickle.load', (['f'], {}), '(f)\n', (5925, 5928), False, 'import cPickle\n'), ((6361, 6392), 'theano.shared', 'theano.shared', (['param_vals', 'name'], {}), '(param_vals, name)\n', (6374, 6392), False, 'import theano\n'), ((1974, 2003), 'theano.tensor.ge', 'theano.tensor.ge', (['scores', '(0.5)'], {}), '(scores, 0.5)\n', (1990, 2003), False, 'import theano\n'), ((4450, 4521), 'theano.tensor.concatenate', 'theano.tensor.concatenate', (['[word1_embeddings, word2_embeddings]'], {'axis': '(1)'}), '([word1_embeddings, word2_embeddings], axis=1)\n', (4475, 4521), False, 'import theano\n'), ((6673, 6707), 'theano.tensor.dot', 'theano.tensor.dot', (['input_matrix', 'W'], {}), '(input_matrix, W)\n', (6690, 6707), False, 'import theano\n'), ((1718, 1762), 'theano.tensor.abs_', 'theano.tensor.abs_', (['(scores - label_ids_float)'], {}), '(scores - label_ids_float)\n', (1736, 1762), False, 'import theano\n'), ((2432, 2461), 'theano.tensor.sum', 'theano.tensor.sum', (['(param ** 2)'], {}), '(param ** 2)\n', (2449, 2461), False, 'import theano\n'), ((1875, 1908), 'theano.tensor.gt', 'theano.tensor.gt', (['difference', '(0.4)'], {}), '(difference, 0.4)\n', (1891, 1908), False, 'import theano\n')]
"""Sounscape is a subclass of scaper.Scaper to fulfill our specific needs and default values""" import glob import inspect import numpy as np import os import shutil import warnings from os import path as osp import scaper import soundfile as sf from .logger import create_logger, DesedWarning, DesedError from .utils import choose_cooccurence_class, create_folder class Soundscape(scaper.Scaper): """ Initialize scaper object with a reference dB and sr. Args: duration: float, in seconds, the duration of the generated audio clip. fg_path: str, path of foreground files (be careful, need subfolders, one per class or group) bg_path: str, path of background files (be careful, need subfolders, one per group) ref_db: float, the reference dB of the clip. samplerate: int, the sr of the final soundscape delete_if_exists: bool, whether to delete existing files and folders created with the same name. Returns: scaper.Scaper object """ def __init__( self, duration, fg_path, bg_path, ref_db=-55, samplerate=16000, random_state=None, delete_if_exists=True, ): super(Soundscape, self).__init__( duration, fg_path, bg_path, random_state=random_state ) self.ref_db = ref_db self.sr = samplerate if self.ref_db is not None: self.ref_db = ref_db if self.sr is not None: self.sr = samplerate self.delete_if_exists = delete_if_exists def add_random_background(self, label=None): """ Add a random background to a scaper object Args: label: str or list, possible labels are names the subfolders of self.bg_path. None can use them all. """ # If str or None, keep it like this if label is not None: if isinstance(label, list): bg_label = self.random_state.choice(label) elif isinstance(label, str): bg_label = label else: raise NotImplementedError( "Background label can only be a list of available labels or a string" ) else: bg_label = "*" chosen_file = self._choose_file(osp.join(self.bg_path, bg_label)) file_duration = sf.info(chosen_file).duration starting_source = min( self.random_state.rand() * file_duration, max(file_duration - self.duration, 0), ) self.add_background( label=("const", chosen_file.split("/")[-2]), source_file=("const", chosen_file), source_time=("const", starting_source), ) def add_fg_event_non_noff( self, label, snr=("uniform", 6, 30), pitch_shift=None, time_stretch=None, event_duration_min=0.25, ): """ add a single event to a scaper object given a class. Take into account if the event has an onset or offset Args: label: str, label of the event to add. snr: tuple, tuple accepted by Scaper().add_event() pitch_shift: tuple, tuple accepted by Scaper().add_event() time_stretch: tuple, tuple accepted by Scaper().add_event() event_duration_min: float, minimum duration of a foreground event (in second) Returns: sc, scaper.Scaper object with the event added. """ logger = create_logger(__name__ + "/" + inspect.currentframe().f_code.co_name) label_path = os.path.join(self.fg_path, label) assert osp.exists( label_path ), f"The label provided ({label}) does not point to a valid folder: {label_path}" chosen_file = self._choose_file(os.path.join(self.fg_path, label)) file_duration = round( sf.info(chosen_file).duration, 6 ) # because Scaper uses sox with truncate 6 digits if "_nOn_nOff" in label: # If no onset and offset, the file should be bigger than the duration of the file logger.debug("no onset/offset") if file_duration - self.duration <= 0: warnings.warn( "Event without onset and offset added not for the full time of the audio soundscape" ) source_start = 0 else: source_start = self.random_state.uniform( 0, file_duration - self.duration ) self.add_event( label=("const", label), source_file=("const", chosen_file), source_time=("const", source_start), event_time=("const", 0), event_duration=("const", self.duration), snr=snr, pitch_shift=pitch_shift, time_stretch=time_stretch, ) elif "_nOn" in label: logger.debug("no onset") if file_duration - event_duration_min <= 0: source_start = 0 else: source_start = self.random_state.uniform( 0, file_duration - event_duration_min ) self.add_event( label=("const", label), source_file=("const", chosen_file), source_time=("const", source_start), event_time=("const", 0), event_duration=( "const", np.minimum(self.duration, file_duration - source_start), ), snr=snr, pitch_shift=pitch_shift, time_stretch=time_stretch, ) elif "_nOff" in label: logger.debug("no offset") event_start = self.random_state.uniform( max(0, self.duration - file_duration), self.duration - event_duration_min, ) event_length = self.duration - event_start self.add_event( label=("const", label), source_file=("const", chosen_file), source_time=("const", 0), event_time=("const", event_start), event_duration=("const", event_length), snr=snr, pitch_shift=pitch_shift, time_stretch=time_stretch, ) else: logger.debug("onset offset") if file_duration > self.duration: if file_duration // self.duration > 2: choice = np.random.choice( ["onset", "middle", "offset"], p=[0.375, 0.25, 0.375] ) else: choice = np.random.choice(["onset", "offset"]) logger.debug(f"choice: {choice}") if choice == "onset": event_start = self.random_state.uniform( 0, self.duration - event_duration_min ) length_possible = self.duration - event_start event_length = ( file_duration if file_duration < length_possible else length_possible ) source_start = 0 elif choice == "offset": event_start = 0 event_length = self.random_state.uniform( 0, self.duration - event_duration_min ) source_start = file_duration - event_length else: source_start = self.random_state.uniform( self.duration, file_duration - self.duration ) event_start = 0 event_length = self.duration else: event_start = self.random_state.uniform( 0, self.duration - event_duration_min ) source_start = 0 length_possible = self.duration - event_start event_length = ( file_duration if file_duration < length_possible else length_possible ) logger.debug( f"event_start: {event_start}, length: {event_length}, source_start: {source_start}, " f"file_duration: {file_duration}" ) self.add_event( label=("const", label), source_file=("const", chosen_file), source_time=("const", source_start), event_time=("const", event_start), event_duration=("const", event_length), snr=snr, pitch_shift=pitch_shift, time_stretch=time_stretch, ) return self def _choose_file(self, class_path, non_noff=False): """ Choose randomly a file of a given class. Args: class_path: str, path of the class containing all the files of a certain class. Returns: str, path of the file. """ event_files = sorted(glob.glob(os.path.join(class_path, "*"))) if non_noff: event_files.append(glob.glob(os.path.join(class_path + "_nOn", "*"))) event_files.append(glob.glob(os.path.join(class_path + "_nOff", "*"))) event_files.append(glob.glob(os.path.join(class_path + "_nOn_nOff", "*"))) event_files = sorted(event_files) event_files = [f for f in event_files if os.path.isfile(f)] assert len(event_files) > 0, ( f"no event files to be chosen in this path: {os.path.join(class_path, '*')}" f" (pattern used by glob)" ) ind = self.random_state.randint(0, len(event_files)) return event_files[ind] def _remove(self, path): if osp.exists(path): if osp.isdir(path): shutil.rmtree(path) elif osp.isfile(path): os.remove(path) else: raise NotImplementedError("Can only remove files or folders") def generate_co_occurence( self, co_occur_params, label, out_folder, filename, min_events=1, max_events=None, reverb=None, save_isolated_events=False, snr=("uniform", 6, 30), pitch_shift=None, time_stretch=None, bg_labels=None, **kwargs, ): """ Generate a single file, using the information of onset or offset present (see DESED dataset and folders in soundbank foreground) Args: co_occur_params: dict, dict containing information about how to mix classes, and the probability of each class. label: str, the main foreground label of the generated file. out_folder: str, path to extract generate file filename: str, name of the generated file, without extension (.wav, .jams and .txt will be created) min_events: int, optional, the minimum number of events per files (default=1, >= 1) (Be careful, if max_events in label_occurences params is less than this it will raise an error) If defined in the label_occurences dict, this parameter corresponds to the number of cooccurences. max_events: int, optional, if defined, overwrite the value in label_occurences if defined (in label_occurences this parameter corresponds to the number of cooccurences). reverb: float, the reverb to be applied to the foreground events save_isolated_events: bool, whether or not to save isolated events in a subfolder (called <filename>_events by default) snr: tuple, tuple accepted by Scaper().add_event() pitch_shift: tuple, tuple accepted by Scaper().add_event() time_stretch: tuple, tuple accepted by Scaper().add_event() bg_labels: list or str, if None choose in all available files. If a name or list is given it has to match the name of a folder in 'background'. example: "sins" kwargs: arguments accepted by Scaper.generate Returns: None Examples: Example of co_occur_params dictionary:: { "max_events": 13, "classes": [ "Alarm_bell_ringing", "Dog", ], "probas": [ 70, 30 ] } prob is the probability of this class (not used here) """ create_folder(out_folder) self.add_random_background(bg_labels) # add main event, non_noff stands for no onset and no offset (accept label to have _nOn or _nOff specified). self.add_fg_event_non_noff( label, snr=snr, pitch_shift=pitch_shift, time_stretch=time_stretch ) if max_events is None: max_events = co_occur_params.get("max_events") if max_events is None: raise DesedError("max_events has to be specified") else: max_events = max_events - 1 if min_events is None: min_events = co_occur_params.get("min_events") if min_events is None: raise DesedError( "min_events has to be specified in generate co occurence or in params" ) else: min_events = min_events - 1 # add random number of foreground events if min_events == max_events: n_events = min_events else: n_events = self.random_state.randint(min_events, max_events) for _ in range(n_events): chosen_class = choose_cooccurence_class( co_occur_params, random_state=self.random_state ) self.add_fg_event_non_noff( chosen_class, snr=snr, pitch_shift=pitch_shift, time_stretch=time_stretch, ) # Just in case an extension has been added ext = osp.splitext(filename)[-1] if ext in [".wav", ".jams", ".txt"]: filename = osp.splitext(filename)[0] # generate audio_file = osp.join(out_folder, f"{filename}.wav") jams_file = osp.join(out_folder, f"{filename}.jams") txt_file = osp.join(out_folder, f"{filename}.txt") if self.delete_if_exists: self._remove(audio_file) self._remove(jams_file) self._remove(txt_file) # To get isolated events in a subfolder isolated_events_path = kwargs.get("isolated_events_path") if save_isolated_events: if isolated_events_path is None: isolated_events_path = osp.join(out_folder, f"{filename}_events") if self.delete_if_exists: self._remove(isolated_events_path) else: if osp.exists(isolated_events_path): warnings.warn( f"The folder {isolated_events_path} already exists, it means there could be some " f"unwanted audio files from previous generated audio files in it.", DesedWarning, ) self.generate( audio_file, jams_file, reverb=reverb, txt_path=txt_file, save_isolated_events=save_isolated_events, isolated_events_path=isolated_events_path, **kwargs, ) def generate_using_non_noff( self, label, list_labels, out_folder, filename, n_events, reverb=None, save_isolated_events=False, snr=("uniform", 6, 30), pitch_shift=None, time_stretch=None, bg_labels=None, **kwargs, ): """ Generate a single file, using the information of onset or offset present (see DESED dataset and folders in soundbank foreground) Args: label: str, the main foreground label of the generated file. list_labels: list, the list of available labels out_folder: str, path to extract generate file filename: str, name of the generated file, without extension (.wav, .jams and .txt will be created) n_events: int, the of events in the soundscape reverb: float, the reverb to be applied to the foreground events save_isolated_events: bool, whether or not to save isolated events in a subfolder (called <filename>_events by default) snr: tuple, tuple accepted by Scaper().add_event() pitch_shift: tuple, tuple accepted by Scaper().add_event() time_stretch: tuple, tuple accepted by Scaper().add_event() bg_labels: list, if None choose in all available files. If a name is given it has to match the name of a folder in 'background'. example: ["sins"] kwargs: arguments accepted by Scaper.generate Returns: None """ create_folder(out_folder) self.add_random_background(bg_labels) if n_events > 0: # add main event, non_noff stands for no onset and no offset (accept label to have _nOn or _nOff specified). self.add_fg_event_non_noff( label, snr=snr, pitch_shift=pitch_shift, time_stretch=time_stretch ) for _ in range(n_events - 1): chosen_class = self.random_state.choice(list_labels) self.add_fg_event_non_noff( chosen_class, snr=snr, pitch_shift=pitch_shift, time_stretch=time_stretch, ) # Just in case an extension has been added ext = osp.splitext(filename)[-1] if ext in [".wav", ".jams", ".txt"]: filename = osp.splitext(filename)[0] # generate audio_file = osp.join(out_folder, f"{filename}.wav") jams_file = osp.join(out_folder, f"{filename}.jams") txt_file = osp.join(out_folder, f"{filename}.txt") if self.delete_if_exists: self._remove(audio_file) self._remove(jams_file) self._remove(txt_file) # To get isolated events in a subfolder isolated_events_path = kwargs.get("isolated_events_path") if save_isolated_events: if isolated_events_path is None: isolated_events_path = osp.join(out_folder, f"{filename}_events") if self.delete_if_exists: self._remove(isolated_events_path) else: if osp.exists(isolated_events_path): warnings.warn( f"The folder {isolated_events_path} already exists, it means there could be some " f"unwanted audio files from previous generated audio files in it.", DesedWarning, ) self.generate( audio_file, jams_file, reverb=reverb, txt_path=txt_file, save_isolated_events=save_isolated_events, isolated_events_path=isolated_events_path, **kwargs, ) def generate_one_bg_multi_fg( self, out_folder, filename, n_fg_events, labels=("choose", []), source_files=("choose", []), sources_time=("const", 0), events_start=("truncnorm", 5.0, 2.0, 0.0, 10.0), events_duration=("uniform", 0.25, 10.0), snrs=("uniform", 6, 30), pitch_shifts=("uniform", -3.0, 3.0), time_stretches=("uniform", 1, 1), reverb=0.1, txt_file=True, save_isolated_events=False, isolated_events_path=None, bg_labels=None, **kwargs, ): """ Generate a clip with a background file and multiple foreground files. Args: out_folder: str, path to extract generate file filename: str, name of the generated file, without extension (.wav, .jams and .txt will be created) n_fg_events: int, the number of foreground events to add labels: tuple or list, distribution to choose foreground events or list of events.* source_files: tuple or list, distribution to choose source files or list of source files.* sources_time: tuple or list, distribution to choose source start time or list of sources start time.* events_start: tuple or list, distribution to choose events start time or list of events start time.* events_duration: tuple or list, distribution to choose events duation or list of events duration.* snrs: tuple or list, distribution to choose foreground to background SNRs or list of SNRs.* pitch_shifts: tuple or list, distribution to choose pitch shift or list of pitch shifts.* time_stretches: tuple or list, distribution to choose time stretches or list of time stretches.* reverb: float, the reverb to be applied to the foreground events txt_file: bool, whether or not to save the .txt file. save_isolated_events: bool, whether or not to save isolated events in a separate folder isolated_events_path: str, only useful when save_isolated_events=True. Give the path to the events folders. If None, a folder is created next to the audio files. bg_labels: list, if None choose in all available files. If a name is given it has to match the name of a folder in 'background'. example: ["sins"] kwargs: arguments accepted by Scaper.generate * All arguments with asterix, if tuple given, see Scaper for distribution allowed. Returns: None """ create_folder(out_folder) self.add_random_background(bg_labels) params = { "label": labels, "source_file": source_files, "source_time": sources_time, "event_time": events_start, "event_duration": events_duration, "snr": snrs, "pitch_shift": pitch_shifts, "time_stretch": time_stretches, } # Make sure that if we give a list of tuple for a parameter that the length of the list # is matching the number of foreground events for i in range(n_fg_events): event_params = {} for key in params: if params[key] is None or isinstance(params[key], tuple): param = params[key] elif type(params[key]) is list: assert len(params[key]) == n_fg_events if not isinstance(params[key][i], tuple): param = ("const", params[key][i]) else: param = params[key][i] else: raise NotImplementedError( "Params of events is tuple(same for all) or " "list (different for each event)" ) event_params[key] = param self.add_event(**event_params) # generate audiofile = osp.join(out_folder, f"{filename}.wav") jamsfile = osp.join(out_folder, f"{filename}.jams") if self.delete_if_exists: self._remove(audiofile) self._remove(jamsfile) if txt_file: # Can be useless if you want background annotation as well, see post_processing_annotations. txtfile = osp.join(out_folder, f"{filename}.txt") if self.delete_if_exists: self._remove(txtfile) else: txtfile = None if save_isolated_events: if isolated_events_path is None: isolated_events_path = osp.join(out_folder, f"{filename}_events") if self.delete_if_exists: self._remove(isolated_events_path) self.generate( audio_path=audiofile, jams_path=jamsfile, reverb=reverb, txt_path=txtfile, save_isolated_events=save_isolated_events, isolated_events_path=isolated_events_path, **kwargs, )
[ "numpy.random.choice", "os.remove", "soundfile.info", "numpy.minimum", "shutil.rmtree", "os.path.isdir", "os.path.exists", "os.path.isfile", "os.path.splitext", "inspect.currentframe", "warnings.warn", "os.path.join" ]
[((3672, 3705), 'os.path.join', 'os.path.join', (['self.fg_path', 'label'], {}), '(self.fg_path, label)\n', (3684, 3705), False, 'import os\n'), ((3721, 3743), 'os.path.exists', 'osp.exists', (['label_path'], {}), '(label_path)\n', (3731, 3743), True, 'from os import path as osp\n'), ((10071, 10087), 'os.path.exists', 'osp.exists', (['path'], {}), '(path)\n', (10081, 10087), True, 'from os import path as osp\n'), ((14587, 14626), 'os.path.join', 'osp.join', (['out_folder', 'f"""{filename}.wav"""'], {}), "(out_folder, f'{filename}.wav')\n", (14595, 14626), True, 'from os import path as osp\n'), ((14647, 14687), 'os.path.join', 'osp.join', (['out_folder', 'f"""{filename}.jams"""'], {}), "(out_folder, f'{filename}.jams')\n", (14655, 14687), True, 'from os import path as osp\n'), ((14707, 14746), 'os.path.join', 'osp.join', (['out_folder', 'f"""{filename}.txt"""'], {}), "(out_folder, f'{filename}.txt')\n", (14715, 14746), True, 'from os import path as osp\n'), ((18379, 18418), 'os.path.join', 'osp.join', (['out_folder', 'f"""{filename}.wav"""'], {}), "(out_folder, f'{filename}.wav')\n", (18387, 18418), True, 'from os import path as osp\n'), ((18439, 18479), 'os.path.join', 'osp.join', (['out_folder', 'f"""{filename}.jams"""'], {}), "(out_folder, f'{filename}.jams')\n", (18447, 18479), True, 'from os import path as osp\n'), ((18499, 18538), 'os.path.join', 'osp.join', (['out_folder', 'f"""{filename}.txt"""'], {}), "(out_folder, f'{filename}.txt')\n", (18507, 18538), True, 'from os import path as osp\n'), ((23703, 23742), 'os.path.join', 'osp.join', (['out_folder', 'f"""{filename}.wav"""'], {}), "(out_folder, f'{filename}.wav')\n", (23711, 23742), True, 'from os import path as osp\n'), ((23762, 23802), 'os.path.join', 'osp.join', (['out_folder', 'f"""{filename}.jams"""'], {}), "(out_folder, f'{filename}.jams')\n", (23770, 23802), True, 'from os import path as osp\n'), ((2378, 2410), 'os.path.join', 'osp.join', (['self.bg_path', 'bg_label'], {}), '(self.bg_path, bg_label)\n', (2386, 2410), True, 'from os import path as osp\n'), ((2436, 2456), 'soundfile.info', 'sf.info', (['chosen_file'], {}), '(chosen_file)\n', (2443, 2456), True, 'import soundfile as sf\n'), ((3886, 3919), 'os.path.join', 'os.path.join', (['self.fg_path', 'label'], {}), '(self.fg_path, label)\n', (3898, 3919), False, 'import os\n'), ((10104, 10119), 'os.path.isdir', 'osp.isdir', (['path'], {}), '(path)\n', (10113, 10119), True, 'from os import path as osp\n'), ((14425, 14447), 'os.path.splitext', 'osp.splitext', (['filename'], {}), '(filename)\n', (14437, 14447), True, 'from os import path as osp\n'), ((18217, 18239), 'os.path.splitext', 'osp.splitext', (['filename'], {}), '(filename)\n', (18229, 18239), True, 'from os import path as osp\n'), ((24058, 24097), 'os.path.join', 'osp.join', (['out_folder', 'f"""{filename}.txt"""'], {}), "(out_folder, f'{filename}.txt')\n", (24066, 24097), True, 'from os import path as osp\n'), ((3964, 3984), 'soundfile.info', 'sf.info', (['chosen_file'], {}), '(chosen_file)\n', (3971, 3984), True, 'import soundfile as sf\n'), ((4295, 4404), 'warnings.warn', 'warnings.warn', (['"""Event without onset and offset added not for the full time of the audio soundscape"""'], {}), "(\n 'Event without onset and offset added not for the full time of the audio soundscape'\n )\n", (4308, 4404), False, 'import warnings\n'), ((9340, 9369), 'os.path.join', 'os.path.join', (['class_path', '"""*"""'], {}), "(class_path, '*')\n", (9352, 9369), False, 'import os\n'), ((9741, 9758), 'os.path.isfile', 'os.path.isfile', (['f'], {}), '(f)\n', (9755, 9758), False, 'import os\n'), ((9856, 9885), 'os.path.join', 'os.path.join', (['class_path', '"""*"""'], {}), "(class_path, '*')\n", (9868, 9885), False, 'import os\n'), ((10137, 10156), 'shutil.rmtree', 'shutil.rmtree', (['path'], {}), '(path)\n', (10150, 10156), False, 'import shutil\n'), ((10174, 10190), 'os.path.isfile', 'osp.isfile', (['path'], {}), '(path)\n', (10184, 10190), True, 'from os import path as osp\n'), ((14520, 14542), 'os.path.splitext', 'osp.splitext', (['filename'], {}), '(filename)\n', (14532, 14542), True, 'from os import path as osp\n'), ((15122, 15164), 'os.path.join', 'osp.join', (['out_folder', 'f"""{filename}_events"""'], {}), "(out_folder, f'{filename}_events')\n", (15130, 15164), True, 'from os import path as osp\n'), ((15291, 15323), 'os.path.exists', 'osp.exists', (['isolated_events_path'], {}), '(isolated_events_path)\n', (15301, 15323), True, 'from os import path as osp\n'), ((18312, 18334), 'os.path.splitext', 'osp.splitext', (['filename'], {}), '(filename)\n', (18324, 18334), True, 'from os import path as osp\n'), ((18914, 18956), 'os.path.join', 'osp.join', (['out_folder', 'f"""{filename}_events"""'], {}), "(out_folder, f'{filename}_events')\n", (18922, 18956), True, 'from os import path as osp\n'), ((19083, 19115), 'os.path.exists', 'osp.exists', (['isolated_events_path'], {}), '(isolated_events_path)\n', (19093, 19115), True, 'from os import path as osp\n'), ((24333, 24375), 'os.path.join', 'osp.join', (['out_folder', 'f"""{filename}_events"""'], {}), "(out_folder, f'{filename}_events')\n", (24341, 24375), True, 'from os import path as osp\n'), ((9434, 9472), 'os.path.join', 'os.path.join', (["(class_path + '_nOn')", '"""*"""'], {}), "(class_path + '_nOn', '*')\n", (9446, 9472), False, 'import os\n'), ((9516, 9555), 'os.path.join', 'os.path.join', (["(class_path + '_nOff')", '"""*"""'], {}), "(class_path + '_nOff', '*')\n", (9528, 9555), False, 'import os\n'), ((9599, 9642), 'os.path.join', 'os.path.join', (["(class_path + '_nOn_nOff')", '"""*"""'], {}), "(class_path + '_nOn_nOff', '*')\n", (9611, 9642), False, 'import os\n'), ((10208, 10223), 'os.remove', 'os.remove', (['path'], {}), '(path)\n', (10217, 10223), False, 'import os\n'), ((15345, 15529), 'warnings.warn', 'warnings.warn', (['f"""The folder {isolated_events_path} already exists, it means there could be some unwanted audio files from previous generated audio files in it."""', 'DesedWarning'], {}), "(\n f'The folder {isolated_events_path} already exists, it means there could be some unwanted audio files from previous generated audio files in it.'\n , DesedWarning)\n", (15358, 15529), False, 'import warnings\n'), ((19137, 19321), 'warnings.warn', 'warnings.warn', (['f"""The folder {isolated_events_path} already exists, it means there could be some unwanted audio files from previous generated audio files in it."""', 'DesedWarning'], {}), "(\n f'The folder {isolated_events_path} already exists, it means there could be some unwanted audio files from previous generated audio files in it.'\n , DesedWarning)\n", (19150, 19321), False, 'import warnings\n'), ((3612, 3634), 'inspect.currentframe', 'inspect.currentframe', ([], {}), '()\n', (3632, 3634), False, 'import inspect\n'), ((5612, 5667), 'numpy.minimum', 'np.minimum', (['self.duration', '(file_duration - source_start)'], {}), '(self.duration, file_duration - source_start)\n', (5622, 5667), True, 'import numpy as np\n'), ((6686, 6757), 'numpy.random.choice', 'np.random.choice', (["['onset', 'middle', 'offset']"], {'p': '[0.375, 0.25, 0.375]'}), "(['onset', 'middle', 'offset'], p=[0.375, 0.25, 0.375])\n", (6702, 6757), True, 'import numpy as np\n'), ((6855, 6892), 'numpy.random.choice', 'np.random.choice', (["['onset', 'offset']"], {}), "(['onset', 'offset'])\n", (6871, 6892), True, 'import numpy as np\n')]
''' Representation learning testing for TCGA data. Set all parameters in this script & run with parameter "batch" or "local". ''' import numpy as np import logging import datetime #import argparse from common import expInterp, ensure_dir_exists import dataReader import batch from readHDF5 import getHDF5data #optional imports for data visualization #import matplotlib.pyplot as plt #import pylab ########################################################################################## # SETUP ########################################################################################## #set the following parameter values # logging configuration logging.basicConfig(level=logging.INFO) # input dataset #data_set = "TCGA_geneexpr_filtered_redistributed" #data_type = 'redistributed_gene_expressions' data_set = "TCGA_geneexpr_filtered" data_type = 'rnaseq_tpm_rle_log2_gene_expressions' # size of the representation to be learned repr_dims = [10] algs_to_run = 'all' n_epochs = 2000 deadline = None #max_duration = None #max_duration = datetime.timedelta(hours=1) max_duration = datetime.timedelta(hours=4) batch_size = 64 normalize_data = True #validation_split = 0 validation_split = 0.2 early_stopping = True # logging settings (what to log) log_weights = False # save predicted values (i.e. first encoded then decoded ) in to a file? save_pred = False algorithms = [] # PCA alg = ( "pca", "PCA (principal component analysis)", lambda input_dim, repr_dim: __import__('models.pca').pca.PCA().init( input_dim = input_dim, output_dim = repr_dim) ) algorithms.append(alg) # Linear AE alg = ( "ae0_linear", "Linear autoencoder", lambda input_dim, repr_dim: __import__('models.ae').ae.AE().init( input_dim = input_dim, enc_dims = [], output_dim = repr_dim, dec_dims = "same", enc_activations = 'linear', dec_activations = 'linear', n_epochs = n_epochs, batch_size = batch_size, optimizer='Adam', log_weights=log_weights) ) algorithms.append(alg) optimizer = 'Adam' # one hidden layer '''hidden_dim_mult = 64 alg = ( "ae1_%sxR_dropout12_%s" % (hidden_dim_mult, optimizer), "Two layer autoencoder", lambda input_dim, repr_dim, optimizer=optimizer, hidden_dim_mult=hidden_dim_mult: __import__('models.ae').ae.AE().init( input_dim = input_dim, enc_dims = [hidden_dim_mult*repr_dim], output_dim = repr_dim, dec_dims = "same", enc_activations = ['prelu', 'linear'], dec_activations = ['prelu', 'linear'], dropout=[0.1, 0.2], n_epochs = n_epochs, batch_size = batch_size, optimizer=optimizer, early_stopping=early_stopping, log_weights=log_weights, log_weights_diff_norm=2) ) algorithms.append(alg) # two hidden layers first_hidden_dim_mult = 32 alg = ( "ae2_%sxR_dropout12_%s" % (first_hidden_dim_mult, optimizer), "Three layer autoencoder", lambda input_dim, repr_dim, optimizer=optimizer, first_hidden_dim_mult=first_hidden_dim_mult: __import__('models.ae').ae.AE().init( input_dim = input_dim, enc_dims = [first_hidden_dim_mult*repr_dim, 4*repr_dim], output_dim = repr_dim, dec_dims = "same", enc_activations = ['prelu', 'prelu', 'linear'], dec_activations = ['prelu', 'prelu', 'linear'], dropout=[0.1, 0.2, 0.2], n_epochs = n_epochs, batch_size = batch_size, optimizer=optimizer, early_stopping=early_stopping, log_weights=log_weights, log_weights_diff_norm=2) ) algorithms.append(alg) # three hidden layers first_hidden_dim_mult = 32 alg = ( "ae3_%sxR_dropout12_%s" % (first_hidden_dim_mult, optimizer), "Four layer autoencoder", lambda input_dim, repr_dim, optimizer=optimizer, first_hidden_dim_mult=first_hidden_dim_mult: __import__('models.ae').ae.AE().init( input_dim = input_dim, enc_dims = [first_hidden_dim_mult*repr_dim, 4*repr_dim, 4*repr_dim], output_dim = repr_dim, dec_dims = "same", enc_activations = ['prelu', 'prelu', 'prelu', 'linear'], dec_activations = ['prelu', 'prelu', 'prelu', 'linear'], dropout=[0.1, 0.2, 0.2, 0.2], n_epochs = n_epochs, batch_size = batch_size, optimizer=optimizer, early_stopping=early_stopping, log_weights=log_weights, log_weights_diff_norm=2) ) algorithms.append(alg)''' # more layers if False: #for optimizer in ['Adam']: for n_hidden_layers in [3, 4, 5, 6, 7, 8]: #for n_hidden_layers in [5]: for max_hidden_dim_mult in [8, 16, 32]: #for max_hidden_dim_mult in [8]: common_params = dict( dec_dims = "same", enc_activations = n_hidden_layers * ['prelu'] + ['linear'], dec_activations = n_hidden_layers * ['prelu'] + ['linear'], n_epochs = n_epochs, batch_size = batch_size, optimizer = optimizer, log_weights = log_weights, log_weights_diff_norm = 2 ) enc_dim_mults = [max(max_hidden_dim_mult,2**a) for a in range(n_hidden_layers,0,-1)] alg = ( "ae%db_%sxR_dropout25_%s" % (n_hidden_layers, max_hidden_dim_mult, optimizer), "%d-layer autoencoder" % (n_hidden_layers), lambda input_dim, repr_dim, common_params=common_params, enc_dim_mults=enc_dim_mults: __import__('models.ae').ae.AE().init( **common_params, **dict( input_dim = input_dim, enc_dims = [a*repr_dim for a in enc_dim_mults], output_dim = repr_dim, dropout = [0.2] + n_hidden_layers * [0.5] ) ) ) algorithms.append(alg) alg = ( "ae%db_%sxR_dropout12_%s" % (n_hidden_layers, max_hidden_dim_mult, optimizer), "%d-layer autoencoder" % (n_hidden_layers), lambda input_dim, repr_dim, common_params=common_params, enc_dim_mults=enc_dim_mults: __import__('models.ae').ae.AE().init( **common_params, **dict( input_dim = input_dim, enc_dims = [a*repr_dim for a in enc_dim_mults], output_dim = repr_dim, dropout = [0.1] + n_hidden_layers * [0.2] ) ) ) algorithms.append(alg) alg = ( "ae%db_%sxR_batchnorm_%s" % (n_hidden_layers, max_hidden_dim_mult, optimizer), "%d-layer autoencoder" % (n_hidden_layers), lambda input_dim, repr_dim, common_params=common_params, enc_dim_mults=enc_dim_mults: __import__('models.ae').ae.AE().init( **common_params, **dict( input_dim = input_dim, enc_dims = [a*repr_dim for a in enc_dim_mults], output_dim = repr_dim, batch_normalization=True, ) ) ) algorithms.append(alg) if algs_to_run != "all": algorithms = [a for a in algorithms if (a[0] in algs_to_run)] ########################################################################################## # END OF SETUP ########################################################################################## def mean_squared_error(x, x_pred): #from sklearn import metrics #mse = metrics.mean_squared_error(x, x_pred, # multioutput='uniform_average') #explained_var = metrics.explained_variance_score(x, x_pred, # multioutput='uniform_average') #return np.average(np.average((x - x_pred) ** 2, axis=0)) return np.average((x - x_pred) ** 2) def relative_mean_squared_error(x, x_pred): mse = mean_squared_error(x, x_pred) x_avg = np.average(x, axis=0) #return mse / np.average(np.average((x - x_avg) ** 2, axis=0)) return mse / np.average((x - x_avg) ** 2) # the task function that is run with each argument combination def task(args): import pandas repr_dim, (alg_id, _, make_alg) = args logging.info("dataset = %s, algorithm = %s", data_set, alg_id) # read the data sets logging.info("Reading data...") #x = getHDF5data("data/%s.h5" % (data_set), True, True)[0] ## transpose and redo the log transform #x = x.T #x = np.log1p(x) data = pandas.read_hdf("data/%s.h5" % (data_set), data_type) x = data.as_matrix() logging.info(" * data shape: %d x %d" % x.shape) #x = x[:,0:20] # FIXME: POISTA # normalize the input to _total_ unit variance and per-feature zero mean if normalize_data: x -= np.mean(x) x /= np.std(x) x -= np.mean(x, axis=0) # init rng np.random.seed(0) # separate validation set if needed val_x = None if validation_split: logging.info("Splitting into training and validation sets") m = x.shape[0] perm = np.random.permutation(m) x = x[perm,:] split_point = int(validation_split * m) (val_x, x) = (x[:split_point,:], x[split_point:,:]) logging.info(" * training set shape: %d x %d" % x.shape) logging.info(" * validation set shape: %d x %d" % val_x.shape) data_dim = x.shape[1] logging.info(" * data shape after preprocessing: %d x %d" % x.shape) logging.info("Running the algorithm...") logging.info(" * learning a representation of size %d", repr_dim) # init the algorithm alg = make_alg(data_dim, repr_dim) # create output dir if does not exist ensure_dir_exists('res') # define the progress saving function progress_filename = 'res/progress-encdec-mse-%s-%d-%s.txt' % (data_set, repr_dim, alg_id) progress_file = open(progress_filename, 'w', encoding='utf-8') if val_x is not None: val_progress_filename = 'res/progress-encdec-validation-mse-%s-%d-%s.txt' % (data_set, repr_dim, alg_id) val_progress_file = open(val_progress_filename, 'w', encoding='utf-8') def save_progress(): x_pred = alg.decode(alg.encode(x)) rel_mse = relative_mean_squared_error(x, x_pred) progress_file.write("%g\n" % rel_mse) if val_x is not None: val_x_pred = alg.decode(alg.encode(val_x)) rel_mse = relative_mean_squared_error(val_x, val_x_pred) val_progress_file.write("%g\n" % rel_mse) callbacks = [] # add stopping callback if deadline is not None: from models.nncommon import TimeBasedStopping callbacks.append(TimeBasedStopping(deadline=deadline, verbose=1)) elif max_duration is not None: from models.nncommon import TimeBasedStopping callbacks.append(TimeBasedStopping(max_duration=max_duration, verbose=1)) # fit to the training data alg.learn(x, validation_data=val_x, log_file_prefix=("log/%s-%d-%s" % (data_set, repr_dim, alg_id)), per_epoch_callback_funs=[save_progress], callbacks=callbacks) # save model logging.info("Saving the learned model...") ensure_dir_exists('repr_models') alg.save("repr_models/%s-%d-%s" % (data_set, repr_dim, alg_id)) ########## MAIN ########## # init and run batch.init(task=task, args_ranges=(repr_dims, algorithms)) batch.main() # try to workaround a bug that tensorflow randomly throws an exception in the end # this seems to be the same: https://github.com/tensorflow/tensorflow/issues/3745 # possibly also this: https://github.com/tensorflow/tensorflow/issues/3388 from sys import modules if "keras.backend.tensorflow_backend" in modules: import keras.backend keras.backend.clear_session()
[ "models.nncommon.TimeBasedStopping", "numpy.average", "pandas.read_hdf", "logging.basicConfig", "numpy.random.seed", "numpy.std", "batch.main", "logging.info", "numpy.mean", "datetime.timedelta", "numpy.random.permutation", "common.ensure_dir_exists", "batch.init" ]
[((653, 692), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO'}), '(level=logging.INFO)\n', (672, 692), False, 'import logging\n'), ((1089, 1116), 'datetime.timedelta', 'datetime.timedelta', ([], {'hours': '(4)'}), '(hours=4)\n', (1107, 1116), False, 'import datetime\n'), ((10932, 10990), 'batch.init', 'batch.init', ([], {'task': 'task', 'args_ranges': '(repr_dims, algorithms)'}), '(task=task, args_ranges=(repr_dims, algorithms))\n', (10942, 10990), False, 'import batch\n'), ((10991, 11003), 'batch.main', 'batch.main', ([], {}), '()\n', (11001, 11003), False, 'import batch\n'), ((7595, 7624), 'numpy.average', 'np.average', (['((x - x_pred) ** 2)'], {}), '((x - x_pred) ** 2)\n', (7605, 7624), True, 'import numpy as np\n'), ((7718, 7739), 'numpy.average', 'np.average', (['x'], {'axis': '(0)'}), '(x, axis=0)\n', (7728, 7739), True, 'import numpy as np\n'), ((7988, 8050), 'logging.info', 'logging.info', (['"""dataset = %s, algorithm = %s"""', 'data_set', 'alg_id'], {}), "('dataset = %s, algorithm = %s', data_set, alg_id)\n", (8000, 8050), False, 'import logging\n'), ((8076, 8107), 'logging.info', 'logging.info', (['"""Reading data..."""'], {}), "('Reading data...')\n", (8088, 8107), False, 'import logging\n'), ((8250, 8301), 'pandas.read_hdf', 'pandas.read_hdf', (["('data/%s.h5' % data_set)", 'data_type'], {}), "('data/%s.h5' % data_set, data_type)\n", (8265, 8301), False, 'import pandas\n'), ((8329, 8377), 'logging.info', 'logging.info', (["(' * data shape: %d x %d' % x.shape)"], {}), "(' * data shape: %d x %d' % x.shape)\n", (8341, 8377), False, 'import logging\n'), ((8595, 8612), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (8609, 8612), True, 'import numpy as np\n'), ((9086, 9154), 'logging.info', 'logging.info', (["(' * data shape after preprocessing: %d x %d' % x.shape)"], {}), "(' * data shape after preprocessing: %d x %d' % x.shape)\n", (9098, 9154), False, 'import logging\n'), ((9158, 9198), 'logging.info', 'logging.info', (['"""Running the algorithm..."""'], {}), "('Running the algorithm...')\n", (9170, 9198), False, 'import logging\n'), ((9201, 9266), 'logging.info', 'logging.info', (['""" * learning a representation of size %d"""', 'repr_dim'], {}), "(' * learning a representation of size %d', repr_dim)\n", (9213, 9266), False, 'import logging\n'), ((9375, 9399), 'common.ensure_dir_exists', 'ensure_dir_exists', (['"""res"""'], {}), "('res')\n", (9392, 9399), False, 'from common import expInterp, ensure_dir_exists\n'), ((10742, 10785), 'logging.info', 'logging.info', (['"""Saving the learned model..."""'], {}), "('Saving the learned model...')\n", (10754, 10785), False, 'import logging\n'), ((10788, 10820), 'common.ensure_dir_exists', 'ensure_dir_exists', (['"""repr_models"""'], {}), "('repr_models')\n", (10805, 10820), False, 'from common import expInterp, ensure_dir_exists\n'), ((7820, 7848), 'numpy.average', 'np.average', (['((x - x_avg) ** 2)'], {}), '((x - x_avg) ** 2)\n', (7830, 7848), True, 'import numpy as np\n'), ((8519, 8529), 'numpy.mean', 'np.mean', (['x'], {}), '(x)\n', (8526, 8529), True, 'import numpy as np\n'), ((8539, 8548), 'numpy.std', 'np.std', (['x'], {}), '(x)\n', (8545, 8548), True, 'import numpy as np\n'), ((8558, 8576), 'numpy.mean', 'np.mean', (['x'], {'axis': '(0)'}), '(x, axis=0)\n', (8565, 8576), True, 'import numpy as np\n'), ((8696, 8755), 'logging.info', 'logging.info', (['"""Splitting into training and validation sets"""'], {}), "('Splitting into training and validation sets')\n", (8708, 8755), False, 'import logging\n'), ((8786, 8810), 'numpy.random.permutation', 'np.random.permutation', (['m'], {}), '(m)\n', (8807, 8810), True, 'import numpy as np\n'), ((8933, 8989), 'logging.info', 'logging.info', (["(' * training set shape: %d x %d' % x.shape)"], {}), "(' * training set shape: %d x %d' % x.shape)\n", (8945, 8989), False, 'import logging\n'), ((8994, 9056), 'logging.info', 'logging.info', (["(' * validation set shape: %d x %d' % val_x.shape)"], {}), "(' * validation set shape: %d x %d' % val_x.shape)\n", (9006, 9056), False, 'import logging\n'), ((10293, 10340), 'models.nncommon.TimeBasedStopping', 'TimeBasedStopping', ([], {'deadline': 'deadline', 'verbose': '(1)'}), '(deadline=deadline, verbose=1)\n', (10310, 10340), False, 'from models.nncommon import TimeBasedStopping\n'), ((10446, 10501), 'models.nncommon.TimeBasedStopping', 'TimeBasedStopping', ([], {'max_duration': 'max_duration', 'verbose': '(1)'}), '(max_duration=max_duration, verbose=1)\n', (10463, 10501), False, 'from models.nncommon import TimeBasedStopping\n')]
""" -------------------------- Created Feb 2022 <NAME> github.com/marcodeangelis MIT License -------------------------- """ import numpy def multiply(s,o): s_lo,s_hi,o_lo,o_hi=s.lo,s.hi,o.lo,o.hi if s.scalar & o.scalar: if (s_lo >= 0) & (o_lo >= 0): # A+ B+ l,h = s_lo * o_lo, s_hi * o_hi if (s_lo>=0) & ((o_lo<0) & (o_hi>0)): # A+ B0 l,h = s_hi * o_lo, s_hi * o_hi if (s_lo>=0) & (o_hi<=0): # A+ B- l,h = s_hi * o_lo, s_lo * o_hi if ((s_lo<0) & (s_hi>0)) & (o_lo>=0): # A0 B+ l,h = s_lo * o_hi, s_hi * o_hi if ((s_lo<0) & (s_hi>0)) & ((o_lo<0) & (o_hi>0)): # A0 B0 l=numpy.min((s_lo*o_hi, s_hi*o_lo,s_lo*o_lo,s_hi*o_hi),axis=0) h=numpy.max((s_lo*o_lo, s_hi*o_hi,s_lo*o_hi,s_hi*o_lo),axis=0) if ((s_lo<0) & (s_hi>0)) & (o_hi<=0): # A0 B- l,h = s_hi * o_lo, s_lo * o_lo if (s_hi<=0) & (o_lo>=0): # A- B+ l,h = s_lo * o_hi, s_hi * o_lo if (s_hi<=0) & ((o_lo<0) & (o_hi>0)): # A- B0 l,h = s_lo * o_hi, s_lo * o_lo if (s_hi<=0) & (o_hi<=0): # A- B- l,h = s_hi * o_hi, s_lo * o_lo elif s_lo.shape==o_lo.shape: l,h = numpy.empty(s_lo.shape),numpy.empty(s_lo.shape) pp=(s_lo >= 0) & (o_lo >= 0) # A+ B+ l[pp] = s_lo[pp] * o_lo[pp] h[pp] = s_hi[pp] * o_hi[pp] pz=(s_lo>=0) & ((o_lo<0) & (o_hi>0)) # A+ B0 l[pz] = s_hi[pz] * o_lo[pz] h[pz] = s_hi[pz] * o_hi[pz] pn=(s_lo>=0) & (o_hi<=0) # A+ B- l[pn] = s_hi[pn] * o_lo[pn] h[pn] = s_lo[pn] * o_hi[pn] zp=((s_lo<0) & (s_hi>0)) & (o_lo>=0) # A0 B+ l[zp] = s_lo[zp] * o_hi[zp] h[zp] = s_hi[zp] * o_hi[zp] zz=((s_lo<0) & (s_hi>0)) & ((o_lo<0) & (o_hi>0)) # A0 B0 l[zz]=numpy.min((s_lo[zz]*o_hi[zz], s_hi[zz]*o_lo[zz],s_lo[zz]*o_lo[zz],s_hi[zz]*o_hi[zz]),axis=0) h[zz]=numpy.max((s_lo[zz]*o_lo[zz], s_hi[zz]*o_hi[zz],s_lo[zz]*o_hi[zz],s_hi[zz]*o_lo[zz]),axis=0) zn=((s_lo<0) & (s_hi>0)) & (o_hi<=0)# A0 B- l[zn] = s_hi[zn] * o_lo[zn] h[zn] = s_lo[zn] * o_lo[zn] np=(s_hi<=0) & (o_lo>=0) # A- B+ l[np] = s_lo[np] * o_hi[np] h[np] = s_hi[np] * o_lo[np] nz=(s_hi<=0) & ((o_lo<0) & (o_hi>0)) # A- B0 l[nz] = s_lo[nz] * o_hi[nz] h[nz] = s_lo[nz] * o_lo[nz] nn=(s_hi<=0) & (o_hi<=0) # A- B- l[nn] = s_hi[nn] * o_hi[nn] h[nn] = s_lo[nn] * o_lo[nn] elif s.scalar: l,h = numpy.empty(o_lo.shape),numpy.empty(o_lo.shape) pp=(s_lo >= 0) & (o_lo >= 0) # A+ B+ l[pp] = s_lo * o_lo[pp] h[pp] = s_hi * o_hi[pp] pz=(s_lo>=0) & ((o_lo<0) & (o_hi>0)) # A+ B0 l[pz] = s_hi * o_lo[pz] h[pz] = s_hi * o_hi[pz] pn=(s_lo>=0) & (o_hi<=0) # A+ B- l[pn] = s_hi * o_lo[pn] h[pn] = s_lo * o_hi[pn] zp=((s_lo<0) & (s_hi>0)) & (o_lo>=0) # A0 B+ l[zp] = s_lo * o_hi[zp] h[zp] = s_hi * o_hi[zp] zz=((s_lo<0) & (s_hi>0)) & ((o_lo<0) & (o_hi>0)) # A0 B0 l[zz]=numpy.min((s_lo*o_hi[zz], s_hi*o_lo[zz],s_lo*o_lo[zz],s_hi*o_hi[zz]),axis=0) h[zz]=numpy.max((s_lo*o_lo[zz], s_hi*o_hi[zz],s_lo*o_hi[zz],s_hi*o_lo[zz]),axis=0) zn=((s_lo<0) & (s_hi>0)) & (o_hi<=0)# A0 B- l[zn] = s_hi * o_lo[zn] h[zn] = s_lo * o_lo[zn] np=(s_hi<=0) & (o_lo>=0) # A- B+ l[np] = s_lo * o_hi[np] h[np] = s_hi * o_lo[np] nz=(s_hi<=0) & ((o_lo<0) & (o_hi>0)) # A- B0 l[nz] = s_lo * o_hi[nz] h[nz] = s_lo * o_lo[nz] nn=(s_hi<=0) & (o_hi<=0) # A- B- l[nn] = s_hi * o_hi[nn] h[nn] = s_lo * o_lo[nn] elif o.scalar: l,h = numpy.empty(s_lo.shape),numpy.empty(s_lo.shape) pp=(s_lo >= 0) & (o_lo >= 0) # A+ B+ l[pp] = s_lo[pp] * o_lo h[pp] = s_hi[pp] * o_hi pz=(s_lo>=0) & ((o_lo<0) & (o_hi>0)) # A+ B0 l[pz] = s_hi[pz] * o_lo h[pz] = s_hi[pz] * o_hi pn=(s_lo>=0) & (o_hi<=0) # A+ B- l[pn] = s_hi[pn] * o_lo h[pn] = s_lo[pn] * o_hi zp=((s_lo<0) & (s_hi>0)) & (o_lo>=0) # A0 B+ l[zp] = s_lo[zp] * o_hi h[zp] = s_hi[zp] * o_hi zz=((s_lo<0) & (s_hi>0)) & ((o_lo<0) & (o_hi>0)) # A0 B0 l[zz]=numpy.min((s_lo[zz]*o_hi, s_hi[zz]*o_lo,s_lo[zz]*o_lo,s_hi[zz]*o_hi),axis=0) h[zz]=numpy.max((s_lo[zz]*o_lo, s_hi[zz]*o_hi,s_lo[zz]*o_hi,s_hi[zz]*o_lo),axis=0) zn=((s_lo<0) & (s_hi>0)) & (o_hi<=0)# A0 B- l[zn] = s_hi[zn] * o_lo h[zn] = s_lo[zn] * o_lo np=(s_hi<=0) & (o_lo>=0) # A- B+ l[np] = s_lo[np] * o_hi h[np] = s_hi[np] * o_lo nz=(s_hi<=0) & ((o_lo<0) & (o_hi>0)) # A- B0 l[nz] = s_lo[nz] * o_hi h[nz] = s_lo[nz] * o_lo nn=(s_hi<=0) & (o_hi<=0) # A- B- l[nn] = s_hi[nn] * o_hi h[nn] = s_lo[nn] * o_lo return l,h def divide(s,o): s_lo,s_hi,o_lo,o_hi=s.lo,s.hi,o.lo,o.hi other_straddle_zero = numpy.any((o_lo.flatten()<=0) & (o_hi.flatten()>=0)) if other_straddle_zero: raise ZeroDivisionError if s.scalar & o.scalar: if (s_lo >= 0) & (o_lo > 0): # A+ B+ l,h = s_lo / o_hi, s_hi / o_lo if ((s_lo<0) & (s_hi>0)) & (o_lo>0): # A0 B+ l,h = s_lo / o_lo, s_hi / o_lo if (s_hi<=0) & (o_lo>=0): # A- B+ l,h = s_lo / o_lo, s_hi / o_hi if (s_lo>=0) & (o_hi<=0): # A+ B- l,h = s_hi / o_hi, s_lo / o_lo if ((s_lo<0) & (s_hi>0)) & (o_hi<=0): # A0 B- l,h = s_hi / o_hi, s_lo / o_hi if (s_hi<=0) & (o_hi<=0): # A- B- l,h = s_hi / o_lo, s_lo / o_hi elif s_lo.shape==o_lo.shape: l,h = numpy.empty(s_lo.shape),numpy.empty(s_lo.shape) pp=(s_lo >= 0) & (o_lo > 0) # A+ B+ l[pp] = s_lo[pp] / o_hi[pp] h[pp] = s_hi[pp] / o_lo[pp] zp=((s_lo<0) & (s_hi>0)) & (o_lo>0) # A0 B+ l[zp] = s_lo[zp] / o_lo[zp] h[zp] = s_hi[zp] / o_lo[zp] np=(s_hi<=0) & (o_lo>=0) # A- B+ l[np] = s_lo[np] / o_lo[np] h[np] = s_hi[np] / o_hi[np] pn=(s_lo>=0) & (o_hi<=0) # A+ B- l[pn] = s_hi[pn] / o_hi[pn] h[pn] = s_lo[pn] / o_lo[pn] zn=((s_lo<0) & (s_hi>0)) & (o_hi<=0) # A0 B- l[zn] = s_hi[zn] / o_hi[zn] h[zn] = s_lo[zn] / o_hi[zn] nn=(s_hi<=0) & (o_hi<=0) # A- B- l[nn] = s_hi[nn] / o_lo[nn] h[nn] = s_lo[nn] / o_hi[nn] elif s.scalar: l,h = numpy.empty(o_lo.shape),numpy.empty(o_lo.shape) pp=(s_lo >= 0) & (o_lo > 0) # A+ B+ l[pp] = s_lo / o_hi[pp] h[pp] = s_hi / o_lo[pp] zp=((s_lo<0) & (s_hi>0)) & (o_lo>0) # A0 B+ l[zp] = s_lo / o_lo[zp] h[zp] = s_hi / o_lo[zp] np=(s_hi<=0) & (o_lo>=0) # A- B+ l[np] = s_lo / o_lo[np] h[np] = s_hi / o_hi[np] pn=(s_lo>=0) & (o_hi<=0) # A+ B- l[pn] = s_hi / o_hi[pn] h[pn] = s_lo / o_lo[pn] zn=((s_lo<0) & (s_hi>0)) & (o_hi<=0) # A0 B- l[zn] = s_hi / o_hi[zn] h[zn] = s_lo / o_hi[zn] nn=(s_hi<=0) & (o_hi<=0) # A- B- l[nn] = s_hi / o_lo[nn] h[nn] = s_lo / o_hi[nn] elif o.scalar: l,h = numpy.empty(s_lo.shape),numpy.empty(s_lo.shape) pp=(s_lo >= 0) & (o_lo > 0) # A+ B+ l[pp] = s_lo[pp] / o_hi h[pp] = s_hi[pp] / o_lo zp=((s_lo<0) & (s_hi>0)) & (o_lo>0) # A0 B+ l[zp] = s_lo[zp] / o_lo h[zp] = s_hi[zp] / o_lo np=(s_hi<=0) & (o_lo>=0) # A- B+ l[np] = s_lo[np] / o_lo h[np] = s_hi[np] / o_hi pn=(s_lo>=0) & (o_hi<=0) # A+ B- l[pn] = s_hi[pn] / o_hi h[pn] = s_lo[pn] / o_lo zn=((s_lo<0) & (s_hi>0)) & (o_hi<=0) # A0 B- l[zn] = s_hi[zn] / o_hi h[zn] = s_lo[zn] / o_hi nn=(s_hi<=0) & (o_hi<=0) # A- B- l[nn] = s_hi[nn] / o_lo h[nn] = s_lo[nn] / o_hi return l,h
[ "numpy.empty", "numpy.min", "numpy.max" ]
[((677, 748), 'numpy.min', 'numpy.min', (['(s_lo * o_hi, s_hi * o_lo, s_lo * o_lo, s_hi * o_hi)'], {'axis': '(0)'}), '((s_lo * o_hi, s_hi * o_lo, s_lo * o_lo, s_hi * o_hi), axis=0)\n', (686, 748), False, 'import numpy\n'), ((752, 823), 'numpy.max', 'numpy.max', (['(s_lo * o_lo, s_hi * o_hi, s_lo * o_hi, s_hi * o_lo)'], {'axis': '(0)'}), '((s_lo * o_lo, s_hi * o_hi, s_lo * o_hi, s_hi * o_lo), axis=0)\n', (761, 823), False, 'import numpy\n'), ((1831, 1939), 'numpy.min', 'numpy.min', (['(s_lo[zz] * o_hi[zz], s_hi[zz] * o_lo[zz], s_lo[zz] * o_lo[zz], s_hi[zz] *\n o_hi[zz])'], {'axis': '(0)'}), '((s_lo[zz] * o_hi[zz], s_hi[zz] * o_lo[zz], s_lo[zz] * o_lo[zz], \n s_hi[zz] * o_hi[zz]), axis=0)\n', (1840, 1939), False, 'import numpy\n'), ((1938, 2046), 'numpy.max', 'numpy.max', (['(s_lo[zz] * o_lo[zz], s_hi[zz] * o_hi[zz], s_lo[zz] * o_hi[zz], s_hi[zz] *\n o_lo[zz])'], {'axis': '(0)'}), '((s_lo[zz] * o_lo[zz], s_hi[zz] * o_hi[zz], s_lo[zz] * o_hi[zz], \n s_hi[zz] * o_lo[zz]), axis=0)\n', (1947, 2046), False, 'import numpy\n'), ((1224, 1247), 'numpy.empty', 'numpy.empty', (['s_lo.shape'], {}), '(s_lo.shape)\n', (1235, 1247), False, 'import numpy\n'), ((1248, 1271), 'numpy.empty', 'numpy.empty', (['s_lo.shape'], {}), '(s_lo.shape)\n', (1259, 1271), False, 'import numpy\n'), ((3114, 3206), 'numpy.min', 'numpy.min', (['(s_lo * o_hi[zz], s_hi * o_lo[zz], s_lo * o_lo[zz], s_hi * o_hi[zz])'], {'axis': '(0)'}), '((s_lo * o_hi[zz], s_hi * o_lo[zz], s_lo * o_lo[zz], s_hi * o_hi[\n zz]), axis=0)\n', (3123, 3206), False, 'import numpy\n'), ((3205, 3297), 'numpy.max', 'numpy.max', (['(s_lo * o_lo[zz], s_hi * o_hi[zz], s_lo * o_hi[zz], s_hi * o_lo[zz])'], {'axis': '(0)'}), '((s_lo * o_lo[zz], s_hi * o_hi[zz], s_lo * o_hi[zz], s_hi * o_lo[\n zz]), axis=0)\n', (3214, 3297), False, 'import numpy\n'), ((5764, 5787), 'numpy.empty', 'numpy.empty', (['s_lo.shape'], {}), '(s_lo.shape)\n', (5775, 5787), False, 'import numpy\n'), ((5788, 5811), 'numpy.empty', 'numpy.empty', (['s_lo.shape'], {}), '(s_lo.shape)\n', (5799, 5811), False, 'import numpy\n'), ((2539, 2562), 'numpy.empty', 'numpy.empty', (['o_lo.shape'], {}), '(o_lo.shape)\n', (2550, 2562), False, 'import numpy\n'), ((2563, 2586), 'numpy.empty', 'numpy.empty', (['o_lo.shape'], {}), '(o_lo.shape)\n', (2574, 2586), False, 'import numpy\n'), ((4333, 4424), 'numpy.min', 'numpy.min', (['(s_lo[zz] * o_hi, s_hi[zz] * o_lo, s_lo[zz] * o_lo, s_hi[zz] * o_hi)'], {'axis': '(0)'}), '((s_lo[zz] * o_hi, s_hi[zz] * o_lo, s_lo[zz] * o_lo, s_hi[zz] *\n o_hi), axis=0)\n', (4342, 4424), False, 'import numpy\n'), ((4424, 4515), 'numpy.max', 'numpy.max', (['(s_lo[zz] * o_lo, s_hi[zz] * o_hi, s_lo[zz] * o_hi, s_hi[zz] * o_lo)'], {'axis': '(0)'}), '((s_lo[zz] * o_lo, s_hi[zz] * o_hi, s_lo[zz] * o_hi, s_hi[zz] *\n o_lo), axis=0)\n', (4433, 4515), False, 'import numpy\n'), ((6549, 6572), 'numpy.empty', 'numpy.empty', (['o_lo.shape'], {}), '(o_lo.shape)\n', (6560, 6572), False, 'import numpy\n'), ((6573, 6596), 'numpy.empty', 'numpy.empty', (['o_lo.shape'], {}), '(o_lo.shape)\n', (6584, 6596), False, 'import numpy\n'), ((3758, 3781), 'numpy.empty', 'numpy.empty', (['s_lo.shape'], {}), '(s_lo.shape)\n', (3769, 3781), False, 'import numpy\n'), ((3782, 3805), 'numpy.empty', 'numpy.empty', (['s_lo.shape'], {}), '(s_lo.shape)\n', (3793, 3805), False, 'import numpy\n'), ((7286, 7309), 'numpy.empty', 'numpy.empty', (['s_lo.shape'], {}), '(s_lo.shape)\n', (7297, 7309), False, 'import numpy\n'), ((7310, 7333), 'numpy.empty', 'numpy.empty', (['s_lo.shape'], {}), '(s_lo.shape)\n', (7321, 7333), False, 'import numpy\n')]
""" @title @description """ import argparse import os import threading import time from queue import Queue, Empty from time import sleep import cv2 import matplotlib import matplotlib.pyplot as plt import numpy as np from Andrutil.ObserverObservable import Observer from matplotlib import style, animation from win32api import GetSystemMetrics from SystemControl import IMAGES_DIR from SystemControl.DataSource import DataSource from SystemControl.DataSource.LiveDataSource import MotorAction class TrialRecorder(Observer): def __init__(self, data_source: DataSource, x_windows_scale: int = 2, y_windows_scale: int = 2): Observer.__init__(self, [data_source]) self.data_source = data_source ############################## self._action_queue = Queue() self.data_source_name = data_source.__class__.__name__ ############################## self.image_width = 244 self.image_height = 244 self.direction_images = {} for m_action in MotorAction: blank_image = np.zeros((self.image_height, self.image_width, 3), np.uint8) action_image = cv2.imread(os.path.join(IMAGES_DIR, f'{m_action.name}.png')) resized_action_image = cv2.resize(action_image, (self.image_width, self.image_height)) added_image = cv2.addWeighted(blank_image, 0.2, resized_action_image, 1, 0) cvt_image = cv2.cvtColor(added_image, cv2.COLOR_BGR2RGB) self.direction_images[m_action] = cvt_image self.width_scale = x_windows_scale self.height_scale = y_windows_scale self._update_delay = 10 matplotlib.use('TkAgg') style.use('ggplot') self._fig = plt.figure(facecolor='black') self.__position_fig() self._axes = self._fig.add_subplot(1, 1, 1) self._axes.set_xticks([]) self._axes.set_yticks([]) self._img_artist = None self.ani = None self.start_time = -1 self.end_time = -1 self.run_time = -1 self.sample_rate_counter = 0 self.sample_rate_lock = threading.Lock() return def __position_fig(self): screen_width_resolution = GetSystemMetrics(0) screen_height_resolution = GetSystemMetrics(1) dpi = self._fig.dpi screen_width_inches = screen_width_resolution / dpi screen_height_inches = screen_height_resolution / dpi self._fig.set_size_inches( screen_width_inches / self.width_scale, screen_height_inches / self.height_scale ) x_offset = (1 - (1 / self.width_scale)) y_offset = (1 - (1 / self.height_scale)) window_pos_x = int(screen_width_resolution * x_offset / 2) window_pos_y = int(screen_height_resolution * y_offset / 2) fig_manager = plt.get_current_fig_manager() fig_manager.window.wm_geometry(f'+{window_pos_x}+{window_pos_y}') fig_manager.window.attributes('-topmost', 0) return def __init_plot(self): img = self.direction_images[MotorAction.REST] self._img_artist = self._axes.imshow(img) return self._img_artist, def update(self, source, update_message): if source in self.subscriptions: if source.__class__.__name__ == self.data_source_name: update_type = update_message.get('type', None) if update_type == 'sample': update_data = update_message.get('data', None) with self.sample_rate_lock: self.sample_rate_counter += 1 elif update_type == 'event': update_event = update_message.get('event', None) curr_time = time.time() d_time = curr_time - self.start_time eta = self.run_time - d_time with self.sample_rate_lock: sample_rate = self.sample_rate_counter / d_time print(f'event: {update_event}\n' f'\tnum samples: {self.sample_rate_counter}\n' f'\tsample rate: {sample_rate}\n' f'\telapsed: {d_time:0.4f}\n' f'\teta: {eta:0.4f}') # self.sample_rate_counter = 0 self._action_queue.put(update_event) def run(self, run_time: float): t = threading.Timer(run_time, self.end_trial) t.daemon = True t.start() self.start_time = time.time() self.run_time = run_time self.data_source.set_recording(True) self.run_animation() return def run_animation(self): self.ani = animation.FuncAnimation( self._fig, self.update_artists, init_func=self.__init_plot, interval=self._update_delay, blit=True ) plt.show() return def end_trial(self): self.end_time = time.time() self.data_source.set_recording(False) self.ani.event_source.stop() plt.close() # FIXME closes due to raising exception return def update_artists(self, update_arg): try: next_action = self._action_queue.get_nowait() action_image = self.direction_images[next_action] self._img_artist.set_data(action_image) except Empty: pass return self._img_artist, def main(margs): from SystemControl.OBciPython.UdpClient import UdpClient from SystemControl.StimulusGenerator import StimulusGenerator, GeneratorType from SystemControl.DataSource.LiveDataSource import LiveDataSource ################################################ record_length = margs.get('record_length', 20) current_subject = margs.get('subject_name', 'random') trial_type = margs.get('session_type', 'motor_imagery_right_left') generate_delay = margs.get('stimulus_delay', 5) jitter_generator = margs.get('jitter', 0.2) ################################################ verbosity = 0 ################################################ stimulus_generator = StimulusGenerator( delay=generate_delay, jitter=jitter_generator, generator_type=GeneratorType.RANDOM, verbosity=verbosity ) udp_client = UdpClient() data_source = LiveDataSource( subject=current_subject, trial_type=trial_type, subscriber_list=[stimulus_generator, udp_client] ) trial_recorder = TrialRecorder( data_source=data_source, x_windows_scale=2, y_windows_scale=2 ) stimulus_generator.run() udp_client.run() sleep(1) trial_recorder.run(record_length) trial_samples = data_source.get_trial_samples() # noinspection PyTypeChecker num_samples = len(trial_samples.index) print(f'Total number of samples: {num_samples}') print(f'Total sample rate: {num_samples / record_length}') data_source.save_data(start_time=0, end_time=-1) return if __name__ == '__main__': parser = argparse.ArgumentParser(description='Perform a single recording session.') parser.add_argument('--record_length', type=int, default=120, help='length (in seconds) of how long to record for the session') parser.add_argument('--subject_name', type=str, default='random', help='Name of subject to use when saving this session') parser.add_argument('--session_type', type=str, default='motor_imagery_right_left', help='type of trial to classify this session as') parser.add_argument('--stimulus_delay', type=int, default=5, help='average time between generation of next stimulus') parser.add_argument('--jitter', type=float, default=0.2, help='proportion of stimulus delay to add or subtract (randomly) from time between stimulus\n' 'if stimulus delay is 5, and jitter is 0.2, then the actual time between stimuli will ' 'be in the range (5-0.2*5, 5+0.2*5)') args = parser.parse_args() main(vars(args))
[ "threading.Timer", "argparse.ArgumentParser", "matplotlib.style.use", "SystemControl.StimulusGenerator.StimulusGenerator", "matplotlib.animation.FuncAnimation", "matplotlib.pyplot.figure", "os.path.join", "win32api.GetSystemMetrics", "cv2.cvtColor", "matplotlib.pyplot.close", "threading.Lock", ...
[((6171, 6297), 'SystemControl.StimulusGenerator.StimulusGenerator', 'StimulusGenerator', ([], {'delay': 'generate_delay', 'jitter': 'jitter_generator', 'generator_type': 'GeneratorType.RANDOM', 'verbosity': 'verbosity'}), '(delay=generate_delay, jitter=jitter_generator,\n generator_type=GeneratorType.RANDOM, verbosity=verbosity)\n', (6188, 6297), False, 'from SystemControl.StimulusGenerator import StimulusGenerator, GeneratorType\n'), ((6325, 6336), 'SystemControl.OBciPython.UdpClient.UdpClient', 'UdpClient', ([], {}), '()\n', (6334, 6336), False, 'from SystemControl.OBciPython.UdpClient import UdpClient\n'), ((6355, 6471), 'SystemControl.DataSource.LiveDataSource.LiveDataSource', 'LiveDataSource', ([], {'subject': 'current_subject', 'trial_type': 'trial_type', 'subscriber_list': '[stimulus_generator, udp_client]'}), '(subject=current_subject, trial_type=trial_type,\n subscriber_list=[stimulus_generator, udp_client])\n', (6369, 6471), False, 'from SystemControl.DataSource.LiveDataSource import LiveDataSource\n'), ((6657, 6665), 'time.sleep', 'sleep', (['(1)'], {}), '(1)\n', (6662, 6665), False, 'from time import sleep\n'), ((7055, 7129), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Perform a single recording session."""'}), "(description='Perform a single recording session.')\n", (7078, 7129), False, 'import argparse\n'), ((638, 676), 'Andrutil.ObserverObservable.Observer.__init__', 'Observer.__init__', (['self', '[data_source]'], {}), '(self, [data_source])\n', (655, 676), False, 'from Andrutil.ObserverObservable import Observer\n'), ((784, 791), 'queue.Queue', 'Queue', ([], {}), '()\n', (789, 791), False, 'from queue import Queue, Empty\n'), ((1645, 1668), 'matplotlib.use', 'matplotlib.use', (['"""TkAgg"""'], {}), "('TkAgg')\n", (1659, 1668), False, 'import matplotlib\n'), ((1677, 1696), 'matplotlib.style.use', 'style.use', (['"""ggplot"""'], {}), "('ggplot')\n", (1686, 1696), False, 'from matplotlib import style, animation\n'), ((1718, 1747), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'facecolor': '"""black"""'}), "(facecolor='black')\n", (1728, 1747), True, 'import matplotlib.pyplot as plt\n'), ((2109, 2125), 'threading.Lock', 'threading.Lock', ([], {}), '()\n', (2123, 2125), False, 'import threading\n'), ((2206, 2225), 'win32api.GetSystemMetrics', 'GetSystemMetrics', (['(0)'], {}), '(0)\n', (2222, 2225), False, 'from win32api import GetSystemMetrics\n'), ((2261, 2280), 'win32api.GetSystemMetrics', 'GetSystemMetrics', (['(1)'], {}), '(1)\n', (2277, 2280), False, 'from win32api import GetSystemMetrics\n'), ((2838, 2867), 'matplotlib.pyplot.get_current_fig_manager', 'plt.get_current_fig_manager', ([], {}), '()\n', (2865, 2867), True, 'import matplotlib.pyplot as plt\n'), ((4462, 4503), 'threading.Timer', 'threading.Timer', (['run_time', 'self.end_trial'], {}), '(run_time, self.end_trial)\n', (4477, 4503), False, 'import threading\n'), ((4572, 4583), 'time.time', 'time.time', ([], {}), '()\n', (4581, 4583), False, 'import time\n'), ((4755, 4883), 'matplotlib.animation.FuncAnimation', 'animation.FuncAnimation', (['self._fig', 'self.update_artists'], {'init_func': 'self.__init_plot', 'interval': 'self._update_delay', 'blit': '(True)'}), '(self._fig, self.update_artists, init_func=self.\n __init_plot, interval=self._update_delay, blit=True)\n', (4778, 4883), False, 'from matplotlib import style, animation\n'), ((4909, 4919), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4917, 4919), True, 'import matplotlib.pyplot as plt\n'), ((4985, 4996), 'time.time', 'time.time', ([], {}), '()\n', (4994, 4996), False, 'import time\n'), ((5088, 5099), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (5097, 5099), True, 'import matplotlib.pyplot as plt\n'), ((1055, 1115), 'numpy.zeros', 'np.zeros', (['(self.image_height, self.image_width, 3)', 'np.uint8'], {}), '((self.image_height, self.image_width, 3), np.uint8)\n', (1063, 1115), True, 'import numpy as np\n'), ((1239, 1302), 'cv2.resize', 'cv2.resize', (['action_image', '(self.image_width, self.image_height)'], {}), '(action_image, (self.image_width, self.image_height))\n', (1249, 1302), False, 'import cv2\n'), ((1329, 1390), 'cv2.addWeighted', 'cv2.addWeighted', (['blank_image', '(0.2)', 'resized_action_image', '(1)', '(0)'], {}), '(blank_image, 0.2, resized_action_image, 1, 0)\n', (1344, 1390), False, 'import cv2\n'), ((1415, 1459), 'cv2.cvtColor', 'cv2.cvtColor', (['added_image', 'cv2.COLOR_BGR2RGB'], {}), '(added_image, cv2.COLOR_BGR2RGB)\n', (1427, 1459), False, 'import cv2\n'), ((1154, 1202), 'os.path.join', 'os.path.join', (['IMAGES_DIR', 'f"""{m_action.name}.png"""'], {}), "(IMAGES_DIR, f'{m_action.name}.png')\n", (1166, 1202), False, 'import os\n'), ((3753, 3764), 'time.time', 'time.time', ([], {}), '()\n', (3762, 3764), False, 'import time\n')]
""" Copyright 2019 <NAME>, <NAME> This file is part of A2DR. A2DR is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. A2DR is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with A2DR. If not, see <http://www.gnu.org/licenses/>. """ import numpy as np import numpy.linalg as LA from scipy import sparse from a2dr import a2dr from a2dr.proximal import prox_sum_squares_affine, prox_nonneg_constr from a2dr.tests.base_test import BaseTest class TestBasic(BaseTest): """Unit tests for A2DR paper experiments.""" def setUp(self): np.random.seed(1) self.eps_rel = 1e-8 # specify these in all examples? self.eps_abs = 1e-6 self.MAX_ITER = 1000 def test_unconstrained(self): # minimize ||y - X\beta||_2^2. # Problem data. m, n = 100, 80 density = 0.1 X = sparse.random(m, n, density=density, data_rvs=np.random.randn) y = np.random.randn(m) prox_list = [lambda v, t: prox_sum_squares_affine(v, t, F=X, g=y, method="lstsq")] # Solve with NumPy. np_result = LA.lstsq(X.todense(), y, rcond=None) np_beta = np_result[0] np_obj = np.sum(np_result[1]) # Solve with DRS. drs_result = a2dr(prox_list, n_list=[n], anderson=False, max_iter=self.MAX_ITER) drs_beta = drs_result["x_vals"][-1] drs_obj = np.sum((y - X.dot(drs_beta))**2) print("Finish DRS.") # Solve with A2DR. a2dr_result = a2dr(prox_list, n_list=[n], anderson=True, max_iter=self.MAX_ITER) a2dr_beta = a2dr_result["x_vals"][-1] a2dr_obj = np.sum((y - X.dot(a2dr_beta))**2) print("Finish A2DR.") self.assertAlmostEqual(np_obj, drs_obj) self.assertAlmostEqual(np_obj, a2dr_obj) def test_ols(self): # minimize ||y - X\beta||_2^2. m = 100 n = 10 N = 4 # Number of splits. (split X row-wise) beta_true = np.array(np.arange(-n / 2, n / 2) + 1) X = np.random.randn(m, n) y = X.dot(beta_true) + np.random.randn(m) # Split problem. X_split = np.split(X, N) y_split = np.split(y, N) # Construct list of proximal operators. # Note: We must do it this way to avoid problems caused by late binding: # https://docs.python-guide.org/writing/gotchas/#late-binding-closures prox_list = [lambda v, t, i=i: prox_sum_squares_affine(v, t, F=X_split[i], g=y_split[i], method="lstsq") \ for i in range(N)] v_init = N * [np.random.randn(n)] # Solve with NumPy. np_beta = [] np_obj = 0 for i in range(N): np_result = LA.lstsq(X_split[i], y_split[i], rcond=None) np_beta += [np_result[0]] np_obj += np.sum(np_result[1]) print("NumPy Objective:", np_obj) print("NumPy Solution:", np_beta) # Solve with DRS (proximal point method). drs_result = a2dr(prox_list, v_init=v_init, max_iter=self.MAX_ITER, eps_abs=self.eps_abs, \ eps_rel=self.eps_rel, anderson=False) drs_beta = drs_result["x_vals"] drs_obj = np.sum([(yi - Xi.dot(beta)) ** 2 for yi, Xi, beta in zip(y_split, X_split, drs_beta)]) print("DRS Objective:", drs_obj) print("DRS Solution:", drs_beta) # Solve with A2DR (proximal point method with Anderson acceleration). a2dr_result = a2dr(prox_list, v_init=v_init, max_iter=self.MAX_ITER, eps_abs=self.eps_abs, \ eps_rel=self.eps_rel, anderson=True) a2dr_beta = a2dr_result["x_vals"] a2dr_obj = np.sum([(yi - Xi.dot(beta)) ** 2 for yi, Xi, beta in zip(y_split, X_split, drs_beta)]) print("A2DR Objective:", a2dr_obj) print("A2DR Solution:", a2dr_beta) # Compare results. self.assertAlmostEqual(np_obj, drs_obj) self.assertAlmostEqual(np_obj, a2dr_obj) for i in range(N): self.assertItemsAlmostEqual(np_beta[i], drs_beta[i]) self.assertItemsAlmostEqual(np_beta[i], a2dr_beta[i]) def test_infeas(self): # a modified non-negative least squares example with infeasible linear constraints m, n = 150, 300 density = 0.001 X = sparse.random(m, n, density=density, data_rvs=np.random.randn) y = np.random.randn(m) # Convert problem to standard form. prox_list = [lambda v, t: prox_sum_squares_affine(v, t, F=X, g=y), prox_nonneg_constr] Z = sparse.eye(n); e1 = sparse.lil_matrix((1,n)) e1[0,0] = 1 A1 = sparse.bmat([[Z], [e1]]) A2 = sparse.bmat([[-Z], [-e1]]) A_list = [A1, A2] b = np.zeros(n+1) b[0] = 1 b[-1] = -1 # Solve with DRS. drs_result = a2dr(prox_list, A_list, b, anderson=False) # Solve with A2DR. a2dr_result = a2dr(prox_list, A_list, b, anderson=True) self.assertTrue(drs_result == {"x_vals": None, "primal": None, "dual": None, "num_iters": None, "solve_time": None} and a2dr_result == {"x_vals": None, "primal": None, "dual": None, "num_iters": None, "solve_time": None})
[ "a2dr.proximal.prox_sum_squares_affine", "a2dr.a2dr", "scipy.sparse.random", "numpy.random.seed", "numpy.sum", "numpy.random.randn", "numpy.linalg.lstsq", "numpy.zeros", "scipy.sparse.bmat", "numpy.split", "scipy.sparse.lil_matrix", "numpy.arange", "scipy.sparse.eye" ]
[((967, 984), 'numpy.random.seed', 'np.random.seed', (['(1)'], {}), '(1)\n', (981, 984), True, 'import numpy as np\n'), ((1260, 1322), 'scipy.sparse.random', 'sparse.random', (['m', 'n'], {'density': 'density', 'data_rvs': 'np.random.randn'}), '(m, n, density=density, data_rvs=np.random.randn)\n', (1273, 1322), False, 'from scipy import sparse\n'), ((1335, 1353), 'numpy.random.randn', 'np.random.randn', (['m'], {}), '(m)\n', (1350, 1353), True, 'import numpy as np\n'), ((1579, 1599), 'numpy.sum', 'np.sum', (['np_result[1]'], {}), '(np_result[1])\n', (1585, 1599), True, 'import numpy as np\n'), ((1648, 1715), 'a2dr.a2dr', 'a2dr', (['prox_list'], {'n_list': '[n]', 'anderson': '(False)', 'max_iter': 'self.MAX_ITER'}), '(prox_list, n_list=[n], anderson=False, max_iter=self.MAX_ITER)\n', (1652, 1715), False, 'from a2dr import a2dr\n'), ((1890, 1956), 'a2dr.a2dr', 'a2dr', (['prox_list'], {'n_list': '[n]', 'anderson': '(True)', 'max_iter': 'self.MAX_ITER'}), '(prox_list, n_list=[n], anderson=True, max_iter=self.MAX_ITER)\n', (1894, 1956), False, 'from a2dr import a2dr\n'), ((2404, 2425), 'numpy.random.randn', 'np.random.randn', (['m', 'n'], {}), '(m, n)\n', (2419, 2425), True, 'import numpy as np\n'), ((2520, 2534), 'numpy.split', 'np.split', (['X', 'N'], {}), '(X, N)\n', (2528, 2534), True, 'import numpy as np\n'), ((2553, 2567), 'numpy.split', 'np.split', (['y', 'N'], {}), '(y, N)\n', (2561, 2567), True, 'import numpy as np\n'), ((3379, 3497), 'a2dr.a2dr', 'a2dr', (['prox_list'], {'v_init': 'v_init', 'max_iter': 'self.MAX_ITER', 'eps_abs': 'self.eps_abs', 'eps_rel': 'self.eps_rel', 'anderson': '(False)'}), '(prox_list, v_init=v_init, max_iter=self.MAX_ITER, eps_abs=self.eps_abs,\n eps_rel=self.eps_rel, anderson=False)\n', (3383, 3497), False, 'from a2dr import a2dr\n'), ((3850, 3967), 'a2dr.a2dr', 'a2dr', (['prox_list'], {'v_init': 'v_init', 'max_iter': 'self.MAX_ITER', 'eps_abs': 'self.eps_abs', 'eps_rel': 'self.eps_rel', 'anderson': '(True)'}), '(prox_list, v_init=v_init, max_iter=self.MAX_ITER, eps_abs=self.eps_abs,\n eps_rel=self.eps_rel, anderson=True)\n', (3854, 3967), False, 'from a2dr import a2dr\n'), ((4689, 4751), 'scipy.sparse.random', 'sparse.random', (['m', 'n'], {'density': 'density', 'data_rvs': 'np.random.randn'}), '(m, n, density=density, data_rvs=np.random.randn)\n', (4702, 4751), False, 'from scipy import sparse\n'), ((4764, 4782), 'numpy.random.randn', 'np.random.randn', (['m'], {}), '(m)\n', (4779, 4782), True, 'import numpy as np\n'), ((4957, 4970), 'scipy.sparse.eye', 'sparse.eye', (['n'], {}), '(n)\n', (4967, 4970), False, 'from scipy import sparse\n'), ((4985, 5010), 'scipy.sparse.lil_matrix', 'sparse.lil_matrix', (['(1, n)'], {}), '((1, n))\n', (5002, 5010), False, 'from scipy import sparse\n'), ((5044, 5068), 'scipy.sparse.bmat', 'sparse.bmat', (['[[Z], [e1]]'], {}), '([[Z], [e1]])\n', (5055, 5068), False, 'from scipy import sparse\n'), ((5082, 5108), 'scipy.sparse.bmat', 'sparse.bmat', (['[[-Z], [-e1]]'], {}), '([[-Z], [-e1]])\n', (5093, 5108), False, 'from scipy import sparse\n'), ((5147, 5162), 'numpy.zeros', 'np.zeros', (['(n + 1)'], {}), '(n + 1)\n', (5155, 5162), True, 'import numpy as np\n'), ((5245, 5287), 'a2dr.a2dr', 'a2dr', (['prox_list', 'A_list', 'b'], {'anderson': '(False)'}), '(prox_list, A_list, b, anderson=False)\n', (5249, 5287), False, 'from a2dr import a2dr\n'), ((5337, 5378), 'a2dr.a2dr', 'a2dr', (['prox_list', 'A_list', 'b'], {'anderson': '(True)'}), '(prox_list, A_list, b, anderson=True)\n', (5341, 5378), False, 'from a2dr import a2dr\n'), ((2457, 2475), 'numpy.random.randn', 'np.random.randn', (['m'], {}), '(m)\n', (2472, 2475), True, 'import numpy as np\n'), ((3097, 3141), 'numpy.linalg.lstsq', 'LA.lstsq', (['X_split[i]', 'y_split[i]'], {'rcond': 'None'}), '(X_split[i], y_split[i], rcond=None)\n', (3105, 3141), True, 'import numpy.linalg as LA\n'), ((3202, 3222), 'numpy.sum', 'np.sum', (['np_result[1]'], {}), '(np_result[1])\n', (3208, 3222), True, 'import numpy as np\n'), ((1388, 1443), 'a2dr.proximal.prox_sum_squares_affine', 'prox_sum_squares_affine', (['v', 't'], {'F': 'X', 'g': 'y', 'method': '"""lstsq"""'}), "(v, t, F=X, g=y, method='lstsq')\n", (1411, 1443), False, 'from a2dr.proximal import prox_sum_squares_affine, prox_nonneg_constr\n'), ((2362, 2386), 'numpy.arange', 'np.arange', (['(-n / 2)', '(n / 2)'], {}), '(-n / 2, n / 2)\n', (2371, 2386), True, 'import numpy as np\n'), ((2816, 2889), 'a2dr.proximal.prox_sum_squares_affine', 'prox_sum_squares_affine', (['v', 't'], {'F': 'X_split[i]', 'g': 'y_split[i]', 'method': '"""lstsq"""'}), "(v, t, F=X_split[i], g=y_split[i], method='lstsq')\n", (2839, 2889), False, 'from a2dr.proximal import prox_sum_squares_affine, prox_nonneg_constr\n'), ((2957, 2975), 'numpy.random.randn', 'np.random.randn', (['n'], {}), '(n)\n', (2972, 2975), True, 'import numpy as np\n'), ((4862, 4901), 'a2dr.proximal.prox_sum_squares_affine', 'prox_sum_squares_affine', (['v', 't'], {'F': 'X', 'g': 'y'}), '(v, t, F=X, g=y)\n', (4885, 4901), False, 'from a2dr.proximal import prox_sum_squares_affine, prox_nonneg_constr\n')]
import numpy as np import bioformats as bf import tnia.io.bioformats_helper as bfh import tnia.io.tifffile_helper as tfh # 4 channels nc=4 nz=5 # 512 by 512 ny = 512 nx = 512 test=((2**16-1)*np.random.rand(nc, nz, ny, nx)).astype('uint16') ''' import tifffile test = np.moveaxis(test,0,1) tfh.save_zcyx('fromthetiffhelper.tif', test) #bfh.save_4D('fromthehelper2.tif',test) ''' import imagej import xarray as xr #ij = imagej.init() ij = imagej.init('sc.fiji:fiji:2.1.1') data = xr.DataArray(test, dims=('C','z','y','x')) dataset = dataset = ij.py.to_dataset(data) dataset = ij.py.to_dataset(data) ij.io().save(dataset, 'frompyfiji.tif')
[ "numpy.random.rand", "imagej.init", "xarray.DataArray" ]
[((439, 472), 'imagej.init', 'imagej.init', (['"""sc.fiji:fiji:2.1.1"""'], {}), "('sc.fiji:fiji:2.1.1')\n", (450, 472), False, 'import imagej\n'), ((480, 525), 'xarray.DataArray', 'xr.DataArray', (['test'], {'dims': "('C', 'z', 'y', 'x')"}), "(test, dims=('C', 'z', 'y', 'x'))\n", (492, 525), True, 'import xarray as xr\n'), ((192, 222), 'numpy.random.rand', 'np.random.rand', (['nc', 'nz', 'ny', 'nx'], {}), '(nc, nz, ny, nx)\n', (206, 222), True, 'import numpy as np\n')]
import pandas as pd import numpy as np import cv2 import sys import os from keras.models import Sequential from keras.callbacks import Callback, ModelCheckpoint from keras.layers import (Flatten, Dense, Convolution2D, MaxPool2D, BatchNormalization, Dropout, Activation, Cropping2D, Lambda) from keras.optimizers import Adam from keras.regularizers import l2 from keras.preprocessing.image import ImageDataGenerator from keras.backend import tf as ktf from sklearn.model_selection import train_test_split from sklearn.utils import shuffle from scipy.misc import imread import scipy import matplotlib import matplotlib.pyplot as plt import argparse import json import random matplotlib.style.use('ggplot') ########################### Utilities ######################################### def print_progress_bar(iteration, total, prefix='', suffix='', decimals=1, bar_length=100): """ Call in a loop to create terminal progress bar @params: iteration - Required : current iteration (Int) total - Required : total iterations (Int) prefix - Optional : prefix string (Str) suffix - Optional : suffix string (Str) decimals - Optional : positive number of decimals in percent complete (Int) bar_length - Optional : character length of bar (Int) """ str_format = "{0:." + str(decimals) + "f}" percents = str_format.format(100 * (iteration / float(total))) filled_length = int(round(bar_length * iteration / float(total))) bar = '█' * filled_length + '-' * (bar_length - filled_length) sys.stdout.write('\r%s |%s| %s%s %s' % (prefix, bar, percents, '%', suffix)), if iteration == total: sys.stdout.write('\n') sys.stdout.flush() ### ############################# VISUALIZATION #################################### def show_data_distribution(df): binwidth = 0.025 # histogram before image augmentation plt.hist(df.steering_angle, bins=np.arange(min(df.steering_angle), max(df.steering_angle) + binwidth, binwidth)) plt.title('Number of images per steering angle') plt.xlabel('Steering Angle') plt.ylabel('# Frames') plt.show() ############################### NETWORK ######################################## def nvidia_end_to_end(shape, l2_regularization_scale): print("Training Nvidia End To End of input shape %s" % str(shape)) height = shape[0] crop_factor = 0.2 # Top 40% to be removed crop_size = (int)(crop_factor * height) model = Sequential() model.add(Cropping2D(cropping=((crop_size, 0), (0, 0)), input_shape=shape)) model.add(Lambda(lambda x: (x / 255.0) - 0.5)) model.add(BatchNormalization(axis=1, input_shape=shape)) model.add(Convolution2D(16, (3, 3), padding='valid', strides=(2, 2), activation='elu', kernel_regularizer=l2(l2_regularization_scale), bias_regularizer=l2(l2_regularization_scale))) model.add(Convolution2D(24, (3, 3), padding='valid', strides=(1, 2), activation='elu', kernel_regularizer=l2(l2_regularization_scale), bias_regularizer=l2(l2_regularization_scale))) model.add(Convolution2D(36, (3, 3), padding='valid', activation='elu', kernel_regularizer=l2(l2_regularization_scale), bias_regularizer=l2(l2_regularization_scale))) model.add(Convolution2D(48, (2, 2), padding='valid', activation='elu', kernel_regularizer=l2(l2_regularization_scale), bias_regularizer=l2(l2_regularization_scale))) model.add(Convolution2D(48, (2, 2), padding='valid', activation='elu', kernel_regularizer=l2(l2_regularization_scale), bias_regularizer=l2(l2_regularization_scale))) model.add(Flatten()) model.add(Dense(512, kernel_regularizer=l2(l2_regularization_scale), bias_regularizer=l2(l2_regularization_scale))) model.add(Dropout(.5)) model.add(Activation('elu')) model.add(Dense(10, kernel_regularizer=l2(l2_regularization_scale), bias_regularizer=l2(l2_regularization_scale))) model.add(Activation('elu')) model.add(Dense(1, kernel_regularizer=l2(l2_regularization_scale), bias_regularizer=l2(l2_regularization_scale))) model.summary() adam = Adam(lr=0.0001) model.compile(loss='mse', optimizer=adam) return model ################################# Dataset Manipulation Functions ############################## def flip_image(img): fimg = np.fliplr(img) return fimg def read_image(filename): img = imread(filename).astype(np.float32) img = scipy.misc.imresize(img, 50) return img def change_brightness(img): change_pct = int(random.uniform(0, 100)) mask = (255 - img) < change_pct img = np.where((255 - img) < change_pct, 255, img + change_pct) return img def read_csv(filename, cols): print("Reading Training file: %s" % filename) return pd.read_csv(filename, names=cols) def drop_zero_value_steering_angle_rows(df, drop_to): """ df: The dataframe to drop rows from col_name: The column to check from for steering_angle drop_to: How many rows to drop to """ # print("Total rows: %s" % len(df)) # indices = df[df[col_name] == 0.0].index # total_existing = indices.shape[0] # print("Total Zero Value rows: %s" % total_existing) # print("Dropping %s rows from df" % (total_existing - drop_to)) # remove_indices = np.random.choice(indices, size=total_existing - drop_to) # new_df = df.drop(remove_indices) # indices = new_df[new_df[col_name] == 0.0].index # print("Remaining zero value %s" % len(indices)) # # print("Total rows: %s" % len(new_df)) # print("Dropped %s rows" % (total_existing - drop_to)) # assert(len(df) - len(new_df) == (total_existing - drop_to)) # return new_df df_with_zero = df[df.steering_angle == 0] df_without_zero = df[df.steering_angle != 0] df_with_zero = df_with_zero.sample(n=drop_to) new_df = pd.concat([df_with_zero, df_without_zero]) return new_df def align_steering_angles_data(df): """ Given a dataframe drop the 0 value steering angles to bring it at par """ new_df = drop_zero_value_steering_angle_rows(df, 600) return new_df ############################# Data Reading Routines ################################# def read_training_data(track): cols = ['center_image', 'left_image', 'right_image', 'steering_angle', 'throttle', 'brake', 'speed'] data_dirs = [entry.path for entry in os.scandir('data') if entry.is_dir()] dfs = [] for ddir in data_dirs: # Ignore the recovery tracks since they will be loaded later if "recovery" not in ddir: if track in ddir: dfs.append(read_csv(ddir + '/driving_log.csv', cols)) elif track == "both": dfs.append(read_csv(ddir + '/driving_log.csv', cols)) df = pd.concat(dfs) return df def read_sample_training(df): """ df: Original DF from our training data which is to be augmented """ cols = ['center_image', 'left_image', 'right_image', 'steering_angle', 'throttle', 'brake', 'speed'] sample_df = read_csv('sample_training_data/driving_log.csv', cols) df = pd.concat([df, sample_df]) return df def preprocess(img): return img def augment_image(img, technique): if technique == "flip": return flip_image(img) elif technique == "brightness": return change_brightness(img) assert("No Valid technique passed for image augmentation") def load_data(df): all_samples = [] measurements = [] shape = None total_images = len(df) index = 0 for i, row in df.iterrows(): print_progress_bar(index, total_images) index += 1 center_image = preprocess(read_image(row[0])) all_samples.append(center_image) measurements.append(float(row[3])) left_image = preprocess(read_image(row[1])) all_samples.append(left_image) measurements.append(float(row[3]) + (0.25)) right_image = preprocess(read_image(row[2])) all_samples.append(right_image) measurements.append(float(row[3]) - (0.25)) shape = center_image.shape # Add an image for the flipped version of the center image flipped_center_image = flip_image(center_image) all_samples.append(flipped_center_image) measurements.append(-float(row[3])) return np.array(all_samples), np.array(measurements), shape # def setup_probabilistic_distribution(df): # binwidth = 0.025 # num_bins = int((max(df.steering_angle) - min(df.steering_angle)) / binwidth) # # histogram before image augmentation # counts, bins = np.histogram(df['steering_angle']) # total = len(df.index) def rearrange_and_augment_dataframe(df, shuffle_data): """ Rearrange the dataframe to linearize the steering angle images and also add a column to indicate whether augmentation is required or not and what kind of augmentation is required. """ center_df = pd.DataFrame() left_df = pd.DataFrame() right_df = pd.DataFrame() flipped_center = pd.DataFrame() center_df['image'] = df['center_image'] flipped_center['image'] = df['center_image'] left_df['image'] = df['left_image'] right_df['image'] = df['right_image'] center_df['steering_angle'] = df['steering_angle'] left_df['steering_angle'] = df['steering_angle'] + 0.25 right_df['steering_angle'] = df['steering_angle'] - 0.25 flipped_center['steering_angle'] = -1.0 * df['steering_angle'] # Set the dataframe columns for augmentation to false for some center_df['augmentation'] = False left_df['augmentation'] = False right_df['augmentation'] = False flipped_center['augmentation'] = True # Set the augmentation techniques we need center_df['techniques'] = "" left_df['techniques'] = "" right_df['techniques'] = "" flipped_center['techniques'] = "flip" # Change the brightness for images with different steering angles and add them brightness_df = center_df.loc[(center_df.steering_angle < -0.025) | (center_df.steering_angle > 0.025)] BRIGHTNESS_AUG_FACTOR = 20 brightness_df = brightness_df.append([brightness_df]*BRIGHTNESS_AUG_FACTOR, ignore_index=True) brightness_df.steering_angle = brightness_df.steering_angle + (np.random.uniform(-1, 1)/30.0) brightness_df.augmentation = True brightness_df.techniques = "brightness" new_df = pd.concat([center_df, left_df, right_df, flipped_center, brightness_df]) if shuffle_data: shuffle(new_df) return new_df def read_recovery_track_data(): # Read the recovery track data for track 2 cols = ['center_image', 'left_image', 'right_image', 'steering_angle', 'throttle', 'brake', 'speed'] df = read_csv('data/track2_recovery/driving_log.csv', cols) recovery_df = rearrange_and_augment_dataframe(df, shuffle_data=True) return recovery_df def save_experiment(name, network_used, epochs, model, hist): # Based on the experiment name, save the history and the model for future use experiments_folder = "experiments/" history_filename = experiments_folder + name + ".json" fp = open(history_filename, 'w') json.dump(hist.history, fp) print(hist.history) fp.close() model_filename = experiments_folder + name + "_" + str(epochs) + "_epochs_" + network_used + '.h5' model.save(model_filename) print("Wrote History file: %s" % history_filename) print("Wrote Model file: %s" % model_filename) NETWORKS = { "nvidia": nvidia_end_to_end, } ################################# GENERATORS ################################### def new_generator(samples, batch_size=32): num_samples = len(samples) while 1: shuffle(samples) for offset in range(0, num_samples, batch_size): batch_samples = samples[offset: offset + batch_size] images = [] angles = [] for i, batch_sample in batch_samples.iterrows(): img = read_image(batch_sample.image) steering_angle = float(batch_sample.steering_angle) augment = batch_sample.augmentation techniques = batch_sample.techniques if augment: # Techniques should be setup like this for multiple ones # flip,brightness techniques = techniques.split(",") for technique in techniques: img = augment_image(img, technique) images.append(img) angles.append(steering_angle) X = np.array(images) y = np.array(angles) yield X, y def generator(samples, batch_size=32): num_samples = len(samples) while 1: shuffle(samples) for offset in range(0, num_samples, batch_size): batch_samples = samples[offset: offset + batch_size] images = [] angles = [] for i, batch_sample in batch_samples.iterrows(): center_image = read_image(batch_sample[0]) center_angle = float(batch_sample[3]) images.append(center_image) angles.append(center_angle) left_image = read_image(batch_sample[1]) left_angle = float(batch_sample[3] + 0.25) images.append(left_image) angles.append(left_angle) right_image = read_image(batch_sample[0]) right_angle = float(batch_sample[3] - 0.25) images.append(right_image) angles.append(right_angle) X = np.array(images) y = np.array(angles) yield shuffle(X, y) def training_generator(samples, batch_size=32): num_samples = len(samples) images = [] angles = [] # Drop all the rows and just keep 10 # drop_indices = np.random.choice(samples.index, size=len(samples.index) - 100, replace=False) # samples = samples.drop(drop_indices) # First create the proper training data. print("Creating Initial Training Data...") for i, batch_sample in samples.iterrows(): center_image = read_image(batch_sample[0]) center_angle = float(batch_sample[3]) images.append(center_image) angles.append(center_angle) left_image = read_image(batch_sample[1]) left_angle = float(batch_sample[3] + 0.25) images.append(left_image) angles.append(left_angle) right_image = read_image(batch_sample[0]) right_angle = float(batch_sample[3] - 0.25) images.append(right_image) angles.append(right_angle) # Also flip the center image and change the steering angle. flipped_center_image = flip_image(center_image) images.append(flipped_center_image) angles.append(-center_angle) images = np.array(images) angles = np.array(angles) print("Feeding to Keras Generator...") datagen = ImageDataGenerator( featurewise_center=False, featurewise_std_normalization=False, rotation_range=10, width_shift_range=0.2, height_shift_range=0.2, zca_whitening=False, channel_shift_range=0.2, zoom_range=0.2) # datagen.fit(images) while 1: X, y = shuffle(images, angles) for X_train, y_train in datagen.flow(X, y, batch_size=batch_size): yield shuffle(X_train, y_train) ################################# MAIN METHODS ################################# def args_definition(): parser = argparse.ArgumentParser() parser.add_argument("--epochs", help="Number of Epochs to train the network for" ,type=int, default=20) parser.add_argument("--network", help="Specify which Neural Network to execute" ,choices=list(NETWORKS.keys()) + ["all"], default="simple_network") parser.add_argument("--track", help="Specify which track data to use", choices=["track1", "track2", "both"], default="both") parser.add_argument("--use_sample_training", help="Use the sample training data", action='store_true') parser.add_argument("--experiment", help="Give the run an experiment name", type=str) parser.add_argument("--show_data_distribution", help="Show the data distribution for the training data", action='store_true') args = parser.parse_args() return args def main(): global NETWORKS args = args_definition() df = read_training_data(args.track) if args.use_sample_training: df = read_sample_training(df) frames, steering_angles, shape = load_data(df) model = NETWORKS[args.network](shape) hist = model.fit(frames, steering_angles, validation_split=0.2, shuffle=True, epochs=args.epochs) model_name = args.network + '.h5' model.save(model_name) if args.experiment != "": save_experiment(args.experiment, args.network, model, hist) from keras import backend as K K.clear_session() class EarlyStoppingByLossVal(Callback): def __init__(self, monitor='val_loss', value=0.00001, verbose=0): super(Callback, self).__init__() self.monitor = monitor self.value = value self.verbose = verbose def on_epoch_end(self, epoch, logs={}): current = logs.get(self.monitor) if current is None: warnings.warn("Early stopping requires %s available!" % self.monitor, RuntimeWarning) if current < self.value: if self.verbose > 0: print("Epoch %05d: early stopping THR" % epoch) self.model.stop_training = True def main_generator(): global NETWORKS args = args_definition() df = read_training_data(args.track) if args.use_sample_training: df = read_sample_training(df) df = rearrange_and_augment_dataframe(df, shuffle_data=True) if args.track == "track2" or args.track == "both": recovery_df = read_recovery_track_data() df = pd.concat([df, recovery_df]) # df = align_steering_angles_data(df) if args.show_data_distribution: show_data_distribution(df) return BATCH_SIZE = 512 train_samples, validation_samples = train_test_split(df, test_size=0.2) print("Total Training Samples: %s" % len(train_samples.index)) print("Total Validation Samples: %s" % len(validation_samples.index)) train_generator = new_generator(train_samples, batch_size=BATCH_SIZE) validation_generator = new_generator(validation_samples, batch_size=BATCH_SIZE) shape = (80, 160, 3) l2_regularization = 1e-7 model = NETWORKS[args.network](shape, l2_regularization) callbacks = [ EarlyStoppingByLossVal(monitor='val_loss', value=0.00001, verbose=1), ModelCheckpoint('latest_run/' + args.experiment + "_" + args.network + "_{epoch:02d}-{val_loss:.2f}.h5", monitor='val_loss', save_best_only=True, verbose=1), ] hist = model.fit_generator(train_generator, steps_per_epoch=len(df) // BATCH_SIZE + 1, validation_data=validation_generator, epochs=args.epochs, validation_steps=10, callbacks=callbacks) model_name = args.network + '.h5' model.save(model_name) if args.experiment != "": save_experiment(args.experiment, args.network, args.epochs, model, hist) from keras import backend as K K.clear_session() if __name__ == "__main__": # main() main_generator()
[ "matplotlib.pyplot.title", "keras.preprocessing.image.ImageDataGenerator", "sys.stdout.write", "keras.regularizers.l2", "matplotlib.style.use", "argparse.ArgumentParser", "keras.layers.Cropping2D", "pandas.read_csv", "sklearn.model_selection.train_test_split", "sys.stdout.flush", "pandas.DataFra...
[((680, 710), 'matplotlib.style.use', 'matplotlib.style.use', (['"""ggplot"""'], {}), "('ggplot')\n", (700, 710), False, 'import matplotlib\n'), ((1736, 1754), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (1752, 1754), False, 'import sys\n'), ((2058, 2106), 'matplotlib.pyplot.title', 'plt.title', (['"""Number of images per steering angle"""'], {}), "('Number of images per steering angle')\n", (2067, 2106), True, 'import matplotlib.pyplot as plt\n'), ((2111, 2139), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Steering Angle"""'], {}), "('Steering Angle')\n", (2121, 2139), True, 'import matplotlib.pyplot as plt\n'), ((2144, 2166), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""# Frames"""'], {}), "('# Frames')\n", (2154, 2166), True, 'import matplotlib.pyplot as plt\n'), ((2171, 2181), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2179, 2181), True, 'import matplotlib.pyplot as plt\n'), ((2514, 2526), 'keras.models.Sequential', 'Sequential', ([], {}), '()\n', (2524, 2526), False, 'from keras.models import Sequential\n'), ((4342, 4357), 'keras.optimizers.Adam', 'Adam', ([], {'lr': '(0.0001)'}), '(lr=0.0001)\n', (4346, 4357), False, 'from keras.optimizers import Adam\n'), ((4550, 4564), 'numpy.fliplr', 'np.fliplr', (['img'], {}), '(img)\n', (4559, 4564), True, 'import numpy as np\n'), ((4664, 4692), 'scipy.misc.imresize', 'scipy.misc.imresize', (['img', '(50)'], {}), '(img, 50)\n', (4683, 4692), False, 'import scipy\n'), ((4828, 4883), 'numpy.where', 'np.where', (['(255 - img < change_pct)', '(255)', '(img + change_pct)'], {}), '(255 - img < change_pct, 255, img + change_pct)\n', (4836, 4883), True, 'import numpy as np\n'), ((4993, 5026), 'pandas.read_csv', 'pd.read_csv', (['filename'], {'names': 'cols'}), '(filename, names=cols)\n', (5004, 5026), True, 'import pandas as pd\n'), ((6068, 6110), 'pandas.concat', 'pd.concat', (['[df_with_zero, df_without_zero]'], {}), '([df_with_zero, df_without_zero])\n', (6077, 6110), True, 'import pandas as pd\n'), ((6994, 7008), 'pandas.concat', 'pd.concat', (['dfs'], {}), '(dfs)\n', (7003, 7008), True, 'import pandas as pd\n'), ((7323, 7349), 'pandas.concat', 'pd.concat', (['[df, sample_df]'], {}), '([df, sample_df])\n', (7332, 7349), True, 'import pandas as pd\n'), ((9164, 9178), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (9176, 9178), True, 'import pandas as pd\n'), ((9193, 9207), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (9205, 9207), True, 'import pandas as pd\n'), ((9223, 9237), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (9235, 9237), True, 'import pandas as pd\n'), ((9259, 9273), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (9271, 9273), True, 'import pandas as pd\n'), ((10617, 10689), 'pandas.concat', 'pd.concat', (['[center_df, left_df, right_df, flipped_center, brightness_df]'], {}), '([center_df, left_df, right_df, flipped_center, brightness_df])\n', (10626, 10689), True, 'import pandas as pd\n'), ((11385, 11412), 'json.dump', 'json.dump', (['hist.history', 'fp'], {}), '(hist.history, fp)\n', (11394, 11412), False, 'import json\n'), ((15090, 15106), 'numpy.array', 'np.array', (['images'], {}), '(images)\n', (15098, 15106), True, 'import numpy as np\n'), ((15120, 15136), 'numpy.array', 'np.array', (['angles'], {}), '(angles)\n', (15128, 15136), True, 'import numpy as np\n'), ((15195, 15413), 'keras.preprocessing.image.ImageDataGenerator', 'ImageDataGenerator', ([], {'featurewise_center': '(False)', 'featurewise_std_normalization': '(False)', 'rotation_range': '(10)', 'width_shift_range': '(0.2)', 'height_shift_range': '(0.2)', 'zca_whitening': '(False)', 'channel_shift_range': '(0.2)', 'zoom_range': '(0.2)'}), '(featurewise_center=False, featurewise_std_normalization=\n False, rotation_range=10, width_shift_range=0.2, height_shift_range=0.2,\n zca_whitening=False, channel_shift_range=0.2, zoom_range=0.2)\n', (15213, 15413), False, 'from keras.preprocessing.image import ImageDataGenerator\n'), ((15788, 15813), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (15811, 15813), False, 'import argparse\n'), ((17361, 17378), 'keras.backend.clear_session', 'K.clear_session', ([], {}), '()\n', (17376, 17378), True, 'from keras import backend as K\n'), ((18592, 18627), 'sklearn.model_selection.train_test_split', 'train_test_split', (['df'], {'test_size': '(0.2)'}), '(df, test_size=0.2)\n', (18608, 18627), False, 'from sklearn.model_selection import train_test_split\n'), ((19878, 19895), 'keras.backend.clear_session', 'K.clear_session', ([], {}), '()\n', (19893, 19895), True, 'from keras import backend as K\n'), ((1595, 1671), 'sys.stdout.write', 'sys.stdout.write', (["('\\r%s |%s| %s%s %s' % (prefix, bar, percents, '%', suffix))"], {}), "('\\r%s |%s| %s%s %s' % (prefix, bar, percents, '%', suffix))\n", (1611, 1671), False, 'import sys\n'), ((1709, 1731), 'sys.stdout.write', 'sys.stdout.write', (['"""\n"""'], {}), "('\\n')\n", (1725, 1731), False, 'import sys\n'), ((2541, 2605), 'keras.layers.Cropping2D', 'Cropping2D', ([], {'cropping': '((crop_size, 0), (0, 0))', 'input_shape': 'shape'}), '(cropping=((crop_size, 0), (0, 0)), input_shape=shape)\n', (2551, 2605), False, 'from keras.layers import Flatten, Dense, Convolution2D, MaxPool2D, BatchNormalization, Dropout, Activation, Cropping2D, Lambda\n'), ((2621, 2654), 'keras.layers.Lambda', 'Lambda', (['(lambda x: x / 255.0 - 0.5)'], {}), '(lambda x: x / 255.0 - 0.5)\n', (2627, 2654), False, 'from keras.layers import Flatten, Dense, Convolution2D, MaxPool2D, BatchNormalization, Dropout, Activation, Cropping2D, Lambda\n'), ((2672, 2717), 'keras.layers.BatchNormalization', 'BatchNormalization', ([], {'axis': '(1)', 'input_shape': 'shape'}), '(axis=1, input_shape=shape)\n', (2690, 2717), False, 'from keras.layers import Flatten, Dense, Convolution2D, MaxPool2D, BatchNormalization, Dropout, Activation, Cropping2D, Lambda\n'), ((3761, 3770), 'keras.layers.Flatten', 'Flatten', ([], {}), '()\n', (3768, 3770), False, 'from keras.layers import Flatten, Dense, Convolution2D, MaxPool2D, BatchNormalization, Dropout, Activation, Cropping2D, Lambda\n'), ((3935, 3947), 'keras.layers.Dropout', 'Dropout', (['(0.5)'], {}), '(0.5)\n', (3942, 3947), False, 'from keras.layers import Flatten, Dense, Convolution2D, MaxPool2D, BatchNormalization, Dropout, Activation, Cropping2D, Lambda\n'), ((3962, 3979), 'keras.layers.Activation', 'Activation', (['"""elu"""'], {}), "('elu')\n", (3972, 3979), False, 'from keras.layers import Flatten, Dense, Convolution2D, MaxPool2D, BatchNormalization, Dropout, Activation, Cropping2D, Lambda\n'), ((4144, 4161), 'keras.layers.Activation', 'Activation', (['"""elu"""'], {}), "('elu')\n", (4154, 4161), False, 'from keras.layers import Flatten, Dense, Convolution2D, MaxPool2D, BatchNormalization, Dropout, Activation, Cropping2D, Lambda\n'), ((4758, 4780), 'random.uniform', 'random.uniform', (['(0)', '(100)'], {}), '(0, 100)\n', (4772, 4780), False, 'import random\n'), ((8549, 8570), 'numpy.array', 'np.array', (['all_samples'], {}), '(all_samples)\n', (8557, 8570), True, 'import numpy as np\n'), ((8572, 8594), 'numpy.array', 'np.array', (['measurements'], {}), '(measurements)\n', (8580, 8594), True, 'import numpy as np\n'), ((10720, 10735), 'sklearn.utils.shuffle', 'shuffle', (['new_df'], {}), '(new_df)\n', (10727, 10735), False, 'from sklearn.utils import shuffle\n'), ((11920, 11936), 'sklearn.utils.shuffle', 'shuffle', (['samples'], {}), '(samples)\n', (11927, 11936), False, 'from sklearn.utils import shuffle\n'), ((12968, 12984), 'sklearn.utils.shuffle', 'shuffle', (['samples'], {}), '(samples)\n', (12975, 12984), False, 'from sklearn.utils import shuffle\n'), ((15526, 15549), 'sklearn.utils.shuffle', 'shuffle', (['images', 'angles'], {}), '(images, angles)\n', (15533, 15549), False, 'from sklearn.utils import shuffle\n'), ((18372, 18400), 'pandas.concat', 'pd.concat', (['[df, recovery_df]'], {}), '([df, recovery_df])\n', (18381, 18400), True, 'import pandas as pd\n'), ((19149, 19314), 'keras.callbacks.ModelCheckpoint', 'ModelCheckpoint', (["('latest_run/' + args.experiment + '_' + args.network +\n '_{epoch:02d}-{val_loss:.2f}.h5')"], {'monitor': '"""val_loss"""', 'save_best_only': '(True)', 'verbose': '(1)'}), "('latest_run/' + args.experiment + '_' + args.network +\n '_{epoch:02d}-{val_loss:.2f}.h5', monitor='val_loss', save_best_only=\n True, verbose=1)\n", (19164, 19314), False, 'from keras.callbacks import Callback, ModelCheckpoint\n'), ((4618, 4634), 'scipy.misc.imread', 'imread', (['filename'], {}), '(filename)\n', (4624, 4634), False, 'from scipy.misc import imread\n'), ((6597, 6615), 'os.scandir', 'os.scandir', (['"""data"""'], {}), "('data')\n", (6607, 6615), False, 'import os\n'), ((10490, 10514), 'numpy.random.uniform', 'np.random.uniform', (['(-1)', '(1)'], {}), '(-1, 1)\n', (10507, 10514), True, 'import numpy as np\n'), ((12803, 12819), 'numpy.array', 'np.array', (['images'], {}), '(images)\n', (12811, 12819), True, 'import numpy as np\n'), ((12836, 12852), 'numpy.array', 'np.array', (['angles'], {}), '(angles)\n', (12844, 12852), True, 'import numpy as np\n'), ((13841, 13857), 'numpy.array', 'np.array', (['images'], {}), '(images)\n', (13849, 13857), True, 'import numpy as np\n'), ((13874, 13890), 'numpy.array', 'np.array', (['angles'], {}), '(angles)\n', (13882, 13890), True, 'import numpy as np\n'), ((2844, 2871), 'keras.regularizers.l2', 'l2', (['l2_regularization_scale'], {}), '(l2_regularization_scale)\n', (2846, 2871), False, 'from keras.regularizers import l2\n'), ((2904, 2931), 'keras.regularizers.l2', 'l2', (['l2_regularization_scale'], {}), '(l2_regularization_scale)\n', (2906, 2931), False, 'from keras.regularizers import l2\n'), ((3059, 3086), 'keras.regularizers.l2', 'l2', (['l2_regularization_scale'], {}), '(l2_regularization_scale)\n', (3061, 3086), False, 'from keras.regularizers import l2\n'), ((3119, 3146), 'keras.regularizers.l2', 'l2', (['l2_regularization_scale'], {}), '(l2_regularization_scale)\n', (3121, 3146), False, 'from keras.regularizers import l2\n'), ((3258, 3285), 'keras.regularizers.l2', 'l2', (['l2_regularization_scale'], {}), '(l2_regularization_scale)\n', (3260, 3285), False, 'from keras.regularizers import l2\n'), ((3318, 3345), 'keras.regularizers.l2', 'l2', (['l2_regularization_scale'], {}), '(l2_regularization_scale)\n', (3320, 3345), False, 'from keras.regularizers import l2\n'), ((3457, 3484), 'keras.regularizers.l2', 'l2', (['l2_regularization_scale'], {}), '(l2_regularization_scale)\n', (3459, 3484), False, 'from keras.regularizers import l2\n'), ((3517, 3544), 'keras.regularizers.l2', 'l2', (['l2_regularization_scale'], {}), '(l2_regularization_scale)\n', (3519, 3544), False, 'from keras.regularizers import l2\n'), ((3656, 3683), 'keras.regularizers.l2', 'l2', (['l2_regularization_scale'], {}), '(l2_regularization_scale)\n', (3658, 3683), False, 'from keras.regularizers import l2\n'), ((3716, 3743), 'keras.regularizers.l2', 'l2', (['l2_regularization_scale'], {}), '(l2_regularization_scale)\n', (3718, 3743), False, 'from keras.regularizers import l2\n'), ((3830, 3857), 'keras.regularizers.l2', 'l2', (['l2_regularization_scale'], {}), '(l2_regularization_scale)\n', (3832, 3857), False, 'from keras.regularizers import l2\n'), ((3890, 3917), 'keras.regularizers.l2', 'l2', (['l2_regularization_scale'], {}), '(l2_regularization_scale)\n', (3892, 3917), False, 'from keras.regularizers import l2\n'), ((4039, 4066), 'keras.regularizers.l2', 'l2', (['l2_regularization_scale'], {}), '(l2_regularization_scale)\n', (4041, 4066), False, 'from keras.regularizers import l2\n'), ((4099, 4126), 'keras.regularizers.l2', 'l2', (['l2_regularization_scale'], {}), '(l2_regularization_scale)\n', (4101, 4126), False, 'from keras.regularizers import l2\n'), ((4220, 4247), 'keras.regularizers.l2', 'l2', (['l2_regularization_scale'], {}), '(l2_regularization_scale)\n', (4222, 4247), False, 'from keras.regularizers import l2\n'), ((4280, 4307), 'keras.regularizers.l2', 'l2', (['l2_regularization_scale'], {}), '(l2_regularization_scale)\n', (4282, 4307), False, 'from keras.regularizers import l2\n'), ((13909, 13922), 'sklearn.utils.shuffle', 'shuffle', (['X', 'y'], {}), '(X, y)\n', (13916, 13922), False, 'from sklearn.utils import shuffle\n'), ((15644, 15669), 'sklearn.utils.shuffle', 'shuffle', (['X_train', 'y_train'], {}), '(X_train, y_train)\n', (15651, 15669), False, 'from sklearn.utils import shuffle\n')]
import numpy as np import cv2 import os import os.path as osp from torch.utils.data import Dataset import elasticdeform as ED class DatasetGen(Dataset): def __init__(self, train_path, gt_path, transform): super(DatasetGen, self).__init__() self.train_names = self.get_file_names(train_path) self.gt_names = self.get_file_names(gt_path) self.transform = transform def __getitem__(self, index): train_image = self.img_standardization(cv2.imread(self.train_names[index],-1))#转为8位3通道 gt_image = self.unit16b2uint8(cv2.imread(self.gt_names[index],-1))#转为8位 train_image = self.trans(train_image) gt_image = self.trans(gt_image) if self.transform is not None: train_image = self.transform(train_image) gt_image = (np.where(gt_image == 0,0,1)).astype(np.uint8)#二值化 return train_image, gt_image def __len__(self): return len(self.train_names) def trans(self, img): return img def img_standardization(self, img): img = self.unit16b2uint8(img) if len(img.shape) == 2: img = np.expand_dims(img, 2) img = np.tile(img, (1, 1, 3)) return img elif len(img.shape) == 3: return img else: raise TypeError('The Depth of image large than 3 \n') def get_file_names(self, file_path): return sorted([osp.join(file_path, image_name) for image_name in os.listdir(file_path)]) def unit16b2uint8(self, img): if img.dtype == 'uint8': return img elif img.dtype == 'uint16': return img.astype(np.uint8) else: raise TypeError('No such of img transfer type: {} for img'.format(img.dtype)) class DatasetHGen(DatasetGen):#Horizontal def __init__(self, train_path, gt_path, transform): super().__init__(train_path, gt_path, transform) def trans(self, img): return cv2.flip(img, 1) class DatasetVGen(DatasetGen):#Vertical def __init__(self, train_path, gt_path, transform): super().__init__(train_path, gt_path, transform) def trans(self, img): return cv2.flip(img, 0) class DatasetHVGen(DatasetGen):#Horizontal + Vertical def __init__(self, train_path, gt_path, transform): super().__init__(train_path, gt_path, transform) def trans(self, img): return cv2.flip(img, -1) class DatasetR90Gen(DatasetGen): def __init__(self, train_path, gt_path, transform): super().__init__(train_path, gt_path, transform) def trans(self, img): img = cv2.flip(cv2.transpose(img), 0) return img class DatasetR270Gen(DatasetGen): def __init__(self, train_path, gt_path, transform): super().__init__(train_path, gt_path, transform) def trans(self, img): img = cv2.flip(cv2.transpose(img), 1) return img class DatasetTPGen(DatasetGen): def __init__(self, train_path, gt_path, transform): super().__init__(train_path, gt_path, transform) def trans(self, img): img = cv2.transpose(img) return img class DatasetSTPGen(DatasetGen): def __init__(self, train_path, gt_path, transform): super().__init__(train_path, gt_path, transform) def trans(self, img): img = cv2.transpose(cv2.flip(img, -1)) return img class DatasetEDGen(DatasetGen): def __init__(self, train_path, gt_path, transform, sigma, points, order): super().__init__(train_path, gt_path, transform) self.sigma = sigma self.points = points self.order = order def __getitem__(self, index): train_image = super().img_standardization(cv2.imread(self.train_names[index],-1)) gt_image = super().unit16b2uint8(cv2.imread(self.gt_names[index],-1)) gt_image = (np.where(gt_image == 0,0,1)).astype(np.uint8) #ElasticDeformation [train_image, gt_image] = ED.deform_random_grid([train_image, gt_image], sigma=self.sigma, points=self.points, order=self.order, axis=[(0,1), (0,1)]) if self.transform is not None: train_image = self.transform(train_image) return train_image, gt_image
[ "numpy.expand_dims", "cv2.transpose", "cv2.imread", "elasticdeform.deform_random_grid", "numpy.where", "numpy.tile", "cv2.flip", "os.path.join", "os.listdir" ]
[((2024, 2040), 'cv2.flip', 'cv2.flip', (['img', '(1)'], {}), '(img, 1)\n', (2032, 2040), False, 'import cv2\n'), ((2249, 2265), 'cv2.flip', 'cv2.flip', (['img', '(0)'], {}), '(img, 0)\n', (2257, 2265), False, 'import cv2\n'), ((2484, 2501), 'cv2.flip', 'cv2.flip', (['img', '(-1)'], {}), '(img, -1)\n', (2492, 2501), False, 'import cv2\n'), ((3200, 3218), 'cv2.transpose', 'cv2.transpose', (['img'], {}), '(img)\n', (3213, 3218), False, 'import cv2\n'), ((4073, 4203), 'elasticdeform.deform_random_grid', 'ED.deform_random_grid', (['[train_image, gt_image]'], {'sigma': 'self.sigma', 'points': 'self.points', 'order': 'self.order', 'axis': '[(0, 1), (0, 1)]'}), '([train_image, gt_image], sigma=self.sigma, points=\n self.points, order=self.order, axis=[(0, 1), (0, 1)])\n', (4094, 4203), True, 'import elasticdeform as ED\n'), ((489, 528), 'cv2.imread', 'cv2.imread', (['self.train_names[index]', '(-1)'], {}), '(self.train_names[index], -1)\n', (499, 528), False, 'import cv2\n'), ((575, 611), 'cv2.imread', 'cv2.imread', (['self.gt_names[index]', '(-1)'], {}), '(self.gt_names[index], -1)\n', (585, 611), False, 'import cv2\n'), ((1174, 1196), 'numpy.expand_dims', 'np.expand_dims', (['img', '(2)'], {}), '(img, 2)\n', (1188, 1196), True, 'import numpy as np\n'), ((1215, 1238), 'numpy.tile', 'np.tile', (['img', '(1, 1, 3)'], {}), '(img, (1, 1, 3))\n', (1222, 1238), True, 'import numpy as np\n'), ((2711, 2729), 'cv2.transpose', 'cv2.transpose', (['img'], {}), '(img)\n', (2724, 2729), False, 'import cv2\n'), ((2959, 2977), 'cv2.transpose', 'cv2.transpose', (['img'], {}), '(img)\n', (2972, 2977), False, 'import cv2\n'), ((3448, 3465), 'cv2.flip', 'cv2.flip', (['img', '(-1)'], {}), '(img, -1)\n', (3456, 3465), False, 'import cv2\n'), ((3826, 3865), 'cv2.imread', 'cv2.imread', (['self.train_names[index]', '(-1)'], {}), '(self.train_names[index], -1)\n', (3836, 3865), False, 'import cv2\n'), ((3907, 3943), 'cv2.imread', 'cv2.imread', (['self.gt_names[index]', '(-1)'], {}), '(self.gt_names[index], -1)\n', (3917, 3943), False, 'import cv2\n'), ((834, 863), 'numpy.where', 'np.where', (['(gt_image == 0)', '(0)', '(1)'], {}), '(gt_image == 0, 0, 1)\n', (842, 863), True, 'import numpy as np\n'), ((1468, 1499), 'os.path.join', 'osp.join', (['file_path', 'image_name'], {}), '(file_path, image_name)\n', (1476, 1499), True, 'import os.path as osp\n'), ((3964, 3993), 'numpy.where', 'np.where', (['(gt_image == 0)', '(0)', '(1)'], {}), '(gt_image == 0, 0, 1)\n', (3972, 3993), True, 'import numpy as np\n'), ((1518, 1539), 'os.listdir', 'os.listdir', (['file_path'], {}), '(file_path)\n', (1528, 1539), False, 'import os\n')]
import torch import imageio from python_speech_features import mfcc, delta, logfbank import librosa import pandas as pd import numpy as np from torch.utils.data import Dataset class LRWDataset(Dataset): COL_MP4 = 'mp4' COL_MP3 = 'mp3' COL_TXT = 'txt' def __init__(self, root_dir, clean_files_path, is_train=True, is_dev=False): self.root_dir = root_dir self.df = self._get_files(root_dir, clean_files_path, is_train, is_dev) self.char_list = ( 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '<sos>', '<eos>', '<pad>', '\'',) self.index_list = [i for i in range(len(self.char_list))] self.index_of_str = dict(zip(self.char_list, self.index_list)) self.char_of_index = dict(zip(self.index_list, self.char_list)) self.total_num = self.index_list[-1] + 1 def __len__(self): return len(self.df) def __getitem__(self, idx): mp4, mp3, txt = self._get_records(idx) reversed_mp3 = self._get_mp3_as_tensor(self.root_dir + mp3) reversed_txt = self._get_txt_as_tensor(self.root_dir + txt) reversed_mp4 = self._get_frames_as_tensors(self.root_dir + mp4) return reversed_mp4, reversed_mp3, reversed_txt def _get_files(self, root_dir, file_path, is_train=True, is_dev=False): df = pd.read_csv(root_dir + file_path) if is_dev: return df if is_train: return df[df['is_train'] == 1] else: return df[df['is_train'] == 0] def _get_records(self, idx): record = self.df.iloc[idx] mp4 = record[LRWDataset.COL_MP4] mp3 = record[LRWDataset.COL_MP3] txt = record[LRWDataset.COL_TXT] return mp4, mp3, txt def _get_reversed_txt_as_tensor(self, txt_file): ascii = self._get_txt_as_tensor(txt_file) rev_ascii = torch.flip(ascii, [0]) return rev_ascii def _get_txt_as_tensor(self, txt_file, txtMaxLen=800): tmp = [] with open(txt_file, 'r') as f: content = f.readline() tmp = [self.index_of_str[i] for i in content.split(':')[1].replace(' ', '').rstrip('\n')] + [self.index_of_str['<eos>']] # if len(tmp) < txtMaxLen: # tmp += [self.index_of_str['<pad>'] for _ in range(txtMaxLen - len(tmp))] # else: # print(len(tmp)) # raise Exception('too short txt max length') return torch.Tensor(tmp) def _get_txt_as_tensor_old(self, txt_file): with open(txt_file, 'r') as f: content = f.readline() ascii = np.array([ord(c) - 32 for c in content.replace('Text:', '').strip()]) ascii = np.append(ascii, [-2]) ascii = np.insert(ascii, 0, [-1]) ascii = torch.autograd.Variable(torch.from_numpy(ascii.astype(int)).int()) return ascii def _get_reversed_frames_as_tensors(self, mp4_file): frames = self._get_frames_as_tensors(mp4_file) rev_frames = torch.flip(frames, [0]) return rev_frames def _get_frames_as_tensors(self, mp4_file): reader = imageio.get_reader(mp4_file) imgs = np.array(reader.get_data(0)) imgs = imgs.reshape(1, *imgs.shape) count = reader.count_frames() for i in range(1, count): frame = np.array(reader.get_data(i)) frame = frame.reshape(1, *frame.shape) imgs = np.vstack((imgs, frame)) frames = torch.from_numpy(imgs) frames = frames.float() return frames def _get_reversed_mp3_as_tensor(self, mp3_file, dim=13, window_size=25, stride=10, method='psf'): windows = self._get_mp3_as_tensor(mp3_file) rev_windows = torch.flip(windows, [1]) return rev_windows def _get_mp3_as_tensor(self, mp3_file, dim=13, window_size=25, stride=10, method='psf'): if method == 'psf': feat = self._get_audio_feat_psf(mp3_file, dim, window_size, stride) else: feat = self._get_audio_feat_librosa(mp3_file, dim, window_size, stride) mfcc = zip(*feat) mfcc = np.stack([np.array(i) for i in mfcc]) cc = np.expand_dims(mfcc, axis=0) # cc = np.expand_dims(np.expand_dims(mfcc, axis=0),axis=0) cct = torch.autograd.Variable(torch.from_numpy(cc.astype(float)).float()) cct = cct.view(13, -1) return cct def _get_audio_feat_psf(self, mp3_file, dim=13, window_size=25, stride=10): sig, rate = librosa.load(mp3_file, sr=None) feat = mfcc(sig, samplerate=rate, numcep=dim, winlen=window_size / 1000, winstep=stride / 1000) return feat def _get_audio_feat_librosa(self, mp3_file, dim=13, window_size=25, stride=10, feature='mfcc', cmvn=False, delta=False, delta_delta=False, save_feature=None): y, sr = librosa.load(mp3_file, sr=None) ws = int(sr * 0.001 * window_size) st = int(sr * 0.001 * stride) if feature == 'fbank': # log-scaled feat = librosa.feature.melspectrogram(y=y, sr=sr, n_mels=dim, n_fft=ws, hop_length=st) feat = np.log(feat + 1e-6) elif feature == 'mfcc': feat = librosa.feature.mfcc(y=y, sr=sr, n_mfcc=dim, n_mels=26, n_fft=ws, hop_length=st) feat[0] = librosa.feature.rmse(y, hop_length=st, frame_length=ws) else: raise ValueError('Unsupported Acoustic Feature: ' + feature) feat = [feat] if delta: feat.append(librosa.feature.delta(feat[0])) if delta_delta: feat.append(librosa.feature.delta(feat[0], order=2)) feat = np.concatenate(feat, axis=0) if cmvn: feat = (feat - feat.mean(axis=1)[:, np.newaxis]) / (feat.std(axis=1) + 1e-16)[:, np.newaxis] if save_feature is not None: tmp = np.swapaxes(feat, 0, 1).astype('float32') np.save(save_feature, tmp) return len(tmp) else: return np.swapaxes(feat, 0, 1).astype('float32')
[ "pandas.read_csv", "librosa.feature.mfcc", "librosa.feature.melspectrogram", "numpy.insert", "numpy.append", "librosa.feature.rmse", "torch.Tensor", "numpy.swapaxes", "imageio.get_reader", "numpy.save", "librosa.feature.delta", "librosa.load", "python_speech_features.mfcc", "numpy.vstack",...
[((1348, 1381), 'pandas.read_csv', 'pd.read_csv', (['(root_dir + file_path)'], {}), '(root_dir + file_path)\n', (1359, 1381), True, 'import pandas as pd\n'), ((1797, 1819), 'torch.flip', 'torch.flip', (['ascii', '[0]'], {}), '(ascii, [0])\n', (1807, 1819), False, 'import torch\n'), ((2304, 2321), 'torch.Tensor', 'torch.Tensor', (['tmp'], {}), '(tmp)\n', (2316, 2321), False, 'import torch\n'), ((2517, 2539), 'numpy.append', 'np.append', (['ascii', '[-2]'], {}), '(ascii, [-2])\n', (2526, 2539), True, 'import numpy as np\n'), ((2550, 2575), 'numpy.insert', 'np.insert', (['ascii', '(0)', '[-1]'], {}), '(ascii, 0, [-1])\n', (2559, 2575), True, 'import numpy as np\n'), ((2787, 2810), 'torch.flip', 'torch.flip', (['frames', '[0]'], {}), '(frames, [0])\n', (2797, 2810), False, 'import torch\n'), ((2888, 2916), 'imageio.get_reader', 'imageio.get_reader', (['mp4_file'], {}), '(mp4_file)\n', (2906, 2916), False, 'import imageio\n'), ((3181, 3203), 'torch.from_numpy', 'torch.from_numpy', (['imgs'], {}), '(imgs)\n', (3197, 3203), False, 'import torch\n'), ((3408, 3432), 'torch.flip', 'torch.flip', (['windows', '[1]'], {}), '(windows, [1])\n', (3418, 3432), False, 'import torch\n'), ((3795, 3823), 'numpy.expand_dims', 'np.expand_dims', (['mfcc'], {'axis': '(0)'}), '(mfcc, axis=0)\n', (3809, 3823), True, 'import numpy as np\n'), ((4091, 4122), 'librosa.load', 'librosa.load', (['mp3_file'], {'sr': 'None'}), '(mp3_file, sr=None)\n', (4103, 4122), False, 'import librosa\n'), ((4132, 4225), 'python_speech_features.mfcc', 'mfcc', (['sig'], {'samplerate': 'rate', 'numcep': 'dim', 'winlen': '(window_size / 1000)', 'winstep': '(stride / 1000)'}), '(sig, samplerate=rate, numcep=dim, winlen=window_size / 1000, winstep=\n stride / 1000)\n', (4136, 4225), False, 'from python_speech_features import mfcc, delta, logfbank\n'), ((4435, 4466), 'librosa.load', 'librosa.load', (['mp3_file'], {'sr': 'None'}), '(mp3_file, sr=None)\n', (4447, 4466), False, 'import librosa\n'), ((5186, 5214), 'numpy.concatenate', 'np.concatenate', (['feat'], {'axis': '(0)'}), '(feat, axis=0)\n', (5200, 5214), True, 'import numpy as np\n'), ((3145, 3169), 'numpy.vstack', 'np.vstack', (['(imgs, frame)'], {}), '((imgs, frame))\n', (3154, 3169), True, 'import numpy as np\n'), ((4585, 4664), 'librosa.feature.melspectrogram', 'librosa.feature.melspectrogram', ([], {'y': 'y', 'sr': 'sr', 'n_mels': 'dim', 'n_fft': 'ws', 'hop_length': 'st'}), '(y=y, sr=sr, n_mels=dim, n_fft=ws, hop_length=st)\n', (4615, 4664), False, 'import librosa\n'), ((4716, 4736), 'numpy.log', 'np.log', (['(feat + 1e-06)'], {}), '(feat + 1e-06)\n', (4722, 4736), True, 'import numpy as np\n'), ((5407, 5433), 'numpy.save', 'np.save', (['save_feature', 'tmp'], {}), '(save_feature, tmp)\n', (5414, 5433), True, 'import numpy as np\n'), ((3760, 3771), 'numpy.array', 'np.array', (['i'], {}), '(i)\n', (3768, 3771), True, 'import numpy as np\n'), ((4772, 4857), 'librosa.feature.mfcc', 'librosa.feature.mfcc', ([], {'y': 'y', 'sr': 'sr', 'n_mfcc': 'dim', 'n_mels': '(26)', 'n_fft': 'ws', 'hop_length': 'st'}), '(y=y, sr=sr, n_mfcc=dim, n_mels=26, n_fft=ws, hop_length=st\n )\n', (4792, 4857), False, 'import librosa\n'), ((4897, 4952), 'librosa.feature.rmse', 'librosa.feature.rmse', (['y'], {'hop_length': 'st', 'frame_length': 'ws'}), '(y, hop_length=st, frame_length=ws)\n', (4917, 4952), False, 'import librosa\n'), ((5070, 5100), 'librosa.feature.delta', 'librosa.feature.delta', (['feat[0]'], {}), '(feat[0])\n', (5091, 5100), False, 'import librosa\n'), ((5136, 5175), 'librosa.feature.delta', 'librosa.feature.delta', (['feat[0]'], {'order': '(2)'}), '(feat[0], order=2)\n', (5157, 5175), False, 'import librosa\n'), ((5362, 5385), 'numpy.swapaxes', 'np.swapaxes', (['feat', '(0)', '(1)'], {}), '(feat, 0, 1)\n', (5373, 5385), True, 'import numpy as np\n'), ((5471, 5494), 'numpy.swapaxes', 'np.swapaxes', (['feat', '(0)', '(1)'], {}), '(feat, 0, 1)\n', (5482, 5494), True, 'import numpy as np\n')]
import numpy as np import pytest from grove.alpha.fermion_transforms.bktransform import BKTransform from grove.alpha.fermion_transforms.jwtransform import JWTransform """ Some tests inspired by: https://github.com/ProjectQ-Framework/FermiLib/blob/develop/src/fermilib/transforms/_bravyi_kitaev_test.py """ def test_hardcoded_transform(): n_qubits = 16 bkt = BKTransform(n_qubits) x = bkt.kill(9) y = bkt.create(9) assert str(x) == '(0.5+0j)*X9*Z7*Z8*X11*X15 + 0.5j*Y9*X11*X15*Z7' assert str(y) == '(0.5+0j)*X9*Z7*Z8*X11*X15 + -0.5j*Y9*X11*X15*Z7' def test_term_length(): # create/kill operators are two-term n_qubits = 16 bkt = BKTransform(n_qubits) assert len(bkt.create(3)) == 2 assert len(bkt.kill(3)) == 2 n_qubits = 7 bkt = BKTransform(n_qubits) assert len(bkt.create(3)) == 2 assert len(bkt.kill(3)) == 2 def test_throw_errors(): # throw error when creation outside qubit range n_qubits = 16 bkt = BKTransform(n_qubits) with pytest.raises(IndexError): bkt.kill(-1) with pytest.raises(IndexError): bkt.kill(16) with pytest.raises(IndexError): bkt.kill(17) def test_locality_invariant(): # for n_qubits = 2**d, c_j Majorana is always log2(N) + 1 local n_qubits = 16 bkt = BKTransform(n_qubits) invariant = np.log2(n_qubits) + 1 for index in range(n_qubits): op = bkt.kill(index) op_terms = op.terms for term in op_terms: coeff = term.coefficient # Identify the c Majorana terms by real # coefficients and check their length. if not isinstance(coeff, complex): assert len(term) == invariant @pytest.mark.skip(reason="pyQuil Pauli needs matrix operator / eigenspectrum " "functionality") def test_eigenspectrum(): # Jordan-Wigner and Bravyi-Kitaev operators should give same eigenspectrum # single number operator n_qubits = 16 bkt = BKTransform(n_qubits) op_BK = bkt.create(3) * bkt.kill(3) jwt = JWTransform() op_JW = jwt.create(3) * jwt.kill(3) assert np.sort(np.linalg.eigvals(op_BK.matrix())) == \ np.sort(np.linalg.eigvals(op_JW.matrix())) # sum of number operators op_BK = 0 op_JW = 0 for i in [1, 3, 5]: op_BK += bkt.create(i) * bkt.kill(i) op_JW += jwt.create(i) * jwt.kill(i) assert np.sort(np.linalg.eigvals(op_BK.matrix())) == \ np.sort(np.linalg.eigvals(op_JW.matrix())) # scaled number operator op_BK = 3 * bkt.create(3) * bkt.kill(3) op_JW = 3 * jwt.create(3) * jwt.kill(3) assert np.sort(np.linalg.eigvals(op_BK.matrix())) == \ np.sort(np.linalg.eigvals(op_JW.matrix()))
[ "grove.alpha.fermion_transforms.jwtransform.JWTransform", "numpy.log2", "pytest.raises", "grove.alpha.fermion_transforms.bktransform.BKTransform", "pytest.mark.skip" ]
[((1727, 1823), 'pytest.mark.skip', 'pytest.mark.skip', ([], {'reason': '"""pyQuil Pauli needs matrix operator / eigenspectrum functionality"""'}), "(reason=\n 'pyQuil Pauli needs matrix operator / eigenspectrum functionality')\n", (1743, 1823), False, 'import pytest\n'), ((370, 391), 'grove.alpha.fermion_transforms.bktransform.BKTransform', 'BKTransform', (['n_qubits'], {}), '(n_qubits)\n', (381, 391), False, 'from grove.alpha.fermion_transforms.bktransform import BKTransform\n'), ((671, 692), 'grove.alpha.fermion_transforms.bktransform.BKTransform', 'BKTransform', (['n_qubits'], {}), '(n_qubits)\n', (682, 692), False, 'from grove.alpha.fermion_transforms.bktransform import BKTransform\n'), ((789, 810), 'grove.alpha.fermion_transforms.bktransform.BKTransform', 'BKTransform', (['n_qubits'], {}), '(n_qubits)\n', (800, 810), False, 'from grove.alpha.fermion_transforms.bktransform import BKTransform\n'), ((986, 1007), 'grove.alpha.fermion_transforms.bktransform.BKTransform', 'BKTransform', (['n_qubits'], {}), '(n_qubits)\n', (997, 1007), False, 'from grove.alpha.fermion_transforms.bktransform import BKTransform\n'), ((1308, 1329), 'grove.alpha.fermion_transforms.bktransform.BKTransform', 'BKTransform', (['n_qubits'], {}), '(n_qubits)\n', (1319, 1329), False, 'from grove.alpha.fermion_transforms.bktransform import BKTransform\n'), ((2010, 2031), 'grove.alpha.fermion_transforms.bktransform.BKTransform', 'BKTransform', (['n_qubits'], {}), '(n_qubits)\n', (2021, 2031), False, 'from grove.alpha.fermion_transforms.bktransform import BKTransform\n'), ((2082, 2095), 'grove.alpha.fermion_transforms.jwtransform.JWTransform', 'JWTransform', ([], {}), '()\n', (2093, 2095), False, 'from grove.alpha.fermion_transforms.jwtransform import JWTransform\n'), ((1017, 1042), 'pytest.raises', 'pytest.raises', (['IndexError'], {}), '(IndexError)\n', (1030, 1042), False, 'import pytest\n'), ((1074, 1099), 'pytest.raises', 'pytest.raises', (['IndexError'], {}), '(IndexError)\n', (1087, 1099), False, 'import pytest\n'), ((1131, 1156), 'pytest.raises', 'pytest.raises', (['IndexError'], {}), '(IndexError)\n', (1144, 1156), False, 'import pytest\n'), ((1346, 1363), 'numpy.log2', 'np.log2', (['n_qubits'], {}), '(n_qubits)\n', (1353, 1363), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- import sys, os import numpy as np import pandas as pd from Modules.camera_location import cal_camera_location, estimate_camera_location from body_part_classification import BodyPartClassification, run_bpc __all__ = ["DivConqBPC", "discretization_setting"] def discretization_setting(discr_setting_filename=None): discr_regions = [] with open(discr_setting_filename, 'r') as fin: for line in fin: discr_regions.append([int(float(item)) for item in line.split(",") if (item != "" and item != "\n")]) return discr_regions def _is_in_discr_region(discr_region, filename_base=False, camera_location=None, filename=None): if filename_base: test_minimum_discr_region = int(filename.split("_")[-1]) if test_minimum_discr_region in discr_region: return True else: return False else: minimum_discr_regions = [[v, h, v + 10, h + 10] for v in range(10, 90, 10) for h in range(-35, 45, 10)] for i in discr_region: s = minimum_discr_regions[i] if s[0] <= camera_location[0] < s[2] and s[1] <= camera_location[1] < s[3]: return True return False class DivConqBPC(BodyPartClassification): def __init__(self, n_train_images=2000, n_target_pixels_per_image=2000, n_offsets=500, n_sep=1, discr_setting_type=None, discr_regions=None, intervals=None, for_clustering=False): BodyPartClassification.__init__(self, n_train_images, n_target_pixels_per_image, n_offsets, n_sep) self.rfs = [] self.discr_setting_type = discr_setting_type self.discr_regions = discr_regions self.intervals = intervals self.for_clustering = for_clustering def train(self, train_filenames): # Main intermediate_path = "/".join(train_filenames[0].split("/")[:-3]) + "/Intermediate/" if self.discr_regions is None: discr_setting_path = intermediate_path + "discretization_setting/" discr_setting_filename = "%s%s.csv" % (discr_setting_path, self.discr_setting_type) self.discr_regions = discretization_setting(discr_setting_filename) setting_str = self.train_setting_str min_discr_regions = list(range(64)) for discr_region in self.discr_regions: np.random.seed(1) self.train_setting_str = setting_str + "_" + str(discr_region) target_files = [] for train_filename in train_filenames: train_filename_id = "/".join(train_filename.split("/")[-2:]) appended = False np.random.shuffle(min_discr_regions) for min_discr_region in min_discr_regions: tmp_train_filename = "%s_%d" % (train_filename, min_discr_region) if min_discr_region in discr_region: if not appended: target_files.append(tmp_train_filename) appended = True if os.path.exists("%s%s_%d_features.gz" % (intermediate_path, train_filename_id, min_discr_region)) \ and os.path.exists("%s%s_%d_labels.gz" % (intermediate_path, train_filename_id, min_discr_region)): target_files[-1] = tmp_train_filename break #pd.DataFrame(["/".join(f.split("/")[-2:]) for f in target_files]).to_csv("/Volumes/PoseEstimation/Data/Main/BodyPartClassification/target_files.csv", header=False, index=False, mode='a') if discr_region[0] % 8 != 7: BodyPartClassification.train(self, np.array(target_files)) self.rfs.append(self.rf) self.train_setting_str = setting_str def predict(self, test_filename, save=True): img = None predict_probability = None target_pixels = None setting_str = self.test_setting_str if "CapturedVideos" in test_filename: cl_exst_probas = estimate_camera_location(test_filename+".mov", self.discr_regions) for i, discr_region in enumerate(self.discr_regions): self.rf = self.rfs[i] self.test_setting_str = setting_str + "_" + str(discr_region) if self.rf is None: raise RuntimeError("The target Random Forest is untrained.") else: if predict_probability is None: predict_probability = cl_exst_probas[i] * BodyPartClassification.predict(self, test_filename, save=save)[1] else: predict_probability += cl_exst_probas[i] * BodyPartClassification.predict(self, test_filename, save=save)[1] elif "CapturedImages" in test_filename: rad, azim, polar = estimate_camera_location(test_filename + ".png") for i, discr_region in enumerate(self.discr_regions): self.rf = self.rfs[i] self.test_setting_str = setting_str + "_" + str(discr_region) if _is_in_discr_region(discr_region, filename_base=False, camera_location=[polar, azim]) or self.for_clustering: if self.rf is None: raise RuntimeError("The target Random Forest is untrained.") else: img, predict_probability, target_pixels = BodyPartClassification.predict(self, test_filename, save=save) break else: continue elif "SyntheticImages" in test_filename: camera_location = cal_camera_location(test_filename + "_param") for i, discr_region in enumerate(self.discr_regions): self.rf = self.rfs[i] self.test_setting_str = setting_str + "_" + str(discr_region) if _is_in_discr_region(discr_region, filename_base=True, camera_location=camera_location, filename=test_filename) or self.for_clustering: if self.rf is None: raise RuntimeError("The target Random Forest is untrained.") else: img, predict_probability, target_pixels = BodyPartClassification.predict(self, test_filename, save=save) break else: continue else: raise ValueError("Invalid test file path.") self.test_setting_str = setting_str return img, predict_probability, target_pixels if __name__ == "__main__": run_bpc(DivConqBPC)
[ "numpy.random.seed", "body_part_classification.BodyPartClassification.predict", "body_part_classification.run_bpc", "os.path.exists", "numpy.array", "Modules.camera_location.cal_camera_location", "Modules.camera_location.estimate_camera_location", "numpy.random.shuffle", "body_part_classification.Bo...
[((6625, 6644), 'body_part_classification.run_bpc', 'run_bpc', (['DivConqBPC'], {}), '(DivConqBPC)\n', (6632, 6644), False, 'from body_part_classification import BodyPartClassification, run_bpc\n'), ((1470, 1572), 'body_part_classification.BodyPartClassification.__init__', 'BodyPartClassification.__init__', (['self', 'n_train_images', 'n_target_pixels_per_image', 'n_offsets', 'n_sep'], {}), '(self, n_train_images,\n n_target_pixels_per_image, n_offsets, n_sep)\n', (1501, 1572), False, 'from body_part_classification import BodyPartClassification, run_bpc\n'), ((2358, 2375), 'numpy.random.seed', 'np.random.seed', (['(1)'], {}), '(1)\n', (2372, 2375), True, 'import numpy as np\n'), ((4063, 4131), 'Modules.camera_location.estimate_camera_location', 'estimate_camera_location', (["(test_filename + '.mov')", 'self.discr_regions'], {}), "(test_filename + '.mov', self.discr_regions)\n", (4087, 4131), False, 'from Modules.camera_location import cal_camera_location, estimate_camera_location\n'), ((2658, 2694), 'numpy.random.shuffle', 'np.random.shuffle', (['min_discr_regions'], {}), '(min_discr_regions)\n', (2675, 2694), True, 'import numpy as np\n'), ((4876, 4924), 'Modules.camera_location.estimate_camera_location', 'estimate_camera_location', (["(test_filename + '.png')"], {}), "(test_filename + '.png')\n", (4900, 4924), False, 'from Modules.camera_location import cal_camera_location, estimate_camera_location\n'), ((3702, 3724), 'numpy.array', 'np.array', (['target_files'], {}), '(target_files)\n', (3710, 3724), True, 'import numpy as np\n'), ((5677, 5722), 'Modules.camera_location.cal_camera_location', 'cal_camera_location', (["(test_filename + '_param')"], {}), "(test_filename + '_param')\n", (5696, 5722), False, 'from Modules.camera_location import cal_camera_location, estimate_camera_location\n'), ((3077, 3177), 'os.path.exists', 'os.path.exists', (["('%s%s_%d_features.gz' % (intermediate_path, train_filename_id,\n min_discr_region))"], {}), "('%s%s_%d_features.gz' % (intermediate_path,\n train_filename_id, min_discr_region))\n", (3091, 3177), False, 'import sys, os\n'), ((3212, 3310), 'os.path.exists', 'os.path.exists', (["('%s%s_%d_labels.gz' % (intermediate_path, train_filename_id, min_discr_region)\n )"], {}), "('%s%s_%d_labels.gz' % (intermediate_path, train_filename_id,\n min_discr_region))\n", (3226, 3310), False, 'import sys, os\n'), ((5453, 5515), 'body_part_classification.BodyPartClassification.predict', 'BodyPartClassification.predict', (['self', 'test_filename'], {'save': 'save'}), '(self, test_filename, save=save)\n', (5483, 5515), False, 'from body_part_classification import BodyPartClassification, run_bpc\n'), ((4570, 4632), 'body_part_classification.BodyPartClassification.predict', 'BodyPartClassification.predict', (['self', 'test_filename'], {'save': 'save'}), '(self, test_filename, save=save)\n', (4600, 4632), False, 'from body_part_classification import BodyPartClassification, run_bpc\n'), ((4729, 4791), 'body_part_classification.BodyPartClassification.predict', 'BodyPartClassification.predict', (['self', 'test_filename'], {'save': 'save'}), '(self, test_filename, save=save)\n', (4759, 4791), False, 'from body_part_classification import BodyPartClassification, run_bpc\n'), ((6276, 6338), 'body_part_classification.BodyPartClassification.predict', 'BodyPartClassification.predict', (['self', 'test_filename'], {'save': 'save'}), '(self, test_filename, save=save)\n', (6306, 6338), False, 'from body_part_classification import BodyPartClassification, run_bpc\n')]
"""Construct an array by repeating A the number of times given by reps.""" import numpy import numpoly from .common import implements @implements(numpy.tile) def tile(A, reps): """ Construct an array by repeating A the number of times given by reps. If `reps` has length ``d``, the result will have dimension of ``max(d, A.ndim)``. If ``A.ndim < d``, `A` is promoted to be d-dimensional by prepending new axes. So a shape (3,) array is promoted to (1, 3) for 2-D replication, or shape (1, 1, 3) for 3-D replication. If this is not the desired behavior, promote `A` to d-dimensions manually before calling this function. If ``A.ndim > d``, `reps` is promoted to `A`.ndim by pre-pending 1's to it. Thus for an `A` of shape (2, 3, 4, 5), a `reps` of (2, 2) is treated as (1, 1, 2, 2). Args: A (numpoly.ndpoly): The input array. reps (numpy.ndarray): The number of repetitions of `A` along each axis. Returns: (numpoly.ndpoly): The tiled output array. Examples: >>> x = numpoly.symbols("x") >>> numpoly.tile(x, 4) polynomial([x, x, x, x]) >>> poly = numpoly.polynomial([[1, x-1], [x**2, x]]) >>> numpoly.tile(poly, 2) polynomial([[1, -1+x, 1, -1+x], [x**2, x, x**2, x]]) >>> numpoly.tile(poly, [2, 1]) polynomial([[1, -1+x], [x**2, x], [1, -1+x], [x**2, x]]) """ A = numpoly.aspolynomial(A) result = numpy.tile(A.values, reps=reps) return numpoly.aspolynomial(result, names=A.indeterminants)
[ "numpoly.aspolynomial", "numpy.tile" ]
[((1545, 1568), 'numpoly.aspolynomial', 'numpoly.aspolynomial', (['A'], {}), '(A)\n', (1565, 1568), False, 'import numpoly\n'), ((1582, 1613), 'numpy.tile', 'numpy.tile', (['A.values'], {'reps': 'reps'}), '(A.values, reps=reps)\n', (1592, 1613), False, 'import numpy\n'), ((1625, 1677), 'numpoly.aspolynomial', 'numpoly.aspolynomial', (['result'], {'names': 'A.indeterminants'}), '(result, names=A.indeterminants)\n', (1645, 1677), False, 'import numpoly\n')]
""" Everything that summarizes Fourier (or other transforms) into another frequency scale and summarizes frequency ranges """ import gammatone import librosa import numpy as np from .stage_meta import Analytic, DType, ToDo class FreqFilter(Analytic): def __init__(self, n_filts=24, sr=16000, window=512, hop=128, sum="log-mean"): fbank = lambda freq, bounds: self._fbank(freq, bounds, sr, window) self.scale = self._scale(sr, n_filts, 20) self.scale = np.array(sorted(self.scale)) self.widths = np.concatenate([[0], self.scale, [sr]]) self.widths = [(self.widths[x], self.widths[x + 2]) for x in range(len(self.scale))] self.filter = np.array([fbank(self.scale[x], self.widths[x]) for x in range(n_filts)], np.float32).T self.sr = sr self.n_filts = n_filts def output_dtype(self, input_dtype): if self.previous: input_dtype = self.previous.output_dtype(input_dtype) return DType("Array", [input_dtype.shape[0], self.n_filts], np.float32) def _function(self, recording): return np.dot(recording, self.filter) class ERBFilter(FreqFilter): """ ERBFilter base class, filter function should be supplied. """ _scale = lambda self, *args: gammatone.gtgram.centre_freqs(*args) class TriangularERB(ERBFilter): def _fbank(_, freq, bounds, sr, window): def filt_fn(x): if x < bounds[0] or x > bounds[1]: return 0. if x >= freq: return 1. - (x - freq) / (bounds[1] - freq) if x < freq: return 1. - (freq - x) / (freq - bounds[0]) filt_fn = np.vectorize(filt_fn) num_window = window // 2 + 1 filt = filt_fn(np.arange(num_window) * sr / window) return filt / filt.sum() class HarmonicTriangularERB(ERBFilter): """ Apply the triangular filter and then scale in time (with 2n 3n 4n... speed) Then add it with weights Then scale to unit max """ def _fbank(_, freq, bounds, sr, window): def filt_fn(x): if x < bounds[0] or x > bounds[1]: return 0. if x >= freq: return 1. - (x - freq) / (bounds[1] - freq) if x < freq: return 1. - (freq - x) / (freq - bounds[0]) filt_fn = np.vectorize(filt_fn) num_window = window // 2 + 1 filt = np.zeros(num_window, np.float32) for i in range(5): filt += filt_fn(np.arange(num_window) * sr / window / (i + 1)) / (i+1) return filt / filt.sum() class OverlappingHarmonicTriangularERB(ERBFilter): """ As HarmonicTraingularERB but with other bounds on the filters """ def _fbank(_, freq, bounds, sr, window): bounds = freq - bounds[0], freq + bounds[1] def filt_fn(x): if x < bounds[0] or x > bounds[1]: return 0. if x >= freq: return 1. - (x - freq) / (bounds[1] - freq) if x < freq: return 1. - (freq - x) / (freq - bounds[0]) filt_fn = np.vectorize(filt_fn) num_window = window // 2 + 1 filt = np.zeros(num_window, np.float32) for i in range(5): filt += filt_fn(np.arange(num_window) * sr / window / (i + 1)) / (i+1) return filt / filt.sum() class MelFilterbank(Analytic): def __init__(self, n_mels, fmin=20, fmax=8000, sr=16000): self.mel_basis = None self.n_mels = n_mels self.fmin = fmin self.fmax = fmax self.sr = sr def output_dtype(self, input_dtype): # print(input_dtype, "MELTI") if self.previous: input_dtype = self.previous.output_dtype(input_dtype) self.mel_basis = librosa.filters.mel(self.sr, (input_dtype.shape[1] - 1) * 2, self.n_mels, self.fmin, self.fmax).T return DType("Array", [input_dtype.shape[0], self.n_mels], np.float32) def _function(self, recording): return np.dot(recording, self.mel_basis) class TuningCurves(ToDo): """ How to implement that? """ class RoEx(ToDo): """ This is general filter but where weights are an integrated bell function """ def _fbank(_, freq, bounds, sr, window): pass class GammatoneFilterbank(Analytic): _sums = { "mean": lambda x: np.mean(x, axis=0), "log-mean": lambda x: np.log(np.abs(np.mean(x, axis=0))), "log-max": lambda x: np.log(np.max(np.abs(x), axis=0)), } def __init__(self, n_mels=24, sr=16000, window=512, hop=128, sum="log-mean"): self.scale = gammatone.gtgram.centre_freqs(sr, n_mels, 20) self.filterbank = gammatone.gtgram.make_erb_filters(sr, self.scale) self.window = window self.hop = hop self.sum = self._sums[sum] self.n_mels = n_mels def output_dtype(self, input_dtype): if self.previous: input_dtype = self.previous.output_dtype(input_dtype) return DType("Array", [int(np.ceil(1 + (input_dtype.shape[0] - self.window) / self.hop)), self.n_mels], np.float32) def _function(self, recording): gt = gammatone.gtgram.erb_filterbank(recording[:], self.filterbank).T length = int(np.ceil(1 + (gt.shape[0] - self.window) / self.hop)) ret = np.zeros([length, gt.shape[1]], np.float32) for i in range(length): ret[i, :] = self.sum(gt[i * self.hop : i * self.hop + self.window, :]) return ret class CARFAC(ToDo): pass
[ "gammatone.gtgram.centre_freqs", "numpy.vectorize", "numpy.ceil", "numpy.abs", "gammatone.gtgram.erb_filterbank", "numpy.zeros", "librosa.filters.mel", "numpy.mean", "numpy.arange", "numpy.dot", "gammatone.gtgram.make_erb_filters", "numpy.concatenate" ]
[((535, 574), 'numpy.concatenate', 'np.concatenate', (['[[0], self.scale, [sr]]'], {}), '([[0], self.scale, [sr]])\n', (549, 574), True, 'import numpy as np\n'), ((1099, 1129), 'numpy.dot', 'np.dot', (['recording', 'self.filter'], {}), '(recording, self.filter)\n', (1105, 1129), True, 'import numpy as np\n'), ((1276, 1312), 'gammatone.gtgram.centre_freqs', 'gammatone.gtgram.centre_freqs', (['*args'], {}), '(*args)\n', (1305, 1312), False, 'import gammatone\n'), ((1682, 1703), 'numpy.vectorize', 'np.vectorize', (['filt_fn'], {}), '(filt_fn)\n', (1694, 1703), True, 'import numpy as np\n'), ((2363, 2384), 'numpy.vectorize', 'np.vectorize', (['filt_fn'], {}), '(filt_fn)\n', (2375, 2384), True, 'import numpy as np\n'), ((2437, 2469), 'numpy.zeros', 'np.zeros', (['num_window', 'np.float32'], {}), '(num_window, np.float32)\n', (2445, 2469), True, 'import numpy as np\n'), ((3131, 3152), 'numpy.vectorize', 'np.vectorize', (['filt_fn'], {}), '(filt_fn)\n', (3143, 3152), True, 'import numpy as np\n'), ((3205, 3237), 'numpy.zeros', 'np.zeros', (['num_window', 'np.float32'], {}), '(num_window, np.float32)\n', (3213, 3237), True, 'import numpy as np\n'), ((4044, 4077), 'numpy.dot', 'np.dot', (['recording', 'self.mel_basis'], {}), '(recording, self.mel_basis)\n', (4050, 4077), True, 'import numpy as np\n'), ((4691, 4736), 'gammatone.gtgram.centre_freqs', 'gammatone.gtgram.centre_freqs', (['sr', 'n_mels', '(20)'], {}), '(sr, n_mels, 20)\n', (4720, 4736), False, 'import gammatone\n'), ((4763, 4812), 'gammatone.gtgram.make_erb_filters', 'gammatone.gtgram.make_erb_filters', (['sr', 'self.scale'], {}), '(sr, self.scale)\n', (4796, 4812), False, 'import gammatone\n'), ((5402, 5445), 'numpy.zeros', 'np.zeros', (['[length, gt.shape[1]]', 'np.float32'], {}), '([length, gt.shape[1]], np.float32)\n', (5410, 5445), True, 'import numpy as np\n'), ((3811, 3910), 'librosa.filters.mel', 'librosa.filters.mel', (['self.sr', '((input_dtype.shape[1] - 1) * 2)', 'self.n_mels', 'self.fmin', 'self.fmax'], {}), '(self.sr, (input_dtype.shape[1] - 1) * 2, self.n_mels,\n self.fmin, self.fmax)\n', (3830, 3910), False, 'import librosa\n'), ((4427, 4445), 'numpy.mean', 'np.mean', (['x'], {'axis': '(0)'}), '(x, axis=0)\n', (4434, 4445), True, 'import numpy as np\n'), ((5249, 5311), 'gammatone.gtgram.erb_filterbank', 'gammatone.gtgram.erb_filterbank', (['recording[:]', 'self.filterbank'], {}), '(recording[:], self.filterbank)\n', (5280, 5311), False, 'import gammatone\n'), ((5335, 5386), 'numpy.ceil', 'np.ceil', (['(1 + (gt.shape[0] - self.window) / self.hop)'], {}), '(1 + (gt.shape[0] - self.window) / self.hop)\n', (5342, 5386), True, 'import numpy as np\n'), ((1764, 1785), 'numpy.arange', 'np.arange', (['num_window'], {}), '(num_window)\n', (1773, 1785), True, 'import numpy as np\n'), ((4491, 4509), 'numpy.mean', 'np.mean', (['x'], {'axis': '(0)'}), '(x, axis=0)\n', (4498, 4509), True, 'import numpy as np\n'), ((4556, 4565), 'numpy.abs', 'np.abs', (['x'], {}), '(x)\n', (4562, 4565), True, 'import numpy as np\n'), ((5102, 5162), 'numpy.ceil', 'np.ceil', (['(1 + (input_dtype.shape[0] - self.window) / self.hop)'], {}), '(1 + (input_dtype.shape[0] - self.window) / self.hop)\n', (5109, 5162), True, 'import numpy as np\n'), ((2525, 2546), 'numpy.arange', 'np.arange', (['num_window'], {}), '(num_window)\n', (2534, 2546), True, 'import numpy as np\n'), ((3293, 3314), 'numpy.arange', 'np.arange', (['num_window'], {}), '(num_window)\n', (3302, 3314), True, 'import numpy as np\n')]
import numpy as np from multiagent.core import World, Agent, Landmark from multiagent.scenario import BaseScenario import random import sys from colorama import init init(strip=not sys.stdout.isatty()) # strip colors if stdout is redirected from termcolor import cprint from pyfiglet import figlet_format from threading import Timer class Scenario(BaseScenario): def __init__(self): self.score = 0 self.t = Timer(40, self.timeout) # duration is in seconds self.t.start() self.game_over = False self.obstacle_vel = [] def timeout(self): cprint(figlet_format('Game Over!\nFinal score: ' + str(self.score)), 'red') self.game_over = True def make_world(self): world = World() # set any world properties first world.dim_c = 2 num_agents = 6 world.num_agents = num_agents num_adversaries = num_agents - 1 num_landmarks = 1 num_obstacles = 1 # add agents world.agents = [Agent() for i in range(num_agents)] for i, agent in enumerate(world.agents): agent.name = 'agent %d' % i agent.collide = True agent.silent = True agent.adversary = True if i < num_adversaries else False agent.size = 0.08 if i < num_adversaries else 0.10 agent.max_speed = 0.9 if i < num_adversaries else None # add landmarks world.landmarks = [Landmark() for i in range(num_landmarks)] for i, landmark in enumerate(world.landmarks): landmark.name = 'landmark %d' % i landmark.collide = False landmark.movable = False landmark.size = 0.03 # add obstacle world.obstacles = [Landmark() for i in range(num_obstacles)] for i, obstacle in enumerate(world.obstacles): obstacle.name = 'obstacle %d' % i obstacle.collide = True obstacle.movable = True obstacle.size = 0.30 # make initial conditions for agent in world.agents: agent.state.p_pos = np.random.uniform(-1, +1, world.dim_p) agent.state.p_vel = np.zeros(world.dim_p) agent.state.c = np.zeros(world.dim_c) for obstacle in world.obstacles: obstacle.state.p_pos = np.random.uniform(-1, +1, world.dim_p) self.obstacle_vel = np.random.uniform(-1, +1, world.dim_p) obstacle.state.p_vel = self.obstacle_vel obstacle.state.c = np.zeros(world.dim_c) self.reset_world(world) return world def reset_world(self, world): # set properties for agents world.agents[-1].color = np.array([0.35, 0.65, 0.85]) for i in range(0, world.num_agents - 1): world.agents[i].color = np.array([0.85, 0.85, 0.85]) # set random initial states for agent in world.agents: pass for i, landmark in enumerate(world.landmarks): landmark.state.p_pos = np.random.uniform(-0.8, +0.8, world.dim_p) landmark.state.p_vel = np.zeros(world.dim_p) landmark.color = np.array([0.35, 0.35, 0.35]) for obstacle in world.obstacles: obstacle.color = np.array([0.70, 0.50, 0.95]) def benchmark_data(self, agent, world): # returns data for benchmarking purposes if agent.adversary: return np.sum(np.square(agent.state.p_pos - agent.goal_a.state.p_pos)) else: dists = [] for l in world.landmarks: dists.append(np.sum(np.square(agent.state.p_pos - l.state.p_pos))) dists.append(np.sum(np.square(agent.state.p_pos - agent.goal_a.state.p_pos))) return tuple(dists) # restrict movement of agent to inside screen def restrict_movement(self, agent, world): x_pos = agent.state.p_pos[0] y_pos = agent.state.p_pos[1] if agent.name == 'obstacle 0': if x_pos < -1.0: x_pos = +1.0 if y_pos < -1.0: y_pos = +1.0 if x_pos > +1.0: x_pos = -1.0 if y_pos > +1.0: y_pos = -1.0 else: if abs(x_pos) > 1.0 or abs(y_pos) > 1.0: pass # agent.state.p_vel = np.zeros(world.dim_p) if x_pos < -1.0: x_pos = -1.0 if y_pos < -1.0: y_pos = -1.0 if x_pos > +1.0: x_pos = +1.0 if y_pos > +1.0: y_pos = +1.0 agent.state.p_pos[0] = x_pos agent.state.p_pos[1] = y_pos # return all agents that are not adversaries def good_agents(self, world): return [agent for agent in world.agents if not agent.adversary] # return all adversarial agents def adversaries(self, world): return [agent for agent in world.agents if agent.adversary] def reward(self, agent, world): # Agents are rewarded based on minimum agent distance to each landmark return self.adversary_reward(agent, world) if agent.adversary else self.agent_reward(agent, world) def agent_reward(self, agent, world): # Rewarded based on how close the attacker agent is to the landmark l = world.landmarks[0] rew = -np.sqrt(np.sum(np.square(agent.state.p_pos - l.state.p_pos))) if np.sqrt(np.sum(np.square(agent.state.p_pos - l.state.p_pos))) < agent.size: self.score += 1 cprint(figlet_format('Score: ' + str(self.score)), 'blue') self.reset_world(world) self.restrict_movement(agent, world) return rew def adversary_reward(self, agent, world): # Punished based on how close attacker agent is to the defender rew = -np.sqrt(np.sum(np.square(agent.state.p_pos - world.agents[-1].state.p_pos))) return rew def observation(self, agent, world): for obstacle in world.obstacles: obstacle.state.p_vel = self.obstacle_vel self.restrict_movement(obstacle, world) # get positions of all entities in this agent's reference frame entity_pos = [] for entity in world.landmarks: entity_pos.append(entity.state.p_pos - agent.state.p_pos) # entity colors entity_color = [] for entity in world.landmarks: entity_color.append(entity.color) # communication of all other agents other_pos = [] for other in world.agents: if other is agent: continue other_pos.append(other.state.p_pos - agent.state.p_pos) return np.concatenate(entity_pos + other_pos)
[ "numpy.random.uniform", "threading.Timer", "numpy.square", "numpy.zeros", "multiagent.core.Landmark", "sys.stdout.isatty", "numpy.array", "multiagent.core.World", "numpy.concatenate", "multiagent.core.Agent" ]
[((431, 454), 'threading.Timer', 'Timer', (['(40)', 'self.timeout'], {}), '(40, self.timeout)\n', (436, 454), False, 'from threading import Timer\n'), ((747, 754), 'multiagent.core.World', 'World', ([], {}), '()\n', (752, 754), False, 'from multiagent.core import World, Agent, Landmark\n'), ((2700, 2728), 'numpy.array', 'np.array', (['[0.35, 0.65, 0.85]'], {}), '([0.35, 0.65, 0.85])\n', (2708, 2728), True, 'import numpy as np\n'), ((6534, 6572), 'numpy.concatenate', 'np.concatenate', (['(entity_pos + other_pos)'], {}), '(entity_pos + other_pos)\n', (6548, 6572), True, 'import numpy as np\n'), ((181, 200), 'sys.stdout.isatty', 'sys.stdout.isatty', ([], {}), '()\n', (198, 200), False, 'import sys\n'), ((1019, 1026), 'multiagent.core.Agent', 'Agent', ([], {}), '()\n', (1024, 1026), False, 'from multiagent.core import World, Agent, Landmark\n'), ((1459, 1469), 'multiagent.core.Landmark', 'Landmark', ([], {}), '()\n', (1467, 1469), False, 'from multiagent.core import World, Agent, Landmark\n'), ((1759, 1769), 'multiagent.core.Landmark', 'Landmark', ([], {}), '()\n', (1767, 1769), False, 'from multiagent.core import World, Agent, Landmark\n'), ((2108, 2146), 'numpy.random.uniform', 'np.random.uniform', (['(-1)', '(+1)', 'world.dim_p'], {}), '(-1, +1, world.dim_p)\n', (2125, 2146), True, 'import numpy as np\n'), ((2179, 2200), 'numpy.zeros', 'np.zeros', (['world.dim_p'], {}), '(world.dim_p)\n', (2187, 2200), True, 'import numpy as np\n'), ((2229, 2250), 'numpy.zeros', 'np.zeros', (['world.dim_c'], {}), '(world.dim_c)\n', (2237, 2250), True, 'import numpy as np\n'), ((2327, 2365), 'numpy.random.uniform', 'np.random.uniform', (['(-1)', '(+1)', 'world.dim_p'], {}), '(-1, +1, world.dim_p)\n', (2344, 2365), True, 'import numpy as np\n'), ((2398, 2436), 'numpy.random.uniform', 'np.random.uniform', (['(-1)', '(+1)', 'world.dim_p'], {}), '(-1, +1, world.dim_p)\n', (2415, 2436), True, 'import numpy as np\n'), ((2521, 2542), 'numpy.zeros', 'np.zeros', (['world.dim_c'], {}), '(world.dim_c)\n', (2529, 2542), True, 'import numpy as np\n'), ((2814, 2842), 'numpy.array', 'np.array', (['[0.85, 0.85, 0.85]'], {}), '([0.85, 0.85, 0.85])\n', (2822, 2842), True, 'import numpy as np\n'), ((3021, 3063), 'numpy.random.uniform', 'np.random.uniform', (['(-0.8)', '(+0.8)', 'world.dim_p'], {}), '(-0.8, +0.8, world.dim_p)\n', (3038, 3063), True, 'import numpy as np\n'), ((3099, 3120), 'numpy.zeros', 'np.zeros', (['world.dim_p'], {}), '(world.dim_p)\n', (3107, 3120), True, 'import numpy as np\n'), ((3150, 3178), 'numpy.array', 'np.array', (['[0.35, 0.35, 0.35]'], {}), '([0.35, 0.35, 0.35])\n', (3158, 3178), True, 'import numpy as np\n'), ((3249, 3275), 'numpy.array', 'np.array', (['[0.7, 0.5, 0.95]'], {}), '([0.7, 0.5, 0.95])\n', (3257, 3275), True, 'import numpy as np\n'), ((3426, 3481), 'numpy.square', 'np.square', (['(agent.state.p_pos - agent.goal_a.state.p_pos)'], {}), '(agent.state.p_pos - agent.goal_a.state.p_pos)\n', (3435, 3481), True, 'import numpy as np\n'), ((3673, 3728), 'numpy.square', 'np.square', (['(agent.state.p_pos - agent.goal_a.state.p_pos)'], {}), '(agent.state.p_pos - agent.goal_a.state.p_pos)\n', (3682, 3728), True, 'import numpy as np\n'), ((5217, 5261), 'numpy.square', 'np.square', (['(agent.state.p_pos - l.state.p_pos)'], {}), '(agent.state.p_pos - l.state.p_pos)\n', (5226, 5261), True, 'import numpy as np\n'), ((5290, 5334), 'numpy.square', 'np.square', (['(agent.state.p_pos - l.state.p_pos)'], {}), '(agent.state.p_pos - l.state.p_pos)\n', (5299, 5334), True, 'import numpy as np\n'), ((5699, 5758), 'numpy.square', 'np.square', (['(agent.state.p_pos - world.agents[-1].state.p_pos)'], {}), '(agent.state.p_pos - world.agents[-1].state.p_pos)\n', (5708, 5758), True, 'import numpy as np\n'), ((3594, 3638), 'numpy.square', 'np.square', (['(agent.state.p_pos - l.state.p_pos)'], {}), '(agent.state.p_pos - l.state.p_pos)\n', (3603, 3638), True, 'import numpy as np\n')]
from __future__ import absolute_import, division, print_function import numpy as np from .core import IdentityOperator, Operator from .flags import real, linear, square, inplace from .utils import isalias, split from .utils.mpi import MPI, as_mpi, distribute_shape, timer_mpi __all__ = ['MPIDistributionGlobalOperator', 'MPIDistributionIdentityOperator'] @real @linear class MPIDistributionGlobalOperator(Operator): """ Distribute sections of a global map to different MPI processes. It is a block column operator, whose blocks are distributed across the MPI processes. MPI rank 1 --> |I O O| +-----+ MPI rank 2 --> |O I O| +-----+ MPI rank 3 --> |O O I| Example ------- Given the file 'example_dgo.py': import numpy as np from pyoperators import DistributionGlobalOperator from mpi4py import MPI x_global = np.array([1,2,3]) d = DistributionGlobalOperator(x_global.shape) x_local = d(x_global) print MPI.COMM_WORLD.rank, ':', x_local, np.all(d.T(x_local) == x_global) the following command: $ mpirun -n 3 python example_dgo.py will output (in random rank order): 0 : [1] True 1 : [2] True 2 : [3] True """ def __init__(self, shapein, commout=None, **keywords): if shapein is None: raise ValueError('The input shape is None.') commout = commout or MPI.COMM_WORLD shapeout = distribute_shape(shapein, comm=commout) slice_ = split(shapein[0], commout.size, commout.rank) counts = [] offsets = [0] for s in split(shapein[0], commout.size): n = (s.stop - s.start) * np.product(shapein[1:]) counts.append(n) offsets.append(offsets[-1] + n) offsets.pop() Operator.__init__(self, commin=MPI.COMM_SELF, commout=commout, shapein=shapein, shapeout=shapeout, **keywords) self.slice = slice_ self.counts = counts self.offsets = offsets def direct(self, input, output): output[:] = input[self.slice.start:self.slice.stop] def transpose(self, input, output): if input.itemsize != output.itemsize: input = input.astype(output.dtype) nbytes = output.itemsize with timer_mpi: self.commout.Allgatherv( input.view(np.byte), [output.view(np.byte), ([c * nbytes for c in self.counts], [o * nbytes for o in self.offsets])]) @real @linear @square @inplace class MPIDistributionIdentityOperator(Operator): """ Distribute a global map, of which each MPI process has a copy, to the MPI processes. It is a block column operator whose blocks are identities distributed across the MPI processes. |1 O| MPI rank 0 --> | . | |O 1| +-----+ |1 O| MPI rank 1 --> | . | |O 1| +-----+ |1 O| MPI rank 2 --> | . | |O 1| For an MPI process, the direct method is the Identity and the transpose method is a reduction. Example ------- Given the file 'example_dio.py': import numpy as np from pyoperators import DistributionIdentityOperator from mpi4py import MPI x_global = np.array([1,1,1]) d = DistributionIdentityOperator() x_local = x_global * (MPI.COMM_WORLD.rank + 1) print MPI.COMM_WORLD.rank, ':', np.all(d(x_global)==x_global), d.T(x_local) the following command: $ mpirun -n 3 python example_dio.py will output (in random rank order): 0 : True [6 6 6] 1 : True [6 6 6] 2 : True [6 6 6] """ def __init__(self, commout=None, **keywords): if commout is None: commout = MPI.COMM_WORLD if commout.size == 1: self.__class__ = IdentityOperator self.__init__(**keywords) return Operator.__init__(self, commin=MPI.COMM_SELF, commout=commout or MPI.COMM_WORLD, **keywords) def direct(self, input, output): if isalias(input, output): return output[...] = input def transpose(self, input, output): if not isalias(input, output): output[...] = input with timer_mpi: self.commout.Allreduce(MPI.IN_PLACE, as_mpi(output), op=MPI.SUM)
[ "numpy.product" ]
[((1705, 1728), 'numpy.product', 'np.product', (['shapein[1:]'], {}), '(shapein[1:])\n', (1715, 1728), True, 'import numpy as np\n')]
""" Filename: plotting.py Author: <NAME>, <EMAIL> This script contains functions to read pre-processed NetCDF files, do some final analysis and plot the results. """ # Import modules from helpers import read_netcdf_dataset, get_config, save_fig_and_log, \ make_datelist, get_and_crop_radar_fobj from datetime import datetime, timedelta from cosmo_utils.plot import ax_contourf from cosmo_utils.pyncdf import getfobj_ncdf, getfobj_ncdf_ens from cosmo_utils.helpers import yymmddhhmm, ddhhmmss, yyyymmddhh_strtotime,\ make_timelist import matplotlib.pyplot as plt import numpy as np # Define functions def plot_domain_mean_timeseries_individual(inargs, plot_type): """ Function to plot time series of domain mean precipitation for each day Parameters ---------- inargs : argparse object Argparse object with all input arguments plot_type : str Type of plot. Must be 'precipitation' or 'cape_tauc' """ assert plot_type in ['precipitation', 'cape_tauc'], \ 'Type must be precipitation or cape_tauc' # Read pre-processed data rootgroup = read_netcdf_dataset(inargs) n_days = rootgroup.dimensions['date'].size # Set up figure n_cols = 4 n_rows = int(np.ceil(float(n_days) / n_cols)) fig, axmat = plt.subplots(n_rows, n_cols, sharex=True, sharey=True, figsize=(10, 3 * n_rows)) axflat = np.ravel(axmat) # Loop over axes / days for iday in range(n_days): dateobj = (timedelta(seconds=int(rootgroup.variables['date'][iday])) + datetime(1, 1, 1)) datestr = dateobj.strftime(get_config(inargs, 'plotting', 'date_fmt')) axflat[iday].set_title(datestr) if iday >= ((n_cols * n_rows) - n_cols): # Only bottom row axflat[iday].set_xlabel('Time [UTC]') if plot_type == 'precipitaiton': plot_precipitation_panel(inargs, axflat, iday, rootgroup) if plot_type == 'cape_tauc': plot_cape_tauc_panel(inargs, axflat, iday, rootgroup) # Finish figure axflat[0].legend(loc=0) plt.tight_layout() # Save figure save_fig_and_log(fig, rootgroup, inargs, plot_type + '_ts_individual') def plot_precipitation_panel(inargs, axflat, iday, rootgroup): """ Plots precipitation timeseries in each panel. Parameters ---------- inargs : argparse object Argparse object with all input arguments axflat : list List of axis objects iday : int Index for list object rootgroup : netCDF object NetCDF object with data to plot """ dateobj = (timedelta(seconds=int(rootgroup.variables['date'][iday])) + datetime(1, 1, 1)) datestr = dateobj.strftime(get_config(inargs, 'plotting', 'date_fmt')) axflat[iday].set_title(datestr) for group in rootgroup.groups: # Get data do be plotted # prec: det, obs or ens mean # prec_lower/upper: ensemble minimum, maximum if group == 'ens': prec_array = rootgroup.groups[group].variables['PREC_ACCUM'] \ [iday, :, :] prec = np.mean(prec_array, axis=1) prec_lower = np.amin(prec_array, axis=1) prec_upper = np.amax(prec_array, axis=1) else: prec = rootgroup.groups[group].variables['PREC_ACCUM'] \ [iday, :, 0] # Plot data axflat[iday].plot(rootgroup.variables['time'][:], prec, label=group, c=get_config(inargs, 'colors', group)) if group == 'ens': axflat[iday].fill_between(rootgroup.variables['time'][:], prec_lower, prec_upper, where=prec_upper >= prec_lower, facecolor=get_config(inargs, 'colors', 'ens_range')) def plot_cape_tauc_panel(inargs, axflat, iday, rootgroup): """ Plots cape and tau_c timeseries in each panel. Parameters ---------- inargs : argparse object Argparse object with all input arguments axflat : list List of axis objects iday : int Index for list object rootgroup : netCDF object NetCDF object with data to plot """ ax1 = axflat[iday] ax2 = ax1.twinx() ax2.set_ylim(0,20) dateobj = (timedelta(seconds=int(rootgroup.variables['date'][iday])) + datetime(1, 1, 1)) datestr = dateobj.strftime(get_config(inargs, 'plotting', 'date_fmt')) ax1.set_title(datestr) if iday % 4 == 0: # Only left column ax1.set_ylabel('CAPE [J/kg]') if iday % 4 == 3: ax2.set_ylabel('tau_c [h]') else: ax2.get_yaxis().set_ticks([]) for group in ['det', 'ens']: for var, ax, ls in zip(['CAPE_ML', 'TAU_C'], [ax1, ax2], ['-', '--']): # Get data do be plotted # prec: det, obs or ens mean # prec_lower/upper: ensemble minimum, maximum if group == 'ens': array = rootgroup.groups[group].variables[var][iday, :, :] mean = np.mean(array, axis=1) lower = np.amin(array, axis=1) upper = np.amax(array, axis=1) else: mean = rootgroup.groups[group].variables[var][iday, :, 0] # Plot data ax.plot(rootgroup.variables['time'][:], mean, label=group, c=get_config(inargs, 'colors', group), ls=ls) if group == 'ens': ax.fill_between(rootgroup.variables['time'][:], lower, upper, where=upper >= lower, facecolor=get_config(inargs, 'colors', 'ens_range')) def plot_domain_mean_timeseries_composite(inargs, plot_type): """ Function to plot time series of domain mean as a composite over all days Parameters ---------- inargs : argparse object Argparse object with all input arguments plot_type : str Type of plot. Must be 'precipitation' or 'cape_tauc' """ assert plot_type in ['precipitation', 'cape_tauc'], \ 'Type must be precipitation or cape_tauc' # Read pre-processed data rootgroup = read_netcdf_dataset(inargs) x = rootgroup.variables['time'][:] fig, ax1 = plt.subplots(1, 1, figsize=(3, 3)) if plot_type == 'precipitation': ax1.set_ylabel('Accumulation [mm/h]') for group in rootgroup.groups: array = rootgroup.groups[group].variables['PREC_ACCUM'][:] mean = np.mean(array, axis=(0,2)) ax1.plot(x, mean, label=group, c=get_config(inargs, 'colors', group)) if plot_type == 'cape_tauc': ax1.set_ylabel('CAPE [J/kg]') ax2 = ax1.twinx() ax2.set_ylabel('tau_c [h]') for group in ['det', 'ens']: for var, ax, ls in zip(['CAPE_ML', 'TAU_C'], [ax1, ax2], ['-', '--']): array = rootgroup.groups[group].variables[var][:] mean = np.mean(array, axis=(0, 2)) ax.plot(x, mean, label=group, c=get_config(inargs, 'colors', group), ls=ls) ax1.set_xlabel('Time [UTC]') dateobj_start = (timedelta(seconds=int(rootgroup.variables['date'][0])) + datetime(1,1,1)) datestr_start = dateobj_start.strftime(get_config(inargs, 'plotting', 'date_fmt')) dateobj_end = (timedelta(seconds=int(rootgroup.variables['date'][-1])) + datetime(1, 1, 1)) datestr_end = dateobj_end.strftime(get_config(inargs, 'plotting', 'date_fmt')) comp_str = 'Composite ' + datestr_start + ' - ' + datestr_end ax1.set_title(comp_str) ax1.legend(loc=0) plt.tight_layout() # Save figure and log save_fig_and_log(fig, rootgroup, inargs, plot_type + '_ts_composite') def plot_prec_stamps(inargs): """ Plots precipitation stamps of obs, det and ensemble every hour for each date and time specified Parameters ---------- inargs : argparse object Argparse object with all input arguments """ # TODO: Update colors cmPrec = ((1, 1, 1), (0, 0.627, 1), (0.137, 0.235, 0.98), (0.392, 0, 0.627), (0.784, 0, 0.627)) # (0.1 , 0.1 , 0.784), levelsPrec = [0, 1, 3, 10, 30, 100.] # Loop over dates for idate, date in enumerate(make_datelist(inargs)): # Loop over times for t in make_timelist(timedelta(hours=inargs.time_start), timedelta(hours=inargs.time_end), timedelta(hours=1)): # Load all CU objects fobjlist = [] titlelist = [] # 1st: Radar fobjlist.append(get_and_crop_radar_fobj(inargs, date, t)) titlelist.append('Radar') # 2nd: det ncdffn_pref = (get_config(inargs, 'paths', 'raw_data') + date + '/deout_ceu_pspens/' + 'det' + '/OUTPUT/lfff') fobjlist.append(getfobj_ncdf(ncdffn_pref + ddhhmmss(t) + '.nc_30m_surf', 'PREC_ACCUM')) titlelist.append('Det') # 3rd: ens ncdffn = 'lfff' + ddhhmmss(t) + '.nc_30m_surf' date_dir = (get_config(inargs, 'paths', 'raw_data') + date + '/deout_ceu_pspens/') fobjlist.extend(getfobj_ncdf_ens(date_dir, 'sub', inargs.nens, ncdffn, dir_suffix='/OUTPUT/', fieldn='PREC_ACCUM', nfill=1)) titlelist.extend(['Mem ' + str(i+1) for i in range(inargs.nens)]) # Now plot n_panels = len(fobjlist) n_cols = 4 n_rows = int(np.ceil(float(n_panels) / n_cols)) fig, axmat = plt.subplots(n_rows, n_cols, figsize=(10, 3.5 * n_rows)) axflat = np.ravel(axmat) for i in range(len(fobjlist)): plt.sca(axflat[i]) cf, tmp = ax_contourf(axflat[i], fobjlist[i], colors=cmPrec, pllevels=levelsPrec, ji0=(50 + inargs.zoom_lat1, 50 + inargs.zoom_lon1), ji1=(357-51 + inargs.zoom_lat2, 357-51 + inargs.zoom_lon2), sp_title=titlelist[i], Basemap_drawrivers=False, npars=0, nmers=0) cb = fig.colorbar(cf, cax=fig.add_axes([0.4, 0.1, 0.2, 0.02]), orientation='horizontal') cb.set_label('Accumulation [mm/h]') titlestr = (yyyymmddhh_strtotime(date).strftime( get_config(inargs, 'plotting', 'date_fmt')) + ' ' + str(t.seconds / 3600).zfill(2) + 'UTC') fig.suptitle(titlestr) plt.tight_layout(rect=[0, 0.1, 1, 0.93]) # Save figure and log save_fig_and_log(fig, None, inargs, 'prec_stamps', date=date, time=str(t.seconds / 3600).zfill(2)) def plotting(inargs): """ Top-level function called by main.py Parameters ---------- inargs : argparse object Argparse object with all input arguments Returns ------- """ # Call appropriate plotting function if inargs.plot == 'weather_ts': plot_domain_mean_timeseries_individual(inargs, plot_type='precipitation') plot_domain_mean_timeseries_composite(inargs, plot_type='precipitation') plot_domain_mean_timeseries_individual(inargs, plot_type='cape_tauc') plot_domain_mean_timeseries_composite(inargs, plot_type='cape_tauc') if inargs.plot == 'prec_stamps': plot_prec_stamps(inargs)
[ "cosmo_utils.helpers.ddhhmmss", "helpers.make_datelist", "numpy.amin", "numpy.ravel", "matplotlib.pyplot.subplots", "datetime.datetime", "numpy.amax", "helpers.get_config", "cosmo_utils.pyncdf.getfobj_ncdf_ens", "numpy.mean", "datetime.timedelta", "helpers.get_and_crop_radar_fobj", "matplotl...
[((1120, 1147), 'helpers.read_netcdf_dataset', 'read_netcdf_dataset', (['inargs'], {}), '(inargs)\n', (1139, 1147), False, 'from helpers import read_netcdf_dataset, get_config, save_fig_and_log, make_datelist, get_and_crop_radar_fobj\n'), ((1299, 1384), 'matplotlib.pyplot.subplots', 'plt.subplots', (['n_rows', 'n_cols'], {'sharex': '(True)', 'sharey': '(True)', 'figsize': '(10, 3 * n_rows)'}), '(n_rows, n_cols, sharex=True, sharey=True, figsize=(10, 3 * n_rows)\n )\n', (1311, 1384), True, 'import matplotlib.pyplot as plt\n'), ((1423, 1438), 'numpy.ravel', 'np.ravel', (['axmat'], {}), '(axmat)\n', (1431, 1438), True, 'import numpy as np\n'), ((2122, 2140), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (2138, 2140), True, 'import matplotlib.pyplot as plt\n'), ((2164, 2234), 'helpers.save_fig_and_log', 'save_fig_and_log', (['fig', 'rootgroup', 'inargs', "(plot_type + '_ts_individual')"], {}), "(fig, rootgroup, inargs, plot_type + '_ts_individual')\n", (2180, 2234), False, 'from helpers import read_netcdf_dataset, get_config, save_fig_and_log, make_datelist, get_and_crop_radar_fobj\n'), ((6520, 6547), 'helpers.read_netcdf_dataset', 'read_netcdf_dataset', (['inargs'], {}), '(inargs)\n', (6539, 6547), False, 'from helpers import read_netcdf_dataset, get_config, save_fig_and_log, make_datelist, get_and_crop_radar_fobj\n'), ((6603, 6637), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': '(3, 3)'}), '(1, 1, figsize=(3, 3))\n', (6615, 6637), True, 'import matplotlib.pyplot as plt\n'), ((8198, 8216), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (8214, 8216), True, 'import matplotlib.pyplot as plt\n'), ((8248, 8317), 'helpers.save_fig_and_log', 'save_fig_and_log', (['fig', 'rootgroup', 'inargs', "(plot_type + '_ts_composite')"], {}), "(fig, rootgroup, inargs, plot_type + '_ts_composite')\n", (8264, 8317), False, 'from helpers import read_netcdf_dataset, get_config, save_fig_and_log, make_datelist, get_and_crop_radar_fobj\n'), ((2725, 2742), 'datetime.datetime', 'datetime', (['(1)', '(1)', '(1)'], {}), '(1, 1, 1)\n', (2733, 2742), False, 'from datetime import datetime, timedelta\n'), ((2775, 2817), 'helpers.get_config', 'get_config', (['inargs', '"""plotting"""', '"""date_fmt"""'], {}), "(inargs, 'plotting', 'date_fmt')\n", (2785, 2817), False, 'from helpers import read_netcdf_dataset, get_config, save_fig_and_log, make_datelist, get_and_crop_radar_fobj\n'), ((4564, 4581), 'datetime.datetime', 'datetime', (['(1)', '(1)', '(1)'], {}), '(1, 1, 1)\n', (4572, 4581), False, 'from datetime import datetime, timedelta\n'), ((4614, 4656), 'helpers.get_config', 'get_config', (['inargs', '"""plotting"""', '"""date_fmt"""'], {}), "(inargs, 'plotting', 'date_fmt')\n", (4624, 4656), False, 'from helpers import read_netcdf_dataset, get_config, save_fig_and_log, make_datelist, get_and_crop_radar_fobj\n'), ((7670, 7687), 'datetime.datetime', 'datetime', (['(1)', '(1)', '(1)'], {}), '(1, 1, 1)\n', (7678, 7687), False, 'from datetime import datetime, timedelta\n'), ((7730, 7772), 'helpers.get_config', 'get_config', (['inargs', '"""plotting"""', '"""date_fmt"""'], {}), "(inargs, 'plotting', 'date_fmt')\n", (7740, 7772), False, 'from helpers import read_netcdf_dataset, get_config, save_fig_and_log, make_datelist, get_and_crop_radar_fobj\n'), ((7924, 7941), 'datetime.datetime', 'datetime', (['(1)', '(1)', '(1)'], {}), '(1, 1, 1)\n', (7932, 7941), False, 'from datetime import datetime, timedelta\n'), ((7982, 8024), 'helpers.get_config', 'get_config', (['inargs', '"""plotting"""', '"""date_fmt"""'], {}), "(inargs, 'plotting', 'date_fmt')\n", (7992, 8024), False, 'from helpers import read_netcdf_dataset, get_config, save_fig_and_log, make_datelist, get_and_crop_radar_fobj\n'), ((8892, 8913), 'helpers.make_datelist', 'make_datelist', (['inargs'], {}), '(inargs)\n', (8905, 8913), False, 'from helpers import read_netcdf_dataset, get_config, save_fig_and_log, make_datelist, get_and_crop_radar_fobj\n'), ((11659, 11699), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {'rect': '[0, 0.1, 1, 0.93]'}), '(rect=[0, 0.1, 1, 0.93])\n', (11675, 11699), True, 'import matplotlib.pyplot as plt\n'), ((1597, 1614), 'datetime.datetime', 'datetime', (['(1)', '(1)', '(1)'], {}), '(1, 1, 1)\n', (1605, 1614), False, 'from datetime import datetime, timedelta\n'), ((1651, 1693), 'helpers.get_config', 'get_config', (['inargs', '"""plotting"""', '"""date_fmt"""'], {}), "(inargs, 'plotting', 'date_fmt')\n", (1661, 1693), False, 'from helpers import read_netcdf_dataset, get_config, save_fig_and_log, make_datelist, get_and_crop_radar_fobj\n'), ((3165, 3192), 'numpy.mean', 'np.mean', (['prec_array'], {'axis': '(1)'}), '(prec_array, axis=1)\n', (3172, 3192), True, 'import numpy as np\n'), ((3218, 3245), 'numpy.amin', 'np.amin', (['prec_array'], {'axis': '(1)'}), '(prec_array, axis=1)\n', (3225, 3245), True, 'import numpy as np\n'), ((3271, 3298), 'numpy.amax', 'np.amax', (['prec_array'], {'axis': '(1)'}), '(prec_array, axis=1)\n', (3278, 3298), True, 'import numpy as np\n'), ((6851, 6878), 'numpy.mean', 'np.mean', (['array'], {'axis': '(0, 2)'}), '(array, axis=(0, 2))\n', (6858, 6878), True, 'import numpy as np\n'), ((8974, 9008), 'datetime.timedelta', 'timedelta', ([], {'hours': 'inargs.time_start'}), '(hours=inargs.time_start)\n', (8983, 9008), False, 'from datetime import datetime, timedelta\n'), ((9041, 9073), 'datetime.timedelta', 'timedelta', ([], {'hours': 'inargs.time_end'}), '(hours=inargs.time_end)\n', (9050, 9073), False, 'from datetime import datetime, timedelta\n'), ((9106, 9124), 'datetime.timedelta', 'timedelta', ([], {'hours': '(1)'}), '(hours=1)\n', (9115, 9124), False, 'from datetime import datetime, timedelta\n'), ((10444, 10500), 'matplotlib.pyplot.subplots', 'plt.subplots', (['n_rows', 'n_cols'], {'figsize': '(10, 3.5 * n_rows)'}), '(n_rows, n_cols, figsize=(10, 3.5 * n_rows))\n', (10456, 10500), True, 'import matplotlib.pyplot as plt\n'), ((10560, 10575), 'numpy.ravel', 'np.ravel', (['axmat'], {}), '(axmat)\n', (10568, 10575), True, 'import numpy as np\n'), ((3537, 3572), 'helpers.get_config', 'get_config', (['inargs', '"""colors"""', 'group'], {}), "(inargs, 'colors', group)\n", (3547, 3572), False, 'from helpers import read_netcdf_dataset, get_config, save_fig_and_log, make_datelist, get_and_crop_radar_fobj\n'), ((5311, 5333), 'numpy.mean', 'np.mean', (['array'], {'axis': '(1)'}), '(array, axis=1)\n', (5318, 5333), True, 'import numpy as np\n'), ((5358, 5380), 'numpy.amin', 'np.amin', (['array'], {'axis': '(1)'}), '(array, axis=1)\n', (5365, 5380), True, 'import numpy as np\n'), ((5405, 5427), 'numpy.amax', 'np.amax', (['array'], {'axis': '(1)'}), '(array, axis=1)\n', (5412, 5427), True, 'import numpy as np\n'), ((7393, 7420), 'numpy.mean', 'np.mean', (['array'], {'axis': '(0, 2)'}), '(array, axis=(0, 2))\n', (7400, 7420), True, 'import numpy as np\n'), ((9269, 9309), 'helpers.get_and_crop_radar_fobj', 'get_and_crop_radar_fobj', (['inargs', 'date', 't'], {}), '(inargs, date, t)\n', (9292, 9309), False, 'from helpers import read_netcdf_dataset, get_config, save_fig_and_log, make_datelist, get_and_crop_radar_fobj\n'), ((9998, 10110), 'cosmo_utils.pyncdf.getfobj_ncdf_ens', 'getfobj_ncdf_ens', (['date_dir', '"""sub"""', 'inargs.nens', 'ncdffn'], {'dir_suffix': '"""/OUTPUT/"""', 'fieldn': '"""PREC_ACCUM"""', 'nfill': '(1)'}), "(date_dir, 'sub', inargs.nens, ncdffn, dir_suffix=\n '/OUTPUT/', fieldn='PREC_ACCUM', nfill=1)\n", (10014, 10110), False, 'from cosmo_utils.pyncdf import getfobj_ncdf, getfobj_ncdf_ens\n'), ((10636, 10654), 'matplotlib.pyplot.sca', 'plt.sca', (['axflat[i]'], {}), '(axflat[i])\n', (10643, 10654), True, 'import matplotlib.pyplot as plt\n'), ((10681, 10949), 'cosmo_utils.plot.ax_contourf', 'ax_contourf', (['axflat[i]', 'fobjlist[i]'], {'colors': 'cmPrec', 'pllevels': 'levelsPrec', 'ji0': '(50 + inargs.zoom_lat1, 50 + inargs.zoom_lon1)', 'ji1': '(357 - 51 + inargs.zoom_lat2, 357 - 51 + inargs.zoom_lon2)', 'sp_title': 'titlelist[i]', 'Basemap_drawrivers': '(False)', 'npars': '(0)', 'nmers': '(0)'}), '(axflat[i], fobjlist[i], colors=cmPrec, pllevels=levelsPrec, ji0\n =(50 + inargs.zoom_lat1, 50 + inargs.zoom_lon1), ji1=(357 - 51 + inargs\n .zoom_lat2, 357 - 51 + inargs.zoom_lon2), sp_title=titlelist[i],\n Basemap_drawrivers=False, npars=0, nmers=0)\n', (10692, 10949), False, 'from cosmo_utils.plot import ax_contourf\n'), ((3851, 3892), 'helpers.get_config', 'get_config', (['inargs', '"""colors"""', '"""ens_range"""'], {}), "(inargs, 'colors', 'ens_range')\n", (3861, 3892), False, 'from helpers import read_netcdf_dataset, get_config, save_fig_and_log, make_datelist, get_and_crop_radar_fobj\n'), ((5638, 5673), 'helpers.get_config', 'get_config', (['inargs', '"""colors"""', 'group'], {}), "(inargs, 'colors', group)\n", (5648, 5673), False, 'from helpers import read_netcdf_dataset, get_config, save_fig_and_log, make_datelist, get_and_crop_radar_fobj\n'), ((6943, 6978), 'helpers.get_config', 'get_config', (['inargs', '"""colors"""', 'group'], {}), "(inargs, 'colors', group)\n", (6953, 6978), False, 'from helpers import read_netcdf_dataset, get_config, save_fig_and_log, make_datelist, get_and_crop_radar_fobj\n'), ((9822, 9833), 'cosmo_utils.helpers.ddhhmmss', 'ddhhmmss', (['t'], {}), '(t)\n', (9830, 9833), False, 'from cosmo_utils.helpers import yymmddhhmm, ddhhmmss, yyyymmddhh_strtotime, make_timelist\n'), ((9875, 9914), 'helpers.get_config', 'get_config', (['inargs', '"""paths"""', '"""raw_data"""'], {}), "(inargs, 'paths', 'raw_data')\n", (9885, 9914), False, 'from helpers import read_netcdf_dataset, get_config, save_fig_and_log, make_datelist, get_and_crop_radar_fobj\n'), ((5919, 5960), 'helpers.get_config', 'get_config', (['inargs', '"""colors"""', '"""ens_range"""'], {}), "(inargs, 'colors', 'ens_range')\n", (5929, 5960), False, 'from helpers import read_netcdf_dataset, get_config, save_fig_and_log, make_datelist, get_and_crop_radar_fobj\n'), ((7493, 7528), 'helpers.get_config', 'get_config', (['inargs', '"""colors"""', 'group'], {}), "(inargs, 'colors', group)\n", (7503, 7528), False, 'from helpers import read_netcdf_dataset, get_config, save_fig_and_log, make_datelist, get_and_crop_radar_fobj\n'), ((11508, 11550), 'helpers.get_config', 'get_config', (['inargs', '"""plotting"""', '"""date_fmt"""'], {}), "(inargs, 'plotting', 'date_fmt')\n", (11518, 11550), False, 'from helpers import read_netcdf_dataset, get_config, save_fig_and_log, make_datelist, get_and_crop_radar_fobj\n'), ((9400, 9439), 'helpers.get_config', 'get_config', (['inargs', '"""paths"""', '"""raw_data"""'], {}), "(inargs, 'paths', 'raw_data')\n", (9410, 9439), False, 'from helpers import read_netcdf_dataset, get_config, save_fig_and_log, make_datelist, get_and_crop_radar_fobj\n'), ((9605, 9616), 'cosmo_utils.helpers.ddhhmmss', 'ddhhmmss', (['t'], {}), '(t)\n', (9613, 9616), False, 'from cosmo_utils.helpers import yymmddhhmm, ddhhmmss, yyyymmddhh_strtotime, make_timelist\n'), ((11445, 11471), 'cosmo_utils.helpers.yyyymmddhh_strtotime', 'yyyymmddhh_strtotime', (['date'], {}), '(date)\n', (11465, 11471), False, 'from cosmo_utils.helpers import yymmddhhmm, ddhhmmss, yyyymmddhh_strtotime, make_timelist\n')]
''' Utilities for scoring the performance of models on datasets. ''' from random import shuffle import numpy as np from classer.utils.status import set_status def score_model(model, data, status_file, test_split=0.1, min_samples=10, iterations=3): '''Calculate a score for a model and a specific dataset Runs a configurable amount of test iterations and averages all results ''' all_iterations = [] for iteration in range(0, iterations): status_message = 'Processing Scoring Iteration {num}'.format( num=iteration+1) set_status(status_file, status_message) shuffle(data) # Early exit for not enough samples if len(data) < min_samples: raise ValueError('A minimum number of {num} samples are ' 'required to score a model'.format(num=min_samples)) test_split_index = int(len(data) * test_split) train_data = data[test_split_index:] test_data = data[:test_split_index] # Train Model #TODO - make sure this doesn't carry over from previous iterations model.train(train_data) # Score iteration_stats, label_map = get_confusion(model, test_data) all_iterations.append(iteration_stats) overall_stats = {} list_stats = {} for single_iteration in all_iterations: for it_stat, it_confusion in single_iteration.items(): if it_stat not in overall_stats.keys(): overall_stats[it_stat] = it_confusion else: overall_stats[it_stat] = overall_stats[it_stat] + it_confusion full_stats = calculate_full_stats(overall_stats, label_map) for stat_name, stat_data in full_stats.items(): if type(stat_data) not in [list, dict, str]: list_stats[stat_name] = stat_data.tolist() else: list_stats[stat_name] = stat_data list_stats['label_map'] = label_map return list_stats def get_confusion(model, test_data, threshold=0.7): ''' Calculate scores for the predictions generated by a trained model on a test set ''' test_samples = [example['text'] for example in test_data] test_labels = [example['label'] for example in test_data] predictions = model.predict(test_samples) # labels ~ {"neg": 0, "pos": 1} label_map = model.label_mapper.label_map['forward'] num_labels = len(label_map.keys()) unknown_col = num_labels # for threshold confusion matrix # A confusion matrix is created, where the value at X, Y # indicates the strength of a prediction with true label X and # predicted label Y confusion = np.zeros((num_labels, num_labels)) max_confusion = np.zeros((num_labels, num_labels)) # Add an extra column in the threshold confusion matrix for # predictions that don't meet either threshold threshold_confusion = np.zeros((num_labels, num_labels+1)) for prediction_idx, prediction in enumerate(predictions): correct_label = test_labels[prediction_idx] correct_label_index = label_map.get(correct_label) max_prediction = None max_prediction_score = 0.0 for predicted_label in prediction.keys(): predicted_label_index = label_map.get(predicted_label) # Populate confusion matrix confusion[correct_label_index, predicted_label_index] = \ confusion[correct_label_index, predicted_label_index] + \ prediction.get(predicted_label) prediction_score = prediction.get(predicted_label) if prediction_score > max_prediction_score: max_prediction = predicted_label max_prediction_score = prediction_score # Populate max confusion matrix max_prediction_index = label_map.get(max_prediction) max_confusion[correct_label_index, max_prediction_index] = \ max_confusion[correct_label_index, max_prediction_index] + 1 # Populate threshold confusion matrix if max_prediction_score >= threshold: threshold_confusion[correct_label_index, max_prediction_index] = \ threshold_confusion[correct_label_index, max_prediction_index] + 1 else: threshold_confusion[correct_label_index, unknown_col] = \ threshold_confusion[correct_label_index, unknown_col] + 1 stats = { "confusion": confusion, "max_confusion": max_confusion, "threshold_confusion": threshold_confusion } return stats, label_map def calculate_full_stats(confusion_stats, label_map): """ Calculate Full precision + Recall stats given the total, max, and threshold confusion matrices """ inverse_label_map = {} for label_name, label_index in label_map.items(): inverse_label_map[label_index] = label_name total_confusion = confusion_stats['confusion'] total_precision, total_recall, total_f = get_precision_recall_f( total_confusion, inverse_label_map) confusion_stats['total_precision'] = total_precision confusion_stats['total_recall'] = total_recall confusion_stats['total_f'] = total_f max_confusion = confusion_stats['max_confusion'] max_precision, max_recall, max_f = get_precision_recall_f( max_confusion, inverse_label_map) confusion_stats['max_precision'] = max_precision confusion_stats['max_recall'] = max_recall confusion_stats['max_f'] = max_f threshold_confusion = confusion_stats['threshold_confusion'] threshold_precision, threshold_recall, threshold_f = get_precision_recall_f( threshold_confusion, inverse_label_map) confusion_stats['threshold_precision'] = threshold_precision confusion_stats['threshold_recall'] = threshold_recall confusion_stats['threshold_f'] = threshold_f return confusion_stats def get_precision_recall_f(confusion, inverse_label_map): """ Calculate precision, recall, and F-score stats for a single confusion matrix """ precision, recall, f_score = {}, {}, {} for label_index in range(len(inverse_label_map.keys())): label_name = inverse_label_map.get(label_index) true_count = confusion[label_index, label_index] all_predicted = confusion[:,label_index].sum() all_truth = confusion[label_index].sum() label_precision = true_count / all_predicted label_recall = true_count / all_truth precision[label_name] = label_precision recall[label_name] = label_recall f_score[label_name] = (2 * label_precision * label_recall) / \ (label_precision + label_recall) return precision, recall, f_score
[ "random.shuffle", "classer.utils.status.set_status", "numpy.zeros" ]
[((2696, 2730), 'numpy.zeros', 'np.zeros', (['(num_labels, num_labels)'], {}), '((num_labels, num_labels))\n', (2704, 2730), True, 'import numpy as np\n'), ((2751, 2785), 'numpy.zeros', 'np.zeros', (['(num_labels, num_labels)'], {}), '((num_labels, num_labels))\n', (2759, 2785), True, 'import numpy as np\n'), ((2927, 2965), 'numpy.zeros', 'np.zeros', (['(num_labels, num_labels + 1)'], {}), '((num_labels, num_labels + 1))\n', (2935, 2965), True, 'import numpy as np\n'), ((593, 632), 'classer.utils.status.set_status', 'set_status', (['status_file', 'status_message'], {}), '(status_file, status_message)\n', (603, 632), False, 'from classer.utils.status import set_status\n'), ((641, 654), 'random.shuffle', 'shuffle', (['data'], {}), '(data)\n', (648, 654), False, 'from random import shuffle\n')]
import sys import random import operator import numpy as np from functools import reduce from itertools import product from gensim.models import KeyedVectors from sklearn.decomposition import PCA from sklearn.cluster import KMeans def select(k, n): value = list(range(k)) rest = dict() for i in range(k): j = random.randrange(i, n) if j < k: # Both elements to be swapped are in the selection value[i], value[j] = value[j], value[i] elif j in rest: # Element j has been swapped before value[i], rest[j] = rest[j], value[i] else: # The value at j is still j, we now add it to the virtual array rest[j] = value[i] value[i] = j return value cluster_size = 0 try: cluster_size = int(sys.argv[2]) except: pass segments = [a.split(',') for a in sys.argv[(2 if cluster_size == 0 else 3):]] dims = [len(a) for a in segments] D = len(dims) K = reduce(lambda a,b: a*b, dims) d_order = np.lexsort((dims,)) model_file = sys.argv[1] wv = KeyedVectors.load_word2vec_format(model_file, binary=(model_file.endswith('.bin'))) sample_count = K*50 vector_count = len(wv.vectors) if sample_count > vector_count: sample_count = vector_count print("Used", sample_count, "of", vector_count, "vectors for clustering") samples = [wv.vectors[i,:] for i in select(sample_count, vector_count)] km = KMeans(n_clusters=K) if cluster_size == 0: labels2words = [list() for _ in range(K)] labels = km.fit_predict(wv.vectors) centers = km.cluster_centers_ for i, l in enumerate(labels): w = wv.index_to_key[i] if w is not None: labels2words[l].append(w) else: labels2words = [] km.fit(wv.vectors) centers = km.cluster_centers_ for center in centers: cluster = [r[0] for r in wv.most_similar(positive=[center], topn=(cluster_size+1)) if r[0] is not None] if len(cluster) > cluster_size: cluster.pop() labels2words.append(cluster) pca = PCA(n_components=D) result = pca.fit_transform(centers) r_order = np.lexsort((result[:,d_order]).T) print("Forms:", K) for i, emes in enumerate(product(*segments)): center = centers[r_order[i],:] cluster = labels2words[r_order[i]] if cluster_size == 0: distances = wv.distances(center, cluster) cluster = [k for k, _ in sorted(zip(cluster, distances), key=operator.itemgetter(1))] word = cluster[0] print( "".join(emes), ':', repr(word.encode("utf-8", errors='replace'))[2:-1], len(cluster) ) for w in cluster[1:]: print('\t', repr(w.encode("utf-8", errors='replace'))[2:-1]) print('==========')
[ "numpy.lexsort", "sklearn.cluster.KMeans", "sklearn.decomposition.PCA", "random.randrange", "itertools.product", "functools.reduce", "operator.itemgetter" ]
[((978, 1010), 'functools.reduce', 'reduce', (['(lambda a, b: a * b)', 'dims'], {}), '(lambda a, b: a * b, dims)\n', (984, 1010), False, 'from functools import reduce\n'), ((1019, 1038), 'numpy.lexsort', 'np.lexsort', (['(dims,)'], {}), '((dims,))\n', (1029, 1038), True, 'import numpy as np\n'), ((1423, 1443), 'sklearn.cluster.KMeans', 'KMeans', ([], {'n_clusters': 'K'}), '(n_clusters=K)\n', (1429, 1443), False, 'from sklearn.cluster import KMeans\n'), ((2039, 2058), 'sklearn.decomposition.PCA', 'PCA', ([], {'n_components': 'D'}), '(n_components=D)\n', (2042, 2058), False, 'from sklearn.decomposition import PCA\n'), ((2105, 2137), 'numpy.lexsort', 'np.lexsort', (['result[:, d_order].T'], {}), '(result[:, d_order].T)\n', (2115, 2137), True, 'import numpy as np\n'), ((2185, 2203), 'itertools.product', 'product', (['*segments'], {}), '(*segments)\n', (2192, 2203), False, 'from itertools import product\n'), ((330, 352), 'random.randrange', 'random.randrange', (['i', 'n'], {}), '(i, n)\n', (346, 352), False, 'import random\n'), ((2425, 2447), 'operator.itemgetter', 'operator.itemgetter', (['(1)'], {}), '(1)\n', (2444, 2447), False, 'import operator\n')]
from abc import abstractmethod from .utils import get_params from .structured_utils import * from .mixin import ActivationMixin from collections import OrderedDict, defaultdict import torch import torch.nn as nn import numpy as np import pandas as pd import itertools import time class StructuredPruning(ActivationMixin): # Base class for structured pruning # if structure = neuron prunes output neurons of linear layers followed by another linear layer # if structure = channel prunes output channels of conv layers followed by another conv layer # if structure = None prunes both linear and conv layers # we use channel to refer to both neurons and conv channels # Computes pruned channels corresponding to all fractions in initialization by default # calling apply(fraction) constructs masks and applies pruning for corresponding fraction # if reweight=True, we update next layer weights with weights that minimize change of input to next layer # if bias=True, we treat the bias as another channel (with no input weights) that can be pruned def __init__(self, model, inputs=None, outputs=None, fractions=1, reweight=False, bias=False, structure='neuron', prune_layers=None, **pruning_params): inputs = torch.cat(inputs, axis=0) outputs = torch.cat(outputs, axis=0) self.device = torch.device('cpu') # 'cuda' if torch.cuda.is_available() else 'cpu' super().__init__(model, inputs, outputs, fractions=fractions, reweight=reweight, bias=bias, structure=structure, prune_layers=prune_layers, **pruning_params) self.prunable, self.channel_prunable, self.next_module_map, self.bn_map = prunable_modules(self.model, structure, prune_layers) # if isinstance(self, LayerStructuredPruning): # if len(self.channel_prunable) > 1 and self.onelayer_results_df is not None: # t = time.perf_counter() # self.perlayer_fractions = self.select_perlayer_fractions() # print("perlayer fractions selection time:", time.perf_counter() - t, "secs.") # else: # self.perlayer_fractions = {fraction: {name: fraction for name in self.channel_prunable} for fraction # in self.fractions} self.preprocessing() if fractions == [1]: # prune nothing self.pruned_channels = {1: {name: [] for name in self.channel_prunable}} self.pruned_bias = {1: {name: False for name in self.channel_prunable}} self.new_params = {1: {name: None for name in self.channel_prunable}} else: self.pruned_channels, self.pruned_bias, self.new_params = self.model_pruned_channels() if self.pruned_bias is None: self.pruned_bias = {fraction: {name: False for name in self.channel_prunable} for fraction in fractions} def preprocessing(self): # do any preprocessing steps needed before calling model_pruned_channels() # skipped if fractions==[1] pass def can_prune(self, module_name): # true for any module where output channels can be pruned return module_name in self.channel_prunable def apply(self, fraction): assert fraction in self.fractions, "fraction should be one of the input fractions" if fraction != 1: self.reweight_params(fraction) masks = self.model_masks(fraction) def get_module(self, module_name, next=False): if next: name = self.next_module_map[module_name] else: name = module_name return get_module(self.model, name) def module_params(self, module_name, next=False): return get_params(self.get_module(module_name, next=next)) def params(self, only_prunable=True, next=False): if only_prunable: return {name: self.module_params(name, next) for name in self.channel_prunable} else: return {name: get_params(module) for name, module in self.model.named_modules()} def module_n_channels(self, module_name, bias=False): params = self.module_params(module_name) return params['weight'].shape[0] + (1 if bias and "bias" in params else 0) def n_channels(self, only_prunable=True, bias=False): if only_prunable: return sum([self.module_n_channels(name, bias) for name in self.channel_prunable]) else: return sum([self.module_n_channels(name, bias) for name, _ in self.model.named_modules()]) def channels_ind(self): return {name: set(range(self.module_n_channels(name, bias=self.bias))) for name in self.channel_prunable} @abstractmethod def model_pruned_channels(self): # returns a dictionary of pruned channels for each fraction, module_name # {fraction: {module_name: list of pruned channels in this module}} # and optionally a dictionary listing if bias was pruned or not for each fraction, otherwise return none # {fraction: True if bias is pruned, False otherwise} # and optionally a dictionary of new params values, otherwise return none # {fraction: {module_name: {param_name: new param of next module (numpy.ndarray)}}} pass def layer_masks(self, module_name, fraction, masks=None, scale=1, perm=False): if masks is None: masks = defaultdict(OrderedDict) module = self.get_module(module_name) pruned_channels = self.pruned_channels[fraction][module_name] bn_name = self.bn_map[module_name] for mod in [module] + ([self.get_module(bn_name)] if bn_name is not None else []): for name in get_params(mod).keys(): # ['weight', 'bias']: indices_structured(mod, name, 0, pruned_channels) if perm: # Multiply params by (non-scaled) masks so metrics can count nonzeros getattr(mod, name + '_orig').data.mul_(getattr(mod, name + '_mask') != 0) masks[mod][name] = getattr(mod, name + '_mask') next_module = self.get_module(module_name, next=True) # scale only next layer weights indices_structured(next_module, 'weight', 1, pruned_channels, scale) if perm: # Multiply params by (non-scaled) masks so metrics can count nonzeros next_module.weight_orig.data.mul_(next_module.weight_mask != 0) masks[next_module]['weight'] = getattr(next_module, 'weight_mask') if self.pruned_bias[fraction][module_name] and next_module.bias is not None: indices_structured(next_module, 'bias', 0, list(range(0, next_module.bias.shape[0]))) if perm: next_module.bias_orig.data.mul_(next_module.bias_mask != 0) masks[next_module]['bias'] = getattr(next_module, 'bias_mask') return masks def undo_layer_masks(self, module_name, weight_mask): undo_pruning(self.get_module(module_name), weight_mask) bn_name = self.bn_map[module_name] if bn_name is not None: undo_pruning(self.get_module(bn_name)) undo_pruning(self.get_module(module_name, next=True)) def model_masks(self, fraction): masks = defaultdict(OrderedDict) for module_name in self.channel_prunable: self.layer_masks(module_name, fraction, masks, scale=self.scale if (hasattr(self, 'scale') and not self.reweight) else 1, perm=True) return masks def reweight_layer_params(self, module_name, fraction): next_module = self.get_module(module_name, next=True) new_params = self.new_params[fraction][module_name] if new_params == {} and self.reweight: # update next layer weights with weights that minimize change of its input resulting from pruning output # channels of current layer params = get_params(next_module) acts = self.module_activations(next_module, only_input=True, update=True) if isinstance(next_module, nn.Conv2d): acts = torch.nn.functional.unfold(torch.from_numpy(acts), next_module.kernel_size, next_module.dilation, next_module.padding, next_module.stride).transpose(1, 2).numpy() acts = acts.reshape(-1, acts.shape[-1]) kept_channels = list(set(range(self.module_n_channels(module_name))) - set(self.pruned_channels[fraction][module_name])) # if module is linear, kernel_size = 1, if it's conv followed by conv, kernel_size = H x W kernel_size = next_module.kernel_size if isinstance(next_module, nn.Conv2d) else \ int(acts.shape[-1]/self.module_n_channels(module_name)) map = lambda channels: map_chton(channels, kernel_size) neg_input_change = NegInputChange(acts, params, rwchange=True, bias=self.bias, map=map) new_params = neg_input_change.get_new_params(kept_channels, cur=False) self.new_params[fraction][module_name] = new_params for pname, new_param in new_params.items(): with torch.no_grad(): # applied before pruning, so we're modifying weight/bias not weight_orig/bias_orig getattr(next_module, pname).data = torch.from_numpy(new_param).to(self.device) def reweight_params(self, fraction): if self.new_params is None: self.new_params = {fraction: {name: {} for name in self.channel_prunable} for fraction in self.fractions} for name in self.channel_prunable: self.reweight_layer_params(name, fraction) def summary(self, fraction): total_n_channels_kept = 0 rows = [] for name, module in self.model.named_modules(): for pname, param in get_params(module).items(): if hasattr(module, pname+'_mask'): # isinstance(module, MaskedModule): compression = 1/(getattr(module, pname+'_mask').detach().cpu().numpy() != 0).mean() else: compression = 1 shape = param.shape if name in self.channel_prunable: if pname == 'weight': pruned_channels = self.pruned_channels[fraction][name] pruned_fraction = len(pruned_channels)/shape[0] n_channels = self.module_n_channels(name, bias=self.bias) if isinstance(self, LayerStructuredPruning): k = int(self.perlayer_fractions[fraction][name] * n_channels) assert n_channels - len(pruned_channels) - self.pruned_bias[fraction][name] == k, \ f"# of kept channels in {name} should be {k}" total_n_channels_kept += n_channels - len(pruned_channels) - self.pruned_bias[fraction][name] else: pruned_channels = [0] if self.pruned_bias[fraction][name] else [] pruned_fraction = len(pruned_channels) else: pruned_channels = [] pruned_fraction = 0 rows.append([name, pname, compression, np.prod(shape), shape, self.can_prune(name), pruned_fraction, pruned_channels]) if not isinstance(self, LayerStructuredPruning): k = int(fraction * self.n_channels(bias=self.bias)) assert total_n_channels_kept == k, f"# of total kept channels should be {k}, {total_n_channels_kept} " \ f"channels were kept" columns = ['module', 'param', 'comp', 'size', 'shape', 'channel prunable', 'pruned_fraction', 'pruned_channels'] return pd.DataFrame(rows, columns=columns) class LayerStructuredPruning(StructuredPruning): # prunes output channels of each prunable layer independently if sequential=False or sequentially starting from # first layer to last one. Uses perlayer fraction selection method from Kuzmin, Andrey, et al. if # onelayer_results_df is not none, otherwise uses equal fraction for all layers. def __init__(self, model, inputs=None, outputs=None, fractions=1, reweight=False, bias=False, structure='neuron', prune_layers=None, sequential=False, onelayer_results_df=None, select='min', **pruning_params): self.onelayer_results_df, self.select = onelayer_results_df, select self.perlayer_fractions = {} super().__init__(model, inputs=inputs, outputs=outputs, fractions=fractions, reweight=reweight, bias=bias, structure=structure, prune_layers=prune_layers, sequential=sequential, **pruning_params) def preprocessing(self): if self.fractions != [1] and len(self.channel_prunable) > 1 and self.onelayer_results_df is not None: t = time.perf_counter() self.perlayer_fractions = self.select_perlayer_fractions() print("perlayer fractions selection time:", time.perf_counter() - t, "secs.") else: self.perlayer_fractions = {fraction: {name: fraction for name in self.channel_prunable} for fraction in self.fractions} # TODO: save selected perlayer budgets instead of fractions, since all methods use that # TODO: add option to prune each layer until reaching an error threshold def select_perlayer_fractions(self, bs=True, eps=1e-5): # implements equal accuracy loss method proposed in Kuzmin, Andrey, et al. "Taxonomy and evaluation of # structured compression of convolutional neural networks." arXiv preprint arXiv:1912.09802 (2019). # but here we select n_channels instead of ranks self.onelayer_results_df.loc[:, 'fraction'] = self.onelayer_results_df.fraction.round(3) # to avoid numerical issues fraction_choices = np.sort(self.onelayer_results_df['fraction'].unique()) perlayer_acc = defaultdict(np.array) if bs else defaultdict(OrderedDict) perlayer_nchannels = [self.module_n_channels(name, self.bias) for name in self.channel_prunable] nchannels = sum(perlayer_nchannels) selected_perlayer_fractions = defaultdict(OrderedDict) # get acc for all fraction choices for name in self.channel_prunable: if bs: perlayer_acc[name] = np.zeros(len(fraction_choices)) for idx, fraction in enumerate(fraction_choices): if bs: perlayer_acc[name][idx] = self.onelayer_results_df[(self.onelayer_results_df['prune_layers'] == name) & (self.onelayer_results_df['fraction'] == fraction)]['pre_acc1'].values[0] else: perlayer_acc[name][fraction] = self.onelayer_results_df[(self.onelayer_results_df['prune_layers'] == name) & (self.onelayer_results_df['fraction'] == fraction)]['pre_acc1'].values[0] L = len(self.channel_prunable) if bs: # binary search assert self.select == 'min', "select should be min if using binary search" assert 1 in fraction_choices, "1 should be among fraction choices" # because we use it for acc_max # acc at fraction 1 is not exactly the same due to numerical errors, we take min to guarantee acc_1 is satisfied by all layers acc_1 = self.onelayer_results_df[self.onelayer_results_df['fraction']==1]['pre_acc1'].min() # enforce monotonicity for name in self.channel_prunable: perlayer_acc[name] = monotone_envelope(fraction_choices, perlayer_acc[name]) for fraction in self.fractions: nchannels_tokeep = int(fraction * nchannels) min_budget = int(nchannels_tokeep >= L) min_fraction = list(min_budget / np.array(perlayer_nchannels)) # find perlayer fractions that lead to largest acc and satisfy nchannels_tokeep acc_min, acc_max = 0, acc_1 while acc_max - acc_min > eps: acc = (acc_min + acc_max)/2 # find smallest fraction satisfying this acc for each layer, acc is at least satisfied by fraction=1 perlayer_fractions = [] for i, name in enumerate(self.channel_prunable): idx = max(0, min(np.searchsorted(perlayer_acc[name], acc, side='left'), len(fraction_choices)-1)) # make sure we don't go out of bounds perlayer_fractions.append(max(fraction_choices[idx], min_fraction[i])) nchannels_kept = sum(np.array(np.multiply(perlayer_fractions, perlayer_nchannels), int)) # check if this combination of per layer fractions satisfy this overall fraction of channels to keep if nchannels_kept <= nchannels_tokeep: acc_min = acc else: acc_max = acc # check if budget is satisfied at convergence, if not rerun with acc=acc_min if nchannels_kept > nchannels_tokeep: perlayer_fractions = [] for i, name in enumerate(self.channel_prunable): idx = max(0, min(np.searchsorted(perlayer_acc[name], acc_min, side='left'), len(fraction_choices)-1)) # make sure we don't go out of bounds perlayer_fractions.append(max(fraction_choices[idx], min_fraction[i])) # use remaining quota if any by filling up layers gradually from one with largest fraction to smallest perlayer_fractions = np.array(perlayer_fractions) for idx in np.argsort(-perlayer_fractions): nchannels_kept = sum(np.array(np.multiply(perlayer_fractions, perlayer_nchannels), int)) if nchannels_kept < nchannels_tokeep: perlayer_fractions[idx] = np.minimum((int(perlayer_fractions[idx]*perlayer_nchannels[idx]) + (nchannels_tokeep - nchannels_kept))/perlayer_nchannels[idx], 1) else: break selected_perlayer_fractions[fraction] = OrderedDict(zip(self.channel_prunable, perlayer_fractions)) else: # exhaustive search max_acc = {fraction: ((), 0) for fraction in self.fractions} for perlayer_fractions in itertools.product(fraction_choices, repeat=L): # t = time.perf_counter() nchannels_kept = sum(np.array(np.multiply(perlayer_fractions, perlayer_nchannels), int)) if self.select == 'min': acc = min([perlayer_acc[name][perlayer_fractions[idx]] for idx, name in enumerate(self.channel_prunable)]) else: acc = sum([perlayer_acc[name][perlayer_fractions[idx]] for idx, name in enumerate(self.channel_prunable)]) for fraction in self.fractions: # check if this combination of per layer fractions satisfy this overall fraction of channels to keep if nchannels_kept <= int(fraction*nchannels) and acc >= max_acc[fraction][1]: max_acc[fraction] = (perlayer_fractions, acc) # print("one iter time:", time.perf_counter() - t, "secs.") for fraction in self.fractions: perlayer_fractions = np.array(max_acc[fraction][0]) nchannels_tokeep = int(fraction * nchannels) # use remaining quota by filling up layers gradually from one with largest fraction to smallest for idx in np.argsort(-perlayer_fractions): nchannels_kept = sum(np.array(np.multiply(perlayer_fractions, perlayer_nchannels), int)) if nchannels_kept < nchannels_tokeep: perlayer_fractions[idx] = np.minimum((int(perlayer_fractions[idx]*perlayer_nchannels[idx]) + (nchannels_tokeep - nchannels_kept))/perlayer_nchannels[idx], 1) else: break selected_perlayer_fractions[fraction] = OrderedDict(zip(self.channel_prunable, perlayer_fractions)) return selected_perlayer_fractions @abstractmethod def layer_pruned_channels(self, module_name, fractions): # returns a dictionary of pruned channels in corresponding module for each fraction in fractions # fractions should be a subset of self.fractions # {fraction: {list of pruned channels in this module}} # and optionally a dictionary listing if bias was pruned or not for each fraction, otherwise return none # {fraction: True if bias is pruned, False otherwise} # and optionally a dictionary of new params values, otherwise return none # {fraction: {param_name: new param of next module (numpy.ndarray)}} pass def layer_pruned_channels(self, module_name): return self.layer_pruned_channels(module_name, self.fractions) def model_pruned_channels(self): pruned_channels = defaultdict(OrderedDict) pruned_bias = defaultdict(OrderedDict) new_params = defaultdict(OrderedDict) if not self.sequential: for name in self.channel_prunable: lay_pruned_channels, lay_pruned_bias, lay_new_params = self.layer_pruned_channels(name, self.fractions) for fraction in self.fractions: pruned_channels[fraction][name] = lay_pruned_channels[fraction] pruned_bias[fraction][name] = lay_pruned_bias[fraction] if lay_pruned_bias is not None else False new_params[fraction][name] = lay_new_params[fraction] if lay_new_params is not None else {} return pruned_channels, pruned_bias, new_params def apply(self, fraction): if self.sequential: assert fraction in self.fractions, "fraction should be one of the input fractions" for name in self.channel_prunable: if fraction == 1: self.pruned_channels[fraction][name], self.pruned_bias[fraction][name], \ self.new_params[fraction][name] = [], False, None else: lay_pruned_channels, lay_pruned_bias, lay_new_params = self.layer_pruned_channels(name, [fraction]) self.pruned_channels[fraction][name] = lay_pruned_channels[fraction] self.pruned_bias[fraction][name] = lay_pruned_bias[fraction] if lay_pruned_bias is not None else False self.new_params[fraction][name] = lay_new_params[fraction] if lay_new_params is not None else {} self.reweight_layer_params(name, fraction) self.layer_masks(name, fraction, scale=self.scale if (hasattr(self, 'scale') and not self.reweight) else 1, perm=True) else: super().apply(fraction)
[ "pandas.DataFrame", "numpy.multiply", "time.perf_counter", "torch.cat", "numpy.searchsorted", "collections.defaultdict", "numpy.argsort", "numpy.array", "torch.device", "itertools.product", "torch.no_grad", "numpy.prod", "torch.from_numpy" ]
[((1273, 1298), 'torch.cat', 'torch.cat', (['inputs'], {'axis': '(0)'}), '(inputs, axis=0)\n', (1282, 1298), False, 'import torch\n'), ((1317, 1343), 'torch.cat', 'torch.cat', (['outputs'], {'axis': '(0)'}), '(outputs, axis=0)\n', (1326, 1343), False, 'import torch\n'), ((1366, 1385), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (1378, 1385), False, 'import torch\n'), ((7360, 7384), 'collections.defaultdict', 'defaultdict', (['OrderedDict'], {}), '(OrderedDict)\n', (7371, 7384), False, 'from collections import OrderedDict, defaultdict\n'), ((11889, 11924), 'pandas.DataFrame', 'pd.DataFrame', (['rows'], {'columns': 'columns'}), '(rows, columns=columns)\n', (11901, 11924), True, 'import pandas as pd\n'), ((14359, 14383), 'collections.defaultdict', 'defaultdict', (['OrderedDict'], {}), '(OrderedDict)\n', (14370, 14383), False, 'from collections import OrderedDict, defaultdict\n'), ((21485, 21509), 'collections.defaultdict', 'defaultdict', (['OrderedDict'], {}), '(OrderedDict)\n', (21496, 21509), False, 'from collections import OrderedDict, defaultdict\n'), ((21532, 21556), 'collections.defaultdict', 'defaultdict', (['OrderedDict'], {}), '(OrderedDict)\n', (21543, 21556), False, 'from collections import OrderedDict, defaultdict\n'), ((21578, 21602), 'collections.defaultdict', 'defaultdict', (['OrderedDict'], {}), '(OrderedDict)\n', (21589, 21602), False, 'from collections import OrderedDict, defaultdict\n'), ((5532, 5556), 'collections.defaultdict', 'defaultdict', (['OrderedDict'], {}), '(OrderedDict)\n', (5543, 5556), False, 'from collections import OrderedDict, defaultdict\n'), ((13010, 13029), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (13027, 13029), False, 'import time\n'), ((14114, 14135), 'collections.defaultdict', 'defaultdict', (['np.array'], {}), '(np.array)\n', (14125, 14135), False, 'from collections import OrderedDict, defaultdict\n'), ((14147, 14171), 'collections.defaultdict', 'defaultdict', (['OrderedDict'], {}), '(OrderedDict)\n', (14158, 14171), False, 'from collections import OrderedDict, defaultdict\n'), ((18749, 18794), 'itertools.product', 'itertools.product', (['fraction_choices'], {'repeat': 'L'}), '(fraction_choices, repeat=L)\n', (18766, 18794), False, 'import itertools\n'), ((9284, 9299), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (9297, 9299), False, 'import torch\n'), ((17895, 17923), 'numpy.array', 'np.array', (['perlayer_fractions'], {}), '(perlayer_fractions)\n', (17903, 17923), True, 'import numpy as np\n'), ((17951, 17982), 'numpy.argsort', 'np.argsort', (['(-perlayer_fractions)'], {}), '(-perlayer_fractions)\n', (17961, 17982), True, 'import numpy as np\n'), ((19756, 19786), 'numpy.array', 'np.array', (['max_acc[fraction][0]'], {}), '(max_acc[fraction][0])\n', (19764, 19786), True, 'import numpy as np\n'), ((19987, 20018), 'numpy.argsort', 'np.argsort', (['(-perlayer_fractions)'], {}), '(-perlayer_fractions)\n', (19997, 20018), True, 'import numpy as np\n'), ((13157, 13176), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (13174, 13176), False, 'import time\n'), ((9436, 9463), 'torch.from_numpy', 'torch.from_numpy', (['new_param'], {}), '(new_param)\n', (9452, 9463), False, 'import torch\n'), ((11395, 11409), 'numpy.prod', 'np.prod', (['shape'], {}), '(shape)\n', (11402, 11409), True, 'import numpy as np\n'), ((16073, 16101), 'numpy.array', 'np.array', (['perlayer_nchannels'], {}), '(perlayer_nchannels)\n', (16081, 16101), True, 'import numpy as np\n'), ((18884, 18935), 'numpy.multiply', 'np.multiply', (['perlayer_fractions', 'perlayer_nchannels'], {}), '(perlayer_fractions, perlayer_nchannels)\n', (18895, 18935), True, 'import numpy as np\n'), ((16877, 16928), 'numpy.multiply', 'np.multiply', (['perlayer_fractions', 'perlayer_nchannels'], {}), '(perlayer_fractions, perlayer_nchannels)\n', (16888, 16928), True, 'import numpy as np\n'), ((18034, 18085), 'numpy.multiply', 'np.multiply', (['perlayer_fractions', 'perlayer_nchannels'], {}), '(perlayer_fractions, perlayer_nchannels)\n', (18045, 18085), True, 'import numpy as np\n'), ((20070, 20121), 'numpy.multiply', 'np.multiply', (['perlayer_fractions', 'perlayer_nchannels'], {}), '(perlayer_fractions, perlayer_nchannels)\n', (20081, 20121), True, 'import numpy as np\n'), ((16613, 16666), 'numpy.searchsorted', 'np.searchsorted', (['perlayer_acc[name]', 'acc'], {'side': '"""left"""'}), "(perlayer_acc[name], acc, side='left')\n", (16628, 16666), True, 'import numpy as np\n'), ((17520, 17577), 'numpy.searchsorted', 'np.searchsorted', (['perlayer_acc[name]', 'acc_min'], {'side': '"""left"""'}), "(perlayer_acc[name], acc_min, side='left')\n", (17535, 17577), True, 'import numpy as np\n'), ((8220, 8242), 'torch.from_numpy', 'torch.from_numpy', (['acts'], {}), '(acts)\n', (8236, 8242), False, 'import torch\n')]
import numpy as np import pylab as pl from scipy import io # Adding Files and locations froot = '/home/hari/Documents/PythonCodes/EfferentFFR/' f331 = True addMEM = False if f331: froot = froot + 'f331/' f0 = 331.0 subjlist = ['I08', 'I14', 'I33', 'I41', 'I52', 'I11', 'I13', 'I12', 'I07'] MEMlist = ['I02', 'I53', 'I29', 'I39', 'I54'] if addMEM: subjlist += MEMlist ch = [3, 30, 31, 23, 22] else: f0 = 100.0 subjlist = ['I08', 'I14', 'I29', 'I33', 'I39', 'I41', 'I52', 'I11', 'I02'] ch = [30, ] cpca = False if cpca: measureName = 'cplv' else: measureName = 'S' condstemlist = ['signalOnly', 'simultaneousNoise', 'noise500ms_ahead', 'forwardMasking'] results = np.zeros(len(condstemlist)) normRes = np.zeros((len(subjlist), len(condstemlist) - 1)) abs70dB = np.zeros(len(subjlist)) for ks, subj in enumerate(subjlist): fpath = froot + subj + '/' # These are so that the generated files are organized better respath = fpath + 'RES/' for k, cond in enumerate(condstemlist): fname = respath + subj + '_' + cond + '_results.mat' dat = io.loadmat(fname) f = dat['f'].squeeze() if cpca: measure = dat[measureName].squeeze() else: measure = dat[measureName].squeeze()[ch, :].mean(axis=0) ind = np.argmin(np.abs(f - f0)) results[k] = measure[ind] if k == 1: abs70dB[ks] = np.log10(results[k] / 1e-6) normRes[ks, 0] = np.log10(results[1]/results[0]) * 20 normRes[ks, 1] = 0.8*np.log10(results[2]/results[1]) * 20 normRes[ks, 2] = np.log10(results[3]/results[1]) * 20 mu = normRes.mean(axis=0) se = normRes.std(axis=0) / len(subjlist)**0.5 pl.bar(np.arange(1, 4) - 0.25, mu, width=0.5) pl.hold(True) pl.errorbar(np.arange(1, 4), mu, yerr=se, fmt='ok', linewidth=3) pl.show()
[ "pylab.hold", "pylab.show", "numpy.abs", "scipy.io.loadmat", "numpy.arange", "numpy.log10" ]
[((1798, 1811), 'pylab.hold', 'pl.hold', (['(True)'], {}), '(True)\n', (1805, 1811), True, 'import pylab as pl\n'), ((1877, 1886), 'pylab.show', 'pl.show', ([], {}), '()\n', (1884, 1886), True, 'import pylab as pl\n'), ((1824, 1839), 'numpy.arange', 'np.arange', (['(1)', '(4)'], {}), '(1, 4)\n', (1833, 1839), True, 'import numpy as np\n'), ((1155, 1172), 'scipy.io.loadmat', 'io.loadmat', (['fname'], {}), '(fname)\n', (1165, 1172), False, 'from scipy import io\n'), ((1522, 1555), 'numpy.log10', 'np.log10', (['(results[1] / results[0])'], {}), '(results[1] / results[0])\n', (1530, 1555), True, 'import numpy as np\n'), ((1642, 1675), 'numpy.log10', 'np.log10', (['(results[3] / results[1])'], {}), '(results[3] / results[1])\n', (1650, 1675), True, 'import numpy as np\n'), ((1759, 1774), 'numpy.arange', 'np.arange', (['(1)', '(4)'], {}), '(1, 4)\n', (1768, 1774), True, 'import numpy as np\n'), ((1377, 1391), 'numpy.abs', 'np.abs', (['(f - f0)'], {}), '(f - f0)\n', (1383, 1391), True, 'import numpy as np\n'), ((1472, 1500), 'numpy.log10', 'np.log10', (['(results[k] / 1e-06)'], {}), '(results[k] / 1e-06)\n', (1480, 1500), True, 'import numpy as np\n'), ((1584, 1617), 'numpy.log10', 'np.log10', (['(results[2] / results[1])'], {}), '(results[2] / results[1])\n', (1592, 1617), True, 'import numpy as np\n')]
import pandas as pd import csv from collections import OrderedDict, defaultdict, Counter from datetime import datetime import pickle as pkl import os import numpy as np import logging import matplotlib # avoid xWindows errors in plotting matplotlib.use('Agg') import matplotlib.pyplot as plt #PROCESSEDPATH='processed/' DATAPATH='/data/users/sarthak/comcast-data/' PROCESSEDPATH='/data/users/sarthak/comcast-data/processed/' OUTPUTPATH='/data/users/sarthak/comcast-data/output/' ''' Generate a test data/control set for quick play 1. test-data-set head -300 250-test.dat > test-data-set.dat tail -300 250-test.dat >> test-data-set.dat 2. test-control-set head -300 control1.dat > test-control-set.dat tail -300 control1.dat >> test-control-set.dat ''' DATASET='250-test' CONTROLSET='control1' keys = ['Device_number', 'end_time', 'date_service_created', 'service_class_name', 'cmts_inet', 'service_direction', 'port_name', 'octets_passed', 'device_key', 'service_identifier'] header_row = ['Device_number', 'end_time', 'cmts_inet', 'service_direction', 'octets_passed'] logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p') logger = logging.getLogger() logger.setLevel('DEBUG') DEBUG_ROW_DISPLAY = 100000 #display every 100,000th row in original data DEBUG_LOG_COUNTER_DISPLAY = 100 #display every 100th device number def read_dataframe(folder, filename): header_row = ['device_number', 'end_time', 'cmts_inet', 'direction', 'bytes'] return pd.read_csv(PROCESSEDPATH + folder + '/' + filename, names=header_row) # CDF plotter def plotCDF_list(data, ax, c='blue'): ''' data = list for which we need to plot cdf ax = axis ''' sorted_data=np.sort( data ) #logger.debug(sorted_data) #yvals=np.arange(len(sorted_data))/float(len(sorted_data)) yvals=np.cumsum(sorted_data) #logger.debug(yvals) ax.plot( sorted_data, yvals, color=c ) return def plotCDF_counter(counter, ax, c='blue'): ''' data = Counter object, not in increasing order ax = axis ''' sorted_keys=sorted( counter ) #log.debug(sorted_data) #yvals=np.arange(len(sorted_data))/float(len(sorted_data)) yvals=np.cumsum([counter[k] for k in sorted_keys]) #log.debug(yvals) ax.plot( sorted_keys, yvals, color=c, marker='o' ) return if __name__ == "__main__": # load pickles for plotting cdf # Load Data peakUsage = pkl.load(open(OUTPUTPATH+DATASET+"/"+'peakBytesPerUser.pkl', 'r')) noZeroHist = pkl.load(open(OUTPUTPATH+DATASET+"/"+'noZeroCounter.pkl', 'r')) peakHist = pkl.load(open(OUTPUTPATH+DATASET+"/"+'peakCounter.pkl', 'r')) peakUsage_control = pkl.load(open(OUTPUTPATH+CONTROLSET+"/"+'peakBytesPerUser.pkl', 'r')) noZeroHist_control = pkl.load(open(OUTPUTPATH+CONTROLSET+"/"+'noZeroCounter.pkl', 'r')) peakHist_control = pkl.load(open(OUTPUTPATH+CONTROLSET+"/"+'peakCounter.pkl', 'r')) logger.info("Plotting...") # plot double subplot CDFs for upstream and downstream # peak usage per user over all time fig0, ax0 = plt.subplots(2, 1, sharex=True) plotCDF_list(peakUsage['up'].values(), ax0[0]) plotCDF_list(peakUsage_control['up'].values(), ax0[0], 'g') plotCDF_list(peakUsage['dw'].values(), ax0[1]) plotCDF_list(peakUsage_control['dw'].values(), ax0[1], 'g') ax0[1].set_xlabel('Peak Bytes per Device Number [Bytes]') ax0[0].set_ylabel('CDF') ax0[1].set_ylabel('CDF') fig0.savefig(OUTPUTPATH + "peakBytesPerDeviceCDF") # No Zeros CDF fig1, ax1 = plt.subplots(2, 1) plotCDF_counter(noZeroHist['up'], ax1[0]) plotCDF_counter(noZeroHist_control['up'], ax1[0], 'g') plotCDF_counter(noZeroHist['dw'], ax1[1]) plotCDF_counter(noZeroHist_control['dw'], ax1[1], 'g') ax1[1].set_xlabel('Non Zero Bytes per Device time-slot [Bytes]') ax1[0].set_ylabel('CDF') ax1[1].set_ylabel('CDF') fig1.savefig(OUTPUTPATH + "noZeroCDF") #fig1.show() fig2, ax2 = plt.subplots(2, 1) plotCDF_counter(peakHist['up'], ax2[0]) plotCDF_counter(peakHist_control['up'], ax2[0], 'g') plotCDF_counter(peakHist['dw'], ax2[1]) plotCDF_counter(peakHist_control['dw'], ax2[1], 'g') ax2[1].set_xlabel('Peak Bytes per Device per Day [Bytes]') ax2[0].set_ylabel('CDF') ax2[1].set_ylabel('CDF') fig2.savefig(OUTPUTPATH + "peakBytesPerDayPerDeviceCDF") #fig2.show()
[ "logging.basicConfig", "pandas.read_csv", "numpy.sort", "numpy.cumsum", "matplotlib.use", "matplotlib.pyplot.subplots", "logging.getLogger" ]
[((238, 259), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (252, 259), False, 'import matplotlib\n'), ((1212, 1302), 'logging.basicConfig', 'logging.basicConfig', ([], {'format': '"""%(asctime)s %(message)s"""', 'datefmt': '"""%m/%d/%Y %I:%M:%S %p"""'}), "(format='%(asctime)s %(message)s', datefmt=\n '%m/%d/%Y %I:%M:%S %p')\n", (1231, 1302), False, 'import logging\n'), ((1307, 1326), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (1324, 1326), False, 'import logging\n'), ((1634, 1704), 'pandas.read_csv', 'pd.read_csv', (["(PROCESSEDPATH + folder + '/' + filename)"], {'names': 'header_row'}), "(PROCESSEDPATH + folder + '/' + filename, names=header_row)\n", (1645, 1704), True, 'import pandas as pd\n'), ((1850, 1863), 'numpy.sort', 'np.sort', (['data'], {}), '(data)\n', (1857, 1863), True, 'import numpy as np\n'), ((1970, 1992), 'numpy.cumsum', 'np.cumsum', (['sorted_data'], {}), '(sorted_data)\n', (1979, 1992), True, 'import numpy as np\n'), ((2333, 2377), 'numpy.cumsum', 'np.cumsum', (['[counter[k] for k in sorted_keys]'], {}), '([counter[k] for k in sorted_keys])\n', (2342, 2377), True, 'import numpy as np\n'), ((3210, 3241), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(2)', '(1)'], {'sharex': '(True)'}), '(2, 1, sharex=True)\n', (3222, 3241), True, 'import matplotlib.pyplot as plt\n'), ((3686, 3704), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(2)', '(1)'], {}), '(2, 1)\n', (3698, 3704), True, 'import matplotlib.pyplot as plt\n'), ((4122, 4140), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(2)', '(1)'], {}), '(2, 1)\n', (4134, 4140), True, 'import matplotlib.pyplot as plt\n')]
#!/usr/bin/env python import numpy as np from scipy.spatial.distance import cdist def cosine_distance(row_patterns, col_patterns, e=1e-10): """A fast and naive implementation of cosine distance. Numerical stability issues might arise. :param row_patterns: A matrix with row vectors of dimensions MxN. :param col_patterns: A matrix of column vectors of dimensions NxK. The matrix can also be the transpose of row_patterns. :param e: A small constant to deal with numerical instability. :return: A matrix of MxK containing the pair-wise distance of all vectors given. """ row_l2 = np.linalg.norm(row_patterns, axis=1) col_l2 = np.linalg.norm(col_patterns, axis=0) row_l2[row_l2 == 0] = e col_l2[col_l2 == 0] = e magnitude_mat = np.dot(row_l2[:, None], col_l2[None, :]) similarity_mat = np.dot(row_patterns, col_patterns) / magnitude_mat return 1 - similarity_mat def get_pr_rec_at(q_features, q_labels, ret_features=None, ret_labels=None, e=1e-32, mode="unspecified", metric="cosine", singleton_samples="chop"): """Provides Precision recall matrices needed for computing mAP. :param q_features: A matrix with the the query row-vectors :param q_labels: A vector with the numerical labels corresponding to each query vector. :param ret_features: A matrix of the same width as q_features containing the row-vectors of the retrieval database. :param ret_labels: A vector with the numerical labels corresponding to each retrieval vector. :param e: A small constant, smaller that any meaningful distance between samples used to control sorting ambiguity. The constant is also used to deal with divisions by 0. :param mode: How to deal with ambiguous sorts. Must be one of ["unspecified", "optimistic", "pessimistic"]. Optimistic will return the most favorable sorting and pessimistic will return the leat favorable sorting. :param metric: The metric by which distances are computed between vectors. This must be one that scipy.spatial.distance.cdist accepts. Popular choices are ['cityblock', 'euclidean', 'cosine']. Look into cdist's documentation for details. :param singleton_samples: What to do with query labels that don't exist in the database. It must be one of ["chop", "perfect", "balanced", "null"]. Selecting "chop" means that row's referring to queries that did not exist, will be omitted from the result matrix. Selecting "perfect" means that the non-retrievable rows will get always 100% precision and recall. Selecting "balanced" means that the non-retrievable rows will get always 0% precision and 100% recall. Selecting "null" means that the non-retrievable rows will get always 0% precision and 0% recall. :return: Two matrices of the same size where the rows refer to query samples and columns refer to retrieval samples. The first one contains precition_@ rows while the second one contains recall_@. """ assert singleton_samples in ["chop", "perfect", "balanced", "null"] assert mode in ["unspecified", "optimistic", "pessimistic"] if ret_labels is None: assert ret_features is None # labels and features must be coupled ret_features = q_features ret_labels = q_labels leave_one_out = True else: leave_one_out = False dist_mat = cdist(q_features, ret_features, metric=metric).astype( np.double) correct = (q_labels.reshape(-1, 1) == ret_labels.reshape(1, -1)).astype( "float") if mode == "optimistic": dist_mat -= correct * e elif mode == "pessimistic": dist_mat += correct * e nearest_idx = np.argsort(dist_mat, axis=1) correct_predictions = q_labels[:, None] == ret_labels[nearest_idx] # each row in correct_predictions contains the index of the retrieval # samples sorted by distance for each query. if leave_one_out: # In leave one out we retrive all samples from all samples # The nearest sample to each query will be the query its self. correct_predictions = correct_predictions[:, 1:] correct_predictions = correct_predictions.astype("double") correct_at = np.cumsum(correct_predictions, axis=1) recall_at = (correct_at + e) / ( correct_predictions.sum(axis=1)[:, None] + e) precision_at = correct_at / np.cumsum(np.ones_like(recall_at), axis=1) if singleton_samples == "chop": exist_idx = np.nonzero(correct_predictions.sum(axis=1) > 0)[0] return precision_at[exist_idx, :], recall_at[exist_idx, :] elif singleton_samples == "perfect": non_existent = np.nonzero(correct_predictions.sum(axis=1) < 1)[0] precision_at[non_existent, :] = 1 recall_at[non_existent, :] = 1 return precision_at, recall_at elif singleton_samples == "null": non_existent = np.nonzero(correct_predictions.sum(axis=1) < 1)[0] precision_at[non_existent, :] = 0 recall_at[non_existent, :] = 0 return precision_at, recall_at elif singleton_samples == "balanced": non_existent = np.nonzero(correct_predictions.sum(axis=1) < 1)[0] precision_at[non_existent, :] = 1 recall_at[non_existent, :] = 1 return precision_at, recall_at else: raise Exception() def get_map(q_features, q_labels, ret_features=None, ret_labels=None, mode="bounds", e=1e-20, metric="euclidean", singleton_samples="chop"): """Provides mean Average Precision mAP estimates. :param q_features: A matrix with the the query row-vectors. :param q_labels: A vector with the numerical labels corresponding to each query vector. :param ret_features: A matrix of the same width as q_features containing the row-vectors of the retrieval database. :param ret_labels: A vector with the numerical labels corresponding to each retrieval vector. :param e: A small constant, smaller that any meaningful distance between samples used to control sorting ambiguity. The constant is also used to deal with divisions by 0. :param mode: How to deal with ambiguous sorts. Must be one of ["unspecified", "optimistic", "pessimistic", "bounds"]. Optimistic will return the most favorable sorting and "pessimistic" will return the least favorable sorting. When mode is "bounds" than both "optimistic" and "pessimistic" are returned. :param metric: The metric by which distances are computed between vectors. This must be one that scipy.spatial.distance.cdist accepts. Popular choices are ['cityblock', 'euclidean', 'cosine']. Look into cdist's documentation for details. :param singleton_samples: What to do with query labels that don't exist in the database. It must be one of ["chop", "perfect", "balanced", "null"]. Selecting "chop" means that row's referring to queries that did not exist, will be omitted from the result matrix. Selecting "perfect" means that the non-retrievable rows will get always 100% precision and recall. Selecting "balanced" means that the non-retrievable rows will get always 0% precision and 100% recall. Selecting "null" means that the non-retrievable rows will get always 0% precision and 0% recall. :return: A floating point number containing the estimate of mAP. If mode was "bounds" than a tuple with the lower and upper bounds of mAP. """ assert mode in ["unspecified", "optimistic", "pessimistic", "mean", "bounds"] if mode in ["mean", "bounds"]: pr_at, rec_at = get_pr_rec_at(q_features, q_labels, ret_features, ret_labels, mode="optimistic", e=e, metric=metric, singleton_samples=singleton_samples) padded_rec_at = np.concatenate( (np.zeros([rec_at.shape[0], 1]), rec_at), axis=1) rec_changes_at = padded_rec_at[:, 1:] > padded_rec_at[:, :-1] average_pr = (pr_at * rec_changes_at).sum( axis=1) / rec_changes_at.sum(axis=1) optimist = average_pr.mean() pr_at, rec_at = get_pr_rec_at(q_features, q_labels, ret_features, ret_labels, mode="pessimistic", e=e, metric=metric, singleton_samples=singleton_samples) padded_rec_at = np.concatenate( (np.zeros([rec_at.shape[0], 1]), rec_at), axis=1) rec_changes_at = padded_rec_at[:, 1:] > padded_rec_at[:, :-1] average_pr = (pr_at * rec_changes_at).sum( axis=1) / rec_changes_at.sum(axis=1) pessimist = average_pr.mean() if mode == "mean": return (optimist + pessimist) / 2 else: return optimist, pessimist else: pr_at, rec_at = get_pr_rec_at(q_features, q_labels, ret_features, ret_labels, mode=mode, e=e, metric=metric, singleton_samples=singleton_samples) padded_rec_at = np.concatenate( (np.zeros([rec_at.shape[0], 1]), rec_at), axis=1) rec_changes_at = padded_rec_at[:, 1:] > padded_rec_at[:, :-1] average_pr = (pr_at * rec_changes_at).sum( axis=1) / rec_changes_at.sum(axis=1) return average_pr.mean()
[ "scipy.spatial.distance.cdist", "numpy.ones_like", "numpy.zeros", "numpy.argsort", "numpy.cumsum", "numpy.linalg.norm", "numpy.dot" ]
[((627, 663), 'numpy.linalg.norm', 'np.linalg.norm', (['row_patterns'], {'axis': '(1)'}), '(row_patterns, axis=1)\n', (641, 663), True, 'import numpy as np\n'), ((677, 713), 'numpy.linalg.norm', 'np.linalg.norm', (['col_patterns'], {'axis': '(0)'}), '(col_patterns, axis=0)\n', (691, 713), True, 'import numpy as np\n'), ((790, 830), 'numpy.dot', 'np.dot', (['row_l2[:, None]', 'col_l2[None, :]'], {}), '(row_l2[:, None], col_l2[None, :])\n', (796, 830), True, 'import numpy as np\n'), ((3910, 3938), 'numpy.argsort', 'np.argsort', (['dist_mat'], {'axis': '(1)'}), '(dist_mat, axis=1)\n', (3920, 3938), True, 'import numpy as np\n'), ((4430, 4468), 'numpy.cumsum', 'np.cumsum', (['correct_predictions'], {'axis': '(1)'}), '(correct_predictions, axis=1)\n', (4439, 4468), True, 'import numpy as np\n'), ((852, 886), 'numpy.dot', 'np.dot', (['row_patterns', 'col_patterns'], {}), '(row_patterns, col_patterns)\n', (858, 886), True, 'import numpy as np\n'), ((3537, 3583), 'scipy.spatial.distance.cdist', 'cdist', (['q_features', 'ret_features'], {'metric': 'metric'}), '(q_features, ret_features, metric=metric)\n', (3542, 3583), False, 'from scipy.spatial.distance import cdist\n'), ((4606, 4629), 'numpy.ones_like', 'np.ones_like', (['recall_at'], {}), '(recall_at)\n', (4618, 4629), True, 'import numpy as np\n'), ((8333, 8363), 'numpy.zeros', 'np.zeros', (['[rec_at.shape[0], 1]'], {}), '([rec_at.shape[0], 1])\n', (8341, 8363), True, 'import numpy as np\n'), ((9035, 9065), 'numpy.zeros', 'np.zeros', (['[rec_at.shape[0], 1]'], {}), '([rec_at.shape[0], 1])\n', (9043, 9065), True, 'import numpy as np\n'), ((9825, 9855), 'numpy.zeros', 'np.zeros', (['[rec_at.shape[0], 1]'], {}), '([rec_at.shape[0], 1])\n', (9833, 9855), True, 'import numpy as np\n')]
import csv import numpy as np import math import random from operator import itemgetter print("Please wait while we initialize...") def euclidean(a, b): l = len(a) val = 0 for i in range(l): if (i-1) in range(5): continue val += (a[i]-b[0][i])**2 val = math.sqrt(val) return val def ifLike(reco): g = y[id[reco[2]], 0] gi = -1 for i in range(len(genrelist)): if genrelist[i] == g: gi = i alpha = 0.08 for j in range(30): myavg[gi][j] = alpha*(x[id[reco[2]]].tolist()[0][j] ) + (1-alpha)*myavg[gi][j] def ifDislike(reco, reason): if reason == "artist": dislikedArtist.append(y[id[reco[2]]].tolist()[0][2]) return def ifPlaylist(reco): g = y[id[reco[2]], 0] gi = -1 for i in range(len(genrelist)): if genrelist[i] == g: gi = i alpha = 0.12 for j in range(30): myavg[gi][j] = alpha*(x[id[reco[2]]].tolist()[0][j] ) + (1-alpha)*myavg[gi][j] def ifPlay(reco): g = y[id[reco[2]], 0] gi = -1 for i in range(len(genrelist)): if genrelist[i] == g: gi = i alpha = 0.04 for j in range(30): myavg[gi][j] = alpha*(x[id[reco[2]]].tolist()[0][j] ) + (1-alpha)*myavg[gi][j] r = csv.reader(open('tracks.csv', 'r', encoding='utf8')) lst = list(r) x = np.matrix(lst) y = x[1:, 0:4] x = x[1:, 4:].astype('double') id = {} dislikedArtist = [] for i in range(30): max = np.amax(x[:, i]) min = np.amin(x[:, i]) avg = sum(z.item(i) for z in x) diff = max-min x[:, i] = (x[:, i]-min)/diff genrelist = [] for i in range(len(y)): id[y[i, 1]] = i if y[i, 0] not in genrelist: genrelist.append(y[i, 0]) timbre = [[0 for x in range(30)] for z in range(len(genrelist))] cnt = [0 for z in range(len(genrelist))] for j in range(len(genrelist)): for i in range(len(y)): if y[i, 0] == genrelist[j]: timbre[j] = [timbre[j][k]+x[i, k] for k in range(30)] cnt[j] = cnt[j]+1 timbre = [[timbre[i][j]/cnt[i] for j in range(30)] for i in range(len(genrelist))] print('welcome to fitopsy') like = [] dislike = [] playlist = [] ignore = [] visited = [] play = [] ignlen = 2 time = 0 print("genre list, choose give us the list of genres you like, comma sepearted") print("1. rock\n2. punk\n3. folk\n4. pop\n5. dance and electronica\n6. metal\n7. jazz and blues\n8. classical\n9. hip-hop\n10. soul and reggae") inp = input("Enter: ") genres = inp.split(',') genres = [int(genres[i]) for i in range(len(genres))] myavg = [[0 for i in range(30)] for j in range(len(timbre))] active = [] history = [] for i in range(len(genres)): myavg[genres[i]-1] = timbre[genres[i]-1] active.append(genres[i]-1) lmt = 5 while len(history) < lmt: candidate = [[] for i in range(len(genres))] for i in range(len(active)): genre = genrelist[genres[i]-1] for j in range(len(x)): if y[j, 0] == genre: if y[j, 1] in visited: continue dist = euclidean(myavg[active[i]], x[j, :].tolist()) candidate[i].append((dist, j)) candidate = [sorted(candidate[i], key=itemgetter(0)) for i in range(len(candidate))] recommend = [] for i in range(len(genres)): for j in range(5): recommend.append( (y[candidate[i][j][1], 3], y[candidate[i][j][1], 2], y[candidate[i][j][1], 1], candidate[i][j][0])) recommend = sorted(recommend, key=itemgetter(3)) print('here are your initial music recommendations based on your favorite genre') for i in range(len(recommend)): print(recommend[i][0], 'by', recommend[i][1]) print("Enter your choice") print("1: Like") print("2: Dislike") print("3: Add to playlist") print("4: Ignore") print("5: Play") inp = int(input()) if inp == 1: like.append((recommend[i], time)) ifLike(recommend[i]) visited.append(recommend[i][2]) history.append((recommend[i][2], 2)) elif inp == 2: print("Enter reason for disliking (artist/song):") ip = input() ifDislike(recommend[i], ip) dislike.append((recommend[i], time)) visited.append(recommend[i][2]) elif inp == 3: ifPlaylist(recommend[i]) playlist.append((recommend[i], time)) visited.append(recommend[i][2]) history.append((recommend[i][2], 3)) elif inp == 4: if len(ignore) < ignlen: ignore.append((recommend[i], time)) visited.append(recommend[i][2]) else: dslk = ignore.pop(0) visited.remove(dslk[0][2]) ignore.append((recommend[i], time)) visited.append(recommend[i][2]) else: ifPlay(recommend[i]) play.append((recommend[i], time)) visited.append(recommend[i][2]) history.append((recommend[i][2], 1)) while (True): recocnt = [0 for i in range(len(genrelist))] candidate = [[] for i in range(len(genrelist))] leng = len(candidate) for i in range(len(genrelist)): if i not in active: continue genre = genrelist[i] for j in range(len(x)): if y[j, 0] == genre: if (y[j, 1] in visited) or (y[j, 2] in dislikedArtist): continue dist = euclidean(myavg[i], x[j, :].tolist()) candidate[i].append((dist, j)) if len(active) == len(genrelist): g1 = random.randint(0, len(genrelist)-1) g2 = random.randint(0, len(genrelist)-1) g1 = inactive[g1] g2 = inactive[g2] for j in range(len(x)): intgenre = -1 for k in range(len(genrelist)): if genrelist[k] == y[j, 0]: intgenre = k if intgenre == g1: if (y[j, 1] in visited) or (y[j, 2] in dislikedArtist): continue dist = euclidean(myavg[g1], x[j, :].tolist()) candidate[g1].append((dist, j)) for j in range(len(x)): intgenre = -1 for k in range(len(genrelist)): if genrelist[k] == y[j, 0]: intgenre = k if intgenre == g2: if (y[j, 1] in visited) or (y[j, 2] in dislikedArtist): continue dist = euclidean(myavg[g2], x[j, :].tolist()) candidate[g2].append((dist, j)) if g1 == g2: recocnt[g1] = 2 else: recocnt[g1] = 1 recocnt[g2] = 1 else: inactive = [] for i in range(len(genrelist)): if i not in active: inactive.append(i) g1 = random.randint(0, len(inactive)-1) g2 = random.randint(0, len(inactive)-1) g1 = inactive[g1] g2 = inactive[g2] for j in range(len(x)): intgenre = -1 for k in range(len(genrelist)): if genrelist[k] == y[j, 0]: intgenre = k if intgenre == g1: if (y[j, 1] in visited) or (y[j, 2] in dislikedArtist): continue dist = euclidean(myavg[g1], x[j, :].tolist()) candidate[g1].append((dist, j)) for j in range(len(x)): intgenre = -1 for k in range(len(genrelist)): if genrelist[k] == y[j, 0]: intgenre = k if intgenre == g2: if (y[j, 1] in visited) or (y[j, 2] in dislikedArtist): continue dist = euclidean(myavg[g2], x[j, :].tolist()) candidate[g2].append((dist, j)) if g1 == g2: recocnt[g1] = 2 else: recocnt[g1] = 1 recocnt[g2] = 1 penalty = [[0 for i in range(len(candidate[j]))] for j in range(len(candidate))] for i in range(len(genrelist)): if i not in active: continue for j in range(len(candidate[i])): for k in range(len(dislike)): dslk = x[id[dislike[k][0][2]]] dist = euclidean(candidate[i][j], dslk.tolist()) penalty[i][j] = penalty[i][j]+0.02/dist for i in range(len(candidate)): for j in range(len(candidate[i])): candidate[i][j] = list(candidate[i][j]) candidate[i][j][0] = candidate[i][j][0] + penalty[i][j] candidate[i][j] = tuple(candidate[i][j]) candidate = [sorted(candidate[i], key=itemgetter(0)) for i in range(len(candidate))] recommend = [] l = int(len(history)) score = [0 for i in range(len(genrelist))] totscore = 0 for i in range(l-1, l-lmt-1, -1): g = y[id[history[i][0]]].tolist()[0][0] gi = -1 for j in range(len(genrelist)): if genrelist[j] == g: gi = j score[gi] = score[gi]+history[i][1] totscore = totscore+history[i][1] mx = -1 mxg = -1 done = 0 for i in range(len(genrelist)): if score[i] == 0: continue count = int(score[i]/totscore)*8 if (count == 0): count = 1 recocnt[i] = count done = done+count if mx < score[i]: mx = score[i] mxg = i recocnt[mxg] = recocnt[mxg]+8-done recommend = [] for i in range(len(genrelist)): if recocnt[i] == 0: continue l = recocnt[i] if len(candidate[i]) < recocnt[i]: l = len(candidate[i]) for j in range(l): recommend.append( (y[candidate[i][j][1], 3], y[candidate[i][j][1], 2], y[candidate[i][j][1], 1], candidate[i][j][0])) recommend = sorted(recommend, key=itemgetter(3)) print('here are your 10 new music recommendations') for i in range(len(recommend)): print(recommend[i][0], 'by', recommend[i][1]) print("Enter your choice") print("1: Like") print("2: Dislike") print("3: Add to playlist") print("4: Ignore") print("5: Play") inp = int(input()) if inp == 1: like.append((recommend[i], time)) ifLike(recommend[i]) visited.append(recommend[i][2]) history.append((recommend[i][2], 2)) elif inp == 2: print("Enter reason for disliking (artist/song):") ip = input() ifDislike(recommend[i], ip) dislike.append((recommend[i], time)) visited.append(recommend[i][2]) elif inp == 3: ifPlaylist(recommend[i]) playlist.append((recommend[i], time)) visited.append(recommend[i][2]) history.append((recommend[i][2], 3)) elif inp == 4: if len(ignore) < ignlen: ignore.append((recommend[i], time)) visited.append(recommend[i][2]) else: dslk = ignore.pop(0) visited.remove(dslk[0][2]) ignore.append((recommend[i], time)) visited.append(recommend[i][2]) else: ifPlay(recommend[i]) play.append((recommend[i], time)) visited.append(recommend[i][2]) history.append((recommend[i][2], 1))
[ "numpy.matrix", "numpy.amin", "math.sqrt", "numpy.amax", "operator.itemgetter" ]
[((1463, 1477), 'numpy.matrix', 'np.matrix', (['lst'], {}), '(lst)\n', (1472, 1477), True, 'import numpy as np\n'), ((303, 317), 'math.sqrt', 'math.sqrt', (['val'], {}), '(val)\n', (312, 317), False, 'import math\n'), ((1584, 1600), 'numpy.amax', 'np.amax', (['x[:, i]'], {}), '(x[:, i])\n', (1591, 1600), True, 'import numpy as np\n'), ((1611, 1627), 'numpy.amin', 'np.amin', (['x[:, i]'], {}), '(x[:, i])\n', (1618, 1627), True, 'import numpy as np\n'), ((3666, 3679), 'operator.itemgetter', 'itemgetter', (['(3)'], {}), '(3)\n', (3676, 3679), False, 'from operator import itemgetter\n'), ((10188, 10201), 'operator.itemgetter', 'itemgetter', (['(3)'], {}), '(3)\n', (10198, 10201), False, 'from operator import itemgetter\n'), ((3336, 3349), 'operator.itemgetter', 'itemgetter', (['(0)'], {}), '(0)\n', (3346, 3349), False, 'from operator import itemgetter\n'), ((8926, 8939), 'operator.itemgetter', 'itemgetter', (['(0)'], {}), '(0)\n', (8936, 8939), False, 'from operator import itemgetter\n')]
#from __future__ import absolute_import import cv2 import glob import numpy as np from output_saver import OutputSaver NUM_COLOR_CHANNELS = 3 CORNERS_PATH = '../output_images/corners/corners%d.jpg' ORIGINAL_PATH = '../output_images/original/original%d.jpg' UNDISTORTED_PATH = '../output_images/undistorted/undistorted%d.jpg' WARPED_PATH = '../output_images/warped/warped%d.jpg' class CameraCalibrator: def __init__(self, nx, ny, output_saver=None): self.nx = nx self.ny = ny self.output_saver = OutputSaver() if output_saver is None else output_saver def distortion_correction(self, glob_path): images = [cv2.imread(path) for path in glob.glob(glob_path)] object_points, image_points = self.get_points(images) undist_images = [] warped_images = [] for index, img in enumerate(self.output_saver.images[ORIGINAL_PATH]): undist = self.undistort_image(img, object_points, image_points) undist_images.append(undist) warped, M = self.perspective_transform(undist, image_points[index]) warped_images.append(warped) self.output_saver.images[UNDISTORTED_PATH] = undist_images self.output_saver.images[WARPED_PATH] = warped_images def undistort_image(self, img, objpoints, imgpoints): # Function that takes an image, object points, and image points # performs the camera calibration, image distortion correction and # returns the undistorted image #img_size = (img.shape[1], img.shape[0]) ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, img.shape[0:2], None, None) undist = cv2.undistort(img, mtx, dist, None, mtx) self.output_saver.add_calibration(mtx, dist) return undist def get_points(self, images): object_points = [] image_points = [] original_images = [] output_images = [] objp = self.__get_object_points() for img in images: gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) ret, corners = cv2.findChessboardCorners(gray, (self.nx, self.ny), None) if ret is True: img_corners = cv2.drawChessboardCorners(img.copy(), (self.nx, self.ny), corners, ret) image_points.append(corners) object_points.append(objp) output_images.append(img_corners) original_images.append(img) self.output_saver.images[CORNERS_PATH] = output_images self.output_saver.images[ORIGINAL_PATH] = original_images print('Number of Images with corners found: ' + str(len(output_images))) return np.array(object_points), np.array(image_points) def __get_object_points(self): #objp = np.zeros((6*8,3), np.float32) #objp[:,:2] = np.mgrid[0:8, 0:6].T.reshape(-1,2) object_points = np.zeros((self.nx*self.ny, NUM_COLOR_CHANNELS), np.float32) object_points[:,:2] = np.mgrid[0:self.nx, 0:self.ny].T.reshape(-1,2) return object_points # Define a function that takes an image, number of x and y points, # camera matrix and distortion coefficients def perspective_transform(self, undist, corners): # Convert undistorted image to grayscale gray = cv2.cvtColor(undist, cv2.COLOR_BGR2GRAY) # Choose offset from image corners to plot detected corners # This should be chosen to present the result at the proper aspect ratio # My choice of 100 pixels is not exact, but close enough for our purpose here offset = 100 # offset for dst points # Grab the image shape img_size = (gray.shape[1], gray.shape[0]) # For source points I'm grabbing the outer four detected corners src = np.float32([corners[0], corners[self.nx-1], corners[-1], corners[-self.nx]]) # For destination points, I'm arbitrarily choosing some points to be # a nice fit for displaying our warped result # again, not exact, but close enough for our purposes dst = np.float32([[offset, offset], [img_size[0]-offset, offset], [img_size[0]-offset, img_size[1]-offset], [offset, img_size[1]-offset]]) # Given src and dst points, calculate the perspective transform matrix M = cv2.getPerspectiveTransform(src, dst) # Warp the image using OpenCV warpPerspective() warped = cv2.warpPerspective(undist, M, img_size) # Return the resulting image and matrix return warped, M
[ "cv2.warpPerspective", "cv2.findChessboardCorners", "cv2.cvtColor", "cv2.getPerspectiveTransform", "numpy.float32", "numpy.zeros", "output_saver.OutputSaver", "cv2.imread", "numpy.array", "cv2.calibrateCamera", "glob.glob", "cv2.undistort" ]
[((1627, 1696), 'cv2.calibrateCamera', 'cv2.calibrateCamera', (['objpoints', 'imgpoints', 'img.shape[0:2]', 'None', 'None'], {}), '(objpoints, imgpoints, img.shape[0:2], None, None)\n', (1646, 1696), False, 'import cv2\n'), ((1714, 1754), 'cv2.undistort', 'cv2.undistort', (['img', 'mtx', 'dist', 'None', 'mtx'], {}), '(img, mtx, dist, None, mtx)\n', (1727, 1754), False, 'import cv2\n'), ((2940, 3001), 'numpy.zeros', 'np.zeros', (['(self.nx * self.ny, NUM_COLOR_CHANNELS)', 'np.float32'], {}), '((self.nx * self.ny, NUM_COLOR_CHANNELS), np.float32)\n', (2948, 3001), True, 'import numpy as np\n'), ((3345, 3385), 'cv2.cvtColor', 'cv2.cvtColor', (['undist', 'cv2.COLOR_BGR2GRAY'], {}), '(undist, cv2.COLOR_BGR2GRAY)\n', (3357, 3385), False, 'import cv2\n'), ((3836, 3914), 'numpy.float32', 'np.float32', (['[corners[0], corners[self.nx - 1], corners[-1], corners[-self.nx]]'], {}), '([corners[0], corners[self.nx - 1], corners[-1], corners[-self.nx]])\n', (3846, 3914), True, 'import numpy as np\n'), ((4121, 4265), 'numpy.float32', 'np.float32', (['[[offset, offset], [img_size[0] - offset, offset], [img_size[0] - offset, \n img_size[1] - offset], [offset, img_size[1] - offset]]'], {}), '([[offset, offset], [img_size[0] - offset, offset], [img_size[0] -\n offset, img_size[1] - offset], [offset, img_size[1] - offset]])\n', (4131, 4265), True, 'import numpy as np\n'), ((4419, 4456), 'cv2.getPerspectiveTransform', 'cv2.getPerspectiveTransform', (['src', 'dst'], {}), '(src, dst)\n', (4446, 4456), False, 'import cv2\n'), ((4530, 4570), 'cv2.warpPerspective', 'cv2.warpPerspective', (['undist', 'M', 'img_size'], {}), '(undist, M, img_size)\n', (4549, 4570), False, 'import cv2\n'), ((527, 540), 'output_saver.OutputSaver', 'OutputSaver', ([], {}), '()\n', (538, 540), False, 'from output_saver import OutputSaver\n'), ((667, 683), 'cv2.imread', 'cv2.imread', (['path'], {}), '(path)\n', (677, 683), False, 'import cv2\n'), ((2069, 2106), 'cv2.cvtColor', 'cv2.cvtColor', (['img', 'cv2.COLOR_BGR2GRAY'], {}), '(img, cv2.COLOR_BGR2GRAY)\n', (2081, 2106), False, 'import cv2\n'), ((2134, 2191), 'cv2.findChessboardCorners', 'cv2.findChessboardCorners', (['gray', '(self.nx, self.ny)', 'None'], {}), '(gray, (self.nx, self.ny), None)\n', (2159, 2191), False, 'import cv2\n'), ((2729, 2752), 'numpy.array', 'np.array', (['object_points'], {}), '(object_points)\n', (2737, 2752), True, 'import numpy as np\n'), ((2754, 2776), 'numpy.array', 'np.array', (['image_points'], {}), '(image_points)\n', (2762, 2776), True, 'import numpy as np\n'), ((696, 716), 'glob.glob', 'glob.glob', (['glob_path'], {}), '(glob_path)\n', (705, 716), False, 'import glob\n')]
# Author: <NAME> import numpy as np import scipy.stats import pandas as pd import argparse import pyBigWig import os import subprocess import io import gzip import pickle def padjust_bh(p): """ Benjamini-Hochberg ajdusted p-values Replicates p.adjust(p, method="BH") from R """ n = len(p) i = np.arange(n,0,-1) o = np.argsort(p)[::-1] ro = np.argsort(o) return np.minimum(1, np.minimum.accumulate(np.float(n)/i * np.array(p)[o]))[ro] parser = argparse.ArgumentParser(description='ASE') parser.add_argument('read_count_file_list', help='Read count file list (one per sample); [sample_id, tissue_site_detail, file_path]') parser.add_argument('het_vcf') parser.add_argument('vep_dict') parser.add_argument('simulation_bias_file', help='?') parser.add_argument('mappability_bigwig', help='Mappability track in bigWig format') parser.add_argument('tissue_abbreviations', help='File mapping tissue_site_detail to abbreviation') parser.add_argument('lamp_values', help='Table with foreign allele frequency per individual') parser.add_argument('individual_id', help='individual_id') parser.add_argument('--coverage_cutoff', default=8, type=int, help='') parser.add_argument('--other_ratio_cutoff', default=0.05, type=float, help='') parser.add_argument('--mono_cutoff', default=0.01, type=float, help='') parser.add_argument('-o', '--output_dir', default='.') args = parser.parse_args() print('Parsing inputs') tissue2abrv = pd.read_csv(args.tissue_abbreviations, sep='\t', index_col=0, squeeze=True).to_dict() readcount_file_df = pd.read_csv(args.read_count_file_list, sep='\t', index_col=0) df = pd.read_csv(args.simulation_bias_file, sep='\t', header=None, dtype=str) simulation_bias_set = set(df[0]+':'+df[1]) print('Parsing read count files') readcount_df_list = [] for i,rfile in enumerate(readcount_file_df['ase_readcount_file']): readcount_df = pd.read_csv(rfile, sep='\t', index_col=2) readcount_df = readcount_df[['contig', 'position', 'refAllele', 'altAllele', 'refCount', 'altCount', 'totalCount', 'otherBases']] readcount_df = readcount_df.rename(columns={'contig':'chr', 'position':'coord', 'refAllele':'ref', 'altAllele':'alt', 'refCount':'refcount', 'altCount':'altcount', 'totalCount':'totalcount', 'otherBases':'othercount'}) readcount_df = readcount_df[readcount_df['totalcount']>=args.coverage_cutoff] readcount_df['refratio'] = readcount_df['refcount']/readcount_df['totalcount'] readcount_df['otherratio'] = readcount_df['othercount'] / (readcount_df['othercount'] + readcount_df['totalcount']) readcount_df['otherflag'] = (readcount_df['otherratio']>=args.other_ratio_cutoff)*1 readcount_df['allcount'] = readcount_df['totalcount'] + readcount_df['othercount'] sample_id = readcount_file_df.index[i] readcount_df['sampid'] = sample_id readcount_df['subjid'] = '-'.join(sample_id.split('-')[:2]) readcount_df['tissue'] = readcount_file_df.loc[sample_id, 'tissue_site_detail'] readcount_df['tissueabrv'] = tissue2abrv[readcount_file_df.loc[sample_id, 'tissue_site_detail']] readcount_df['covflag'] = 0 # covflag is never 1, since filtered above (coverage_cutoff) readcount_df_list.append(readcount_df) print('Loading VCF') vcf_df = pd.read_csv(args.het_vcf, sep='\t', comment='#', header=None, names=['chr', 'pos', 'id', 'ref', 'alt', 'qual', 'filter', 'info', 'format', 'genotype'], dtype=str, usecols=['chr', 'pos', 'id', 'info','format', 'genotype'], index_col=2) vcf_snp_id_df = pd.DataFrame(index=vcf_df.index, columns=['chr', 'coord', 'genotype', 'ensg', 'vtype', 'mapbias', 'mapflag', 'monoflag', 'mono_refcount', 'mono_altcount', 'mono_totalcount', 'mono_othercount']) vcf_snp_id_df[['chr', 'coord']] = vcf_df[['chr', 'pos']] vcf_snp_id_df['genotype'] = vcf_df['format']+';'+vcf_df['genotype'] print('Adding VEP annotation') with open(args.vep_dict, 'rb') as f: vep_dict = pickle.load(f) ensg = [] vtype = [] for i in vcf_df.index: gene_name, vep = vep_dict.get(i, ('NA','NA')) ensg.append(gene_name) vtype.append(vep) vcf_snp_id_df['ensg'] = ensg vcf_snp_id_df['vtype'] = vtype vep_dict = None print('Adding mappability') mp = [] bw = pyBigWig.open(args.mappability_bigwig) for c,p in zip(vcf_df['chr'], vcf_df['pos']): mp.append((bw.stats(c, int(p)-1, int(p), exact=True)[0]!=1) * 1) # BED coordinates, 0-indexed; input must be int (not numpy) bw.close() vcf_snp_id_df['mapbias'] = [1 if i in simulation_bias_set else 0 for i in vcf_snp_id_df['chr']+':'+vcf_snp_id_df['coord']] vcf_snp_id_df['mapflag'] = mp vcf_snp_id_df['monoflag'] = 0 vcf_snp_id_df['mono_refcount'] = 0 vcf_snp_id_df['mono_altcount'] = 0 vcf_snp_id_df['mono_totalcount'] = 0 vcf_snp_id_df['mono_othercount'] = 0 for readcount_df in readcount_df_list: # combine read counts for each variant vcf_snp_id_df.loc[readcount_df.index, 'mono_refcount'] += readcount_df['refcount'] vcf_snp_id_df.loc[readcount_df.index, 'mono_altcount'] += readcount_df['altcount'] vcf_snp_id_df.loc[readcount_df.index, 'mono_totalcount'] += readcount_df['totalcount'] vcf_snp_id_df.loc[readcount_df.index, 'mono_othercount'] += readcount_df['othercount'] print('Calculating statistics') lamp = pd.read_csv(args.lamp_values, sep='\t', index_col=0, squeeze=True).median() ref = vcf_snp_id_df['mono_refcount'] tot = vcf_snp_id_df['mono_totalcount'] monop_list = scipy.stats.binom.cdf(tot-ref, tot, 1-lamp) + scipy.stats.binom.cdf(ref, tot, 1-lamp) # monoallelic_p monop_adj_list = padjust_bh(monop_list) vcf_snp_id_df['monoflag'] = (monop_adj_list > args.mono_cutoff) * 1 indiv_cov75_counts = [] for readcount_df in readcount_df_list: readcount_df['GENOTYPE_WARNING'] = vcf_snp_id_df.loc[readcount_df.index, 'monoflag'] idx = (vcf_snp_id_df.loc[readcount_df.index, ['monoflag', 'mapbias', 'mapflag']].sum(axis=1)==0) & (readcount_df['otherflag']==0) indiv_cov75_counts.extend(list(readcount_df.loc[idx, 'totalcount'])) cov75 = np.percentile(indiv_cov75_counts, 75) print('Calculating bias') genomewide_bias = [0.0, 0.0, 0] for readcount_df in readcount_df_list: idx = (readcount_df[['covflag', 'otherflag']].sum(axis=1) + vcf_snp_id_df.loc[readcount_df.index, ['mapbias', 'mapflag', 'monoflag']].sum(axis=1)) == 0 refcountcov = readcount_df.loc[idx, 'refcount'] altcountcov = readcount_df.loc[idx, 'altcount'] totcountcov = refcountcov + altcountcov bias_keys = readcount_df.loc[idx, 'ref']+'/'+readcount_df.loc[idx, 'alt'] idx2 = (refcountcov+altcountcov) > cov75 refcountcov[idx2] = cov75*(refcountcov[idx2]/totcountcov[idx2]) altcountcov[idx2] = cov75 - refcountcov[idx2] totcountcov[idx2] = cov75 genomewide_bias[0] += refcountcov.sum() genomewide_bias[1] += totcountcov.sum() genomewide_bias[2] += refcountcov.shape[0] genomewide_bias_value = float(genomewide_bias[0]) / genomewide_bias[1] print('Calculating binomial tests, adjusted p-values') for readcount_df in readcount_df_list: readcount_df['binom_p'] = [scipy.stats.binom_test(i, j, genomewide_bias_value) for i,j in zip(readcount_df['refcount'], readcount_df['totalcount'])] readcount_df['nullratio'] = genomewide_bias_value idx = (readcount_df[['covflag', 'otherflag']].sum(axis=1) + vcf_snp_id_df.loc[readcount_df.index, ['mapbias', 'mapflag', 'monoflag']].sum(axis=1))==0 readcount_df.loc[idx, 'binom_p_adj'] = padjust_bh(readcount_df.loc[idx, 'binom_p']) readcount_df.loc[~idx, 'binom_p_adj'] = 'NA' print('Writing output') with gzip.open(os.path.join(args.output_dir, args.individual_id+'.ase_table.tsv.gz'), 'wt') as f: f.write('\t'.join([ 'CHR', 'POS', 'VARIANT_ID', 'REF_ALLELE', 'ALT_ALLELE', 'SAMPLE_ID', 'SUBJECT_ID', 'TISSUE_ID', 'REF_COUNT', 'ALT_COUNT', 'TOTAL_COUNT', 'REF_RATIO', 'OTHER_ALLELE_COUNT', 'NULL_RATIO', 'BINOM_P', 'BINOM_P_ADJUSTED', 'MAMBA_POST_SINGLETIS', 'MAMBA_POST_MULTITIS', 'GENOTYPE', 'VARIANT_ANNOTATION', 'GENE_ID', 'LOW_MAPABILITY', 'MAPPING_BIAS_SIM', 'GENOTYPE_WARNING'])+'\n') merged_df = [] for readcount_df in readcount_df_list: readcount_df['id'] = readcount_df.index readcount_df['blank'] = 'NA' out_df = readcount_df[['chr', 'coord', 'id', 'ref', 'alt', 'sampid', 'subjid', 'tissueabrv', 'refcount', 'altcount', 'totalcount', 'refratio', 'othercount', 'nullratio', 'binom_p', 'binom_p_adj', 'blank', 'blank']] merged_df.append(pd.concat([out_df, vcf_snp_id_df.loc[readcount_df.index, ['genotype', 'vtype', 'ensg', 'mapflag', 'mapbias']], readcount_df['GENOTYPE_WARNING']], axis=1)) merged_df = pd.concat(merged_df, axis=0) merged_df = merged_df.sort_values(['chr', 'coord', 'tissueabrv']) merged_df.to_csv(f, sep='\t', index=False, header=False, float_format='%.6g') print('Done')
[ "pandas.DataFrame", "argparse.ArgumentParser", "pandas.read_csv", "numpy.float", "numpy.percentile", "numpy.argsort", "pickle.load", "pyBigWig.open", "numpy.arange", "numpy.array", "os.path.join", "pandas.concat" ]
[((488, 530), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""ASE"""'}), "(description='ASE')\n", (511, 530), False, 'import argparse\n'), ((1570, 1631), 'pandas.read_csv', 'pd.read_csv', (['args.read_count_file_list'], {'sep': '"""\t"""', 'index_col': '(0)'}), "(args.read_count_file_list, sep='\\t', index_col=0)\n", (1581, 1631), True, 'import pandas as pd\n'), ((1637, 1709), 'pandas.read_csv', 'pd.read_csv', (['args.simulation_bias_file'], {'sep': '"""\t"""', 'header': 'None', 'dtype': 'str'}), "(args.simulation_bias_file, sep='\\t', header=None, dtype=str)\n", (1648, 1709), True, 'import pandas as pd\n'), ((3276, 3523), 'pandas.read_csv', 'pd.read_csv', (['args.het_vcf'], {'sep': '"""\t"""', 'comment': '"""#"""', 'header': 'None', 'names': "['chr', 'pos', 'id', 'ref', 'alt', 'qual', 'filter', 'info', 'format',\n 'genotype']", 'dtype': 'str', 'usecols': "['chr', 'pos', 'id', 'info', 'format', 'genotype']", 'index_col': '(2)'}), "(args.het_vcf, sep='\\t', comment='#', header=None, names=['chr',\n 'pos', 'id', 'ref', 'alt', 'qual', 'filter', 'info', 'format',\n 'genotype'], dtype=str, usecols=['chr', 'pos', 'id', 'info', 'format',\n 'genotype'], index_col=2)\n", (3287, 3523), True, 'import pandas as pd\n'), ((3536, 3737), 'pandas.DataFrame', 'pd.DataFrame', ([], {'index': 'vcf_df.index', 'columns': "['chr', 'coord', 'genotype', 'ensg', 'vtype', 'mapbias', 'mapflag',\n 'monoflag', 'mono_refcount', 'mono_altcount', 'mono_totalcount',\n 'mono_othercount']"}), "(index=vcf_df.index, columns=['chr', 'coord', 'genotype',\n 'ensg', 'vtype', 'mapbias', 'mapflag', 'monoflag', 'mono_refcount',\n 'mono_altcount', 'mono_totalcount', 'mono_othercount'])\n", (3548, 3737), True, 'import pandas as pd\n'), ((4216, 4254), 'pyBigWig.open', 'pyBigWig.open', (['args.mappability_bigwig'], {}), '(args.mappability_bigwig)\n', (4229, 4254), False, 'import pyBigWig\n'), ((5993, 6030), 'numpy.percentile', 'np.percentile', (['indiv_cov75_counts', '(75)'], {}), '(indiv_cov75_counts, 75)\n', (6006, 6030), True, 'import numpy as np\n'), ((324, 343), 'numpy.arange', 'np.arange', (['n', '(0)', '(-1)'], {}), '(n, 0, -1)\n', (333, 343), True, 'import numpy as np\n'), ((379, 392), 'numpy.argsort', 'np.argsort', (['o'], {}), '(o)\n', (389, 392), True, 'import numpy as np\n'), ((1898, 1939), 'pandas.read_csv', 'pd.read_csv', (['rfile'], {'sep': '"""\t"""', 'index_col': '(2)'}), "(rfile, sep='\\t', index_col=2)\n", (1909, 1939), True, 'import pandas as pd\n'), ((3939, 3953), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (3950, 3953), False, 'import pickle\n'), ((8818, 8846), 'pandas.concat', 'pd.concat', (['merged_df'], {'axis': '(0)'}), '(merged_df, axis=0)\n', (8827, 8846), True, 'import pandas as pd\n'), ((350, 363), 'numpy.argsort', 'np.argsort', (['p'], {}), '(p)\n', (360, 363), True, 'import numpy as np\n'), ((1464, 1539), 'pandas.read_csv', 'pd.read_csv', (['args.tissue_abbreviations'], {'sep': '"""\t"""', 'index_col': '(0)', 'squeeze': '(True)'}), "(args.tissue_abbreviations, sep='\\t', index_col=0, squeeze=True)\n", (1475, 1539), True, 'import pandas as pd\n'), ((5249, 5315), 'pandas.read_csv', 'pd.read_csv', (['args.lamp_values'], {'sep': '"""\t"""', 'index_col': '(0)', 'squeeze': '(True)'}), "(args.lamp_values, sep='\\t', index_col=0, squeeze=True)\n", (5260, 5315), True, 'import pandas as pd\n'), ((7562, 7633), 'os.path.join', 'os.path.join', (['args.output_dir', "(args.individual_id + '.ase_table.tsv.gz')"], {}), "(args.output_dir, args.individual_id + '.ase_table.tsv.gz')\n", (7574, 7633), False, 'import os\n'), ((8647, 8809), 'pandas.concat', 'pd.concat', (["[out_df, vcf_snp_id_df.loc[readcount_df.index, ['genotype', 'vtype', 'ensg',\n 'mapflag', 'mapbias']], readcount_df['GENOTYPE_WARNING']]"], {'axis': '(1)'}), "([out_df, vcf_snp_id_df.loc[readcount_df.index, ['genotype',\n 'vtype', 'ensg', 'mapflag', 'mapbias']], readcount_df[\n 'GENOTYPE_WARNING']], axis=1)\n", (8656, 8809), True, 'import pandas as pd\n'), ((440, 451), 'numpy.float', 'np.float', (['n'], {}), '(n)\n', (448, 451), True, 'import numpy as np\n'), ((456, 467), 'numpy.array', 'np.array', (['p'], {}), '(p)\n', (464, 467), True, 'import numpy as np\n')]
import pickle import os from torch.utils import data import numpy as np import torch import torchvision.transforms as transforms from PIL import Image import random from collections import Counter class DataloaderCifar10_MultiLabel(data.Dataset): def __init__(self, img_size=32, is_transform=False, split='train', noise_ratio_list=[0.2, 0.3, 0.4]): self.split = split self.img_size = img_size self.is_transform = is_transform self.transform_train = transforms.Compose([ transforms.Resize(img_size), transforms.RandomCrop(img_size, padding=4), transforms.RandomHorizontalFlip(), transforms.ToTensor(), # HWC --> CHW, 0~255->[0.0,1.0] ]) self.transform_test = transforms.Compose([ transforms.Resize(img_size), transforms.ToTensor(), # HWC --> CHW, 0~255->[0.0,1.0] ]) self.data_list = [] self.noise_ratio_list = noise_ratio_list def unpickle(self, file): with open(file, 'rb') as fo: dict = pickle.load(fo, encoding='bytes') return dict def load_data(self, data_root): all_labels = [] all_data = [] if self.split != 'test': file_list = ['data_batch_1', 'data_batch_2', 'data_batch_3', 'data_batch_4', 'data_batch_5'] else: file_list = ['test_batch'] for i, file_name in enumerate(file_list): cur_batch = self.unpickle(os.path.join(data_root, file_name)) data = cur_batch[b'data'] # [10000, 3072(32*32*3)] array labels = cur_batch[b'labels'] # [10000] list all_data.append(data) all_labels = all_labels + labels all_data = np.concatenate(all_data, axis=0) all_data = np.vstack(all_data).reshape(-1, 3, 32, 32) # [num_img, 3, 32, 32], RGB all_data = all_data.transpose((0, 2, 3, 1)) # CHW --> HWC all_data = list(all_data) self.data_list = all_data self.label_list = all_labels self.noise_label_group = [[] for _ in range(len(self.noise_ratio_list))] # [[], [], []] self.major_vote_label = [] # majority vote as the new label set random.seed(100) if self.split != 'test': for p, noise_ratio in enumerate(self.noise_ratio_list): for i in range(len(self.label_list)): flip = False flip_rdn = random.uniform(0., 1.) if flip_rdn < noise_ratio: flip = True if flip: fake_label = random.randint(0, 9) # [0,9] self.noise_label_group[p].append(fake_label) else: self.noise_label_group[p].append(self.label_list[i]) for i in range(len(self.label_list)): cur_list = [self.noise_label_group[0][i], self.noise_label_group[1][i], self.noise_label_group[2][i]] major_label = Counter(cur_list).most_common(1)[0][0] self.major_vote_label.append(major_label) # print(sum(self.label_list), sum(self.noise_label_list)) return self.data_list, self.label_list, self.noise_label_group, self.major_vote_label def __len__(self): return len(self.data_list) def __getitem__(self, index): img = self.data_list[index] # HWC, RGB, array img = Image.fromarray(img) clean_label = self.label_list[index] if self.split == 'train': noise_label_set = [self.noise_label_group[i][index] for i in range(len(self.noise_ratio_list))] major_label = self.major_vote_label[index] if self.is_transform: img = self.transform_train(img) # CHW, RGB,[0,1] else: noise_label_set = [] major_label = [] img = self.transform_test(img) img = ((img - 0.5) / 0.5) # normalize to [-1, 1] return img, noise_label_set, clean_label, major_label if __name__ == '__main__': root = '/srv/beegfs02/scratch/emotion_perception/data/csevim/datasets/cifar10/cifar-10-batches-py' dataset = DataloaderCifar10_multi() dataset.load_data(root)
[ "random.randint", "torchvision.transforms.RandomHorizontalFlip", "random.uniform", "collections.Counter", "torchvision.transforms.ToTensor", "numpy.vstack", "pickle.load", "random.seed", "PIL.Image.fromarray", "torchvision.transforms.RandomCrop", "os.path.join", "numpy.concatenate", "torchvi...
[((1744, 1776), 'numpy.concatenate', 'np.concatenate', (['all_data'], {'axis': '(0)'}), '(all_data, axis=0)\n', (1758, 1776), True, 'import numpy as np\n'), ((2220, 2236), 'random.seed', 'random.seed', (['(100)'], {}), '(100)\n', (2231, 2236), False, 'import random\n'), ((3452, 3472), 'PIL.Image.fromarray', 'Image.fromarray', (['img'], {}), '(img)\n', (3467, 3472), False, 'from PIL import Image\n'), ((1066, 1099), 'pickle.load', 'pickle.load', (['fo'], {'encoding': '"""bytes"""'}), "(fo, encoding='bytes')\n", (1077, 1099), False, 'import pickle\n'), ((520, 547), 'torchvision.transforms.Resize', 'transforms.Resize', (['img_size'], {}), '(img_size)\n', (537, 547), True, 'import torchvision.transforms as transforms\n'), ((561, 603), 'torchvision.transforms.RandomCrop', 'transforms.RandomCrop', (['img_size'], {'padding': '(4)'}), '(img_size, padding=4)\n', (582, 603), True, 'import torchvision.transforms as transforms\n'), ((617, 650), 'torchvision.transforms.RandomHorizontalFlip', 'transforms.RandomHorizontalFlip', ([], {}), '()\n', (648, 650), True, 'import torchvision.transforms as transforms\n'), ((664, 685), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (683, 685), True, 'import torchvision.transforms as transforms\n'), ((794, 821), 'torchvision.transforms.Resize', 'transforms.Resize', (['img_size'], {}), '(img_size)\n', (811, 821), True, 'import torchvision.transforms as transforms\n'), ((835, 856), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (854, 856), True, 'import torchvision.transforms as transforms\n'), ((1482, 1516), 'os.path.join', 'os.path.join', (['data_root', 'file_name'], {}), '(data_root, file_name)\n', (1494, 1516), False, 'import os\n'), ((1796, 1815), 'numpy.vstack', 'np.vstack', (['all_data'], {}), '(all_data)\n', (1805, 1815), True, 'import numpy as np\n'), ((2456, 2480), 'random.uniform', 'random.uniform', (['(0.0)', '(1.0)'], {}), '(0.0, 1.0)\n', (2470, 2480), False, 'import random\n'), ((2628, 2648), 'random.randint', 'random.randint', (['(0)', '(9)'], {}), '(0, 9)\n', (2642, 2648), False, 'import random\n'), ((3029, 3046), 'collections.Counter', 'Counter', (['cur_list'], {}), '(cur_list)\n', (3036, 3046), False, 'from collections import Counter\n')]
import numpy as np from itertools import accumulate def _printer(i, a, m, k, m_a, k_a, z, x): print(f"{a}x%{m}={k}") print(f"x_{i}={x}") print() def solve(a, m, k, i=0, prnt=False, allow_zero=False): """ Solve simple linear conguruence equation Find the least x such that ax=k (mod m) if allow_zero=True 2x%3=0, x=0 if allow_zero=False 2x%3=0, x=3 """ if m > k: if k == a == 0: return k elif k % a == 0: return k // a assert a > 0 k_a = k % a m_a = m % a m_a = m_a if m_a > 0 else a z = a - k_a z = z if z > 0 else a if a == 1: x = k % m if not allow_zero: x = x if x > 0 else k if prnt: print('case 1') _printer(i, a, m, k, m_a, k_a, z, x) return x if m % a == 0: if k % m % a == 0: x = k % m // a if not allow_zero: x = x if x > 0 else k // a if prnt: print('case 2') _printer(i, a, m, k, m_a, k_a, z, x) return x else: print(f"{a}x%{m}={k} - No SOLUTIONS") raise ValueError('No solutions') new_x = solve( a=m_a, m=a, k=z, i=i + 1, prnt=prnt, allow_zero=allow_zero ) x = (k + new_x * m) // a if prnt: print('case 3') _printer(i, a, m, k, m_a, k_a, z, x) return x def get_dynamic_range(P): """ Return the maximum integer numbers that can be uniquely encoded given moduli P >>> get_dynamic_range([7,6,5]) 210 >>> get_dynamic_range([4,3,2]) 12 """ return np.lcm.reduce(P) def encode(n, P): """ Encode an integer decimal number n into corresponding RNS array >>> encode(n=14221, P=[21,19,18,11,10,8,7,5,4]) [4, 9, 1, 9, 1, 5, 4, 1, 1] """ if n >= get_dynamic_range(P): raise ValueError("You cannot encode such a big number with given moduli. Try to increase moduli dynamic range") code = [n % P[-i] for i in range(1, len(P) + 1)][::-1] return code def decode(code, P): """ Decode an RNS representation array into decimal number :param P: list of moduli in order from bigger to smaller [pn, .., p2, p1, p0] >>> decode(code=[5, 3, 1], P=[7,6,5]) 201 """ lcms = np.fromiter(accumulate(P[::-1], np.lcm), int)[::-1] n = code[-1] % P[-1] for i in range(1, len(P)): bottom_p = lcms[-i] per_diff = bottom_p % P[-i - 1] # rev current_next = n % P[-i - 1] wanted_next = code[-i - 1] % P[-i - 1] if wanted_next < current_next: wanted_next = wanted_next + P[-i - 1] distance = wanted_next - current_next distance = distance % P[-i - 1] if distance > 0: bottomp_scroll_count = solve(a=per_diff, m=P[-i - 1], k=distance, allow_zero=True) n = n + bottomp_scroll_count * bottom_p return n def list_encodings(P): """ An utility method to get a list of all numbers n from 0 to get_dynamic_range(P) in RNS representation :param P: moduli, max(moduli) should be less than 32 :return: """ A = '0123456789ABCDEFGHJKLMNOPQRSTXYZ' max_value = get_dynamic_range(P) D = [A[:P[i]] * (max_value // P[i]) for i in range(len(P))] codes = [] for code in zip(*D): codes.append(''.join(code)) return codes if __name__ == '__main__': from doctest import testmod testmod(name="decode", verbose=True)
[ "numpy.lcm.reduce", "itertools.accumulate", "doctest.testmod" ]
[((1699, 1715), 'numpy.lcm.reduce', 'np.lcm.reduce', (['P'], {}), '(P)\n', (1712, 1715), True, 'import numpy as np\n'), ((3531, 3567), 'doctest.testmod', 'testmod', ([], {'name': '"""decode"""', 'verbose': '(True)'}), "(name='decode', verbose=True)\n", (3538, 3567), False, 'from doctest import testmod\n'), ((2387, 2414), 'itertools.accumulate', 'accumulate', (['P[::-1]', 'np.lcm'], {}), '(P[::-1], np.lcm)\n', (2397, 2414), False, 'from itertools import accumulate\n')]
import os.path import random import torchvision.transforms as transforms import torch import numpy as np from data.base_dataset import BaseDataset from data.audio import Audio #from data.image_folder import make_dataset from PIL import Image import progressbar #def make_dataset(dir): # images = [] # assert os.path.isdir(dir), '%s is not a valid directory' % dir # for root, _, fnames in sorted(os.walk(dir)): # for fname in fnames: # if any(fname.endswith(extension) for extension in ['.bin', '.BIN']): # path = os.path.join(root, fname) # images.append(path) # return sorted(images) def make_dataset(dir): images = [] ids = [] assert os.path.isdir(dir), '%s is not a valid directory' % dir for root, _, fnames in sorted(os.walk(dir)): for fname in fnames: if any(fname.endswith(extension) for extension in ['.npy', '.NPY']): #.deepspeech.npy id_str = fname[:-15] #4] i = int(id_str) ids.append(i) ids = sorted(ids) for id in ids: fname=str(id)+'.deepspeech.npy' path = os.path.join(root, fname) images.append(path) return images def make_ids(paths, root_dir): ids = [] for fname in paths: l = fname.rfind('/') id_str = fname[l+1:-15]#4] i = int(id_str) #print(fname, ': ', i) ids.append(i) return ids def make_dataset_ids_png(dir): images = [] ids = [] assert os.path.isdir(dir), '%s is not a valid directory' % dir for root, _, fnames in sorted(os.walk(dir)): for fname in fnames: if any(fname.endswith(extension) for extension in ['.png', '.png']): id_str = fname[:-4] i = int(id_str) ids.append(i) ids = sorted(ids) return ids def load_intrinsics(input_dir): file = open(input_dir+"/intrinsics.txt", "r") intrinsics = [[(float(x) for x in line.split())] for line in file] file.close() intrinsics = list(intrinsics[0][0]) return intrinsics def load_rigids(input_dir): file = open(input_dir+"/rigid.txt", "r") rigid_floats = [[float(x) for x in line.split()] for line in file] # note that it stores 5 lines per matrix (blank line) file.close() all_rigids = [ [rigid_floats[4*idx + 0],rigid_floats[4*idx + 1],rigid_floats[4*idx + 2],rigid_floats[4*idx + 3]] for idx in range(0, len(rigid_floats)//4) ] return all_rigids def load_expressions(input_dir): file = open(input_dir+"/expression.txt", "r") expressions = [[float(x) for x in line.split()] for line in file] file.close() return expressions def load_identity(input_dir): file = open(input_dir+"/identities.txt", "r") identities = [[float(x) for x in line.split()] for line in file] file.close() return identities class MultiFaceAudioEQTmpCachedDataset(BaseDataset): @staticmethod def modify_commandline_options(parser, is_train): return parser def initialize(self, opt): self.opt = opt self.root = opt.dataroot # read dataset file that contains the filenames for the train, val and test lists file = open(self.root+"/dataset.txt", "r") self.filename_train_list, self.filename_val_list, self.filename_test_list = [str(line) for line in file] file.close() if self.filename_train_list[-1] == '\n': self.filename_train_list = self.filename_train_list[:-1] if self.filename_val_list[-1] == '\n': self.filename_val_list = self.filename_val_list[:-1] if self.filename_test_list[-1] == '\n': self.filename_test_list = self.filename_test_list[:-1] # get list of train sequences file = open(self.root+"/" + self.filename_train_list, "r") self.train_sequence_names = [str(line) for line in file] file.close() for i in range(0,len(self.train_sequence_names)): if self.train_sequence_names[i][-1] == '\n': self.train_sequence_names[i] = self.train_sequence_names[i][:-1] # get list of val sequences file = open(self.root+"/" + self.filename_val_list, "r") self.val_sequence_names = [[str(w) for w in line.split()] for line in file] file.close() for i in range(0,len(self.val_sequence_names)): if self.val_sequence_names[i][0][-1] == '\n': self.val_sequence_names[i][0] = self.val_sequence_names[i][0][:-1] if self.val_sequence_names[i][1][-1] == '\n': self.val_sequence_names[i][1] = self.val_sequence_names[i][1][:-1] # get list of test sequences file = open(self.root+"/" + self.filename_test_list, "r") self.test_sequence_names = [[str(w) for w in line.split()] for line in file] if opt.output_audio_expressions: self.test_sequence_names = self.test_sequence_names[0:1] file.close() for i in range(0,len(self.test_sequence_names)): if self.test_sequence_names[i][0][-1] == '\n': self.test_sequence_names[i][0] = self.test_sequence_names[i][0][:-1] if self.test_sequence_names[i][1][-1] == '\n': self.test_sequence_names[i][1] = self.test_sequence_names[i][1][:-1] # print some stats print('filename_train_list:', self.filename_train_list) print('\tnum_seq:', len(self.train_sequence_names)) print('filename_val_list: ', self.filename_val_list) print('\tnum_seq:', len(self.val_sequence_names)) print('filename_test_list: ', self.filename_test_list) print('\tnum_seq:', len(self.test_sequence_names)) opt.train_sequence_names = self.train_sequence_names opt.val_sequence_names = self.val_sequence_names opt.test_sequence_names = self.test_sequence_names # search mapping from val, test to train sequences that are used as targets self.val_sequence_targets = [] for i in range(0,len(self.val_sequence_names)): target_name = self.val_sequence_names[i][1] target_id = -1 for j in range(0,len(self.train_sequence_names)): if self.train_sequence_names[j] == target_name: target_id = j break if target_id == -1: print('Target sequence not in train set! ', target_name) exit() self.val_sequence_targets.append(target_id) self.test_sequence_targets = [] for i in range(0,len(self.test_sequence_names)): target_name = self.test_sequence_names[i][1] target_id = -1 for j in range(0,len(self.train_sequence_names)): if self.train_sequence_names[j] == target_name: target_id = j break if target_id == -1: print('Target sequence not in train set! ', target_name) exit() self.test_sequence_targets.append(target_id) print('test: ', self.test_sequence_names[i]) print('\t target:', target_id) # store len values opt.nTrainObjects = len(self.train_sequence_names) opt.nValObjects = len(self.val_sequence_names) opt.nTestObjects = len(self.test_sequence_names) ################################################ ################################################ ################################################ # prepare dataloader paths / data self.audio_feature_dir = [] self.image_dir = [] self.uvs_dir = [] self.audio_ids = [] self.image_ids = [] self.intrinsics = [] self.extrinsics = [] self.expressions = [] self.identities = [] self.target_id = [] self.n_frames_total = 0 if opt.phase == 'train': self.sequence_names = self.train_sequence_names for i in range(0,len(self.train_sequence_names)): dataroot = os.path.join(opt.dataroot, self.train_sequence_names[i]) audio_feature_dir = os.path.join(opt.dataroot, self.train_sequence_names[i], 'audio_feature') image_dir = os.path.join(opt.dataroot, self.train_sequence_names[i], 'images') uvs_dir = os.path.join(opt.dataroot, self.train_sequence_names[i], 'uvs') print('load train sequence:', self.train_sequence_names[i]) print('\tidentity_dir:', dataroot) print('\taudio_feature_dir:', audio_feature_dir) print('\timage_dir:', image_dir) print('\tuvs_dir:', uvs_dir) audio_ids = make_ids(make_dataset(audio_feature_dir), dataroot) image_ids = make_dataset_ids_png(image_dir) # [-1] * len(audio_ids) #make_ids(make_dataset(image_dir), dataroot) intrinsics = load_intrinsics(dataroot) extrinsics = load_rigids(dataroot) expressions = load_expressions(dataroot) identity = load_identity(dataroot) min_len = min(len(audio_ids), len(image_ids), len(extrinsics), len(expressions)) self.audio_feature_dir.append(audio_feature_dir) self.image_dir.append(image_dir) self.uvs_dir.append(uvs_dir) self.audio_ids.append(audio_ids[:min_len]) self.image_ids.append(image_ids[:min_len]) self.intrinsics.append(intrinsics) self.extrinsics.append(extrinsics[:min_len]) self.expressions.append(expressions[:min_len]) self.identities.append(identity[:min_len]) self.target_id.append(i) self.n_frames_total += min_len elif opt.phase == 'val': for i in range(0,len(self.val_sequence_names)): target_id = self.val_sequence_targets[i] dataroot = os.path.join(opt.dataroot, self.train_sequence_names[target_id]) audio_feature_dir = os.path.join(opt.dataroot, self.val_sequence_names[i][0], 'audio_feature') image_dir = os.path.join(opt.dataroot, self.train_sequence_names[target_id], 'images') uvs_dir = os.path.join(opt.dataroot, self.train_sequence_names[target_id], 'uvs') print('load val sequence:', self.val_sequence_names[i]) print('\tidentity_dir:', dataroot) print('\taudio_feature_dir:', audio_feature_dir) print('\timage_dir:', image_dir) print('\tuvs_dir:', uvs_dir) audio_ids = make_ids(make_dataset(audio_feature_dir), os.path.join(opt.dataroot, self.val_sequence_names[i][0])) image_ids = make_dataset_ids_png(image_dir) # [-1] * len(audio_ids) #make_ids(make_dataset(image_dir), dataroot) intrinsics = load_intrinsics(dataroot) extrinsics = load_rigids(dataroot) expressions = load_expressions(os.path.join(opt.dataroot, self.val_sequence_names[i][0])) identity = load_identity(dataroot) min_len = min(len(audio_ids), len(image_ids), len(extrinsics), len(expressions)) self.audio_feature_dir.append(audio_feature_dir) self.image_dir.append(image_dir) self.uvs_dir.append(uvs_dir) self.audio_ids.append(audio_ids[:min_len]) self.image_ids.append(image_ids[:min_len]) self.intrinsics.append(intrinsics) self.extrinsics.append(extrinsics[:min_len]) self.expressions.append(expressions[:min_len]) self.identities.append(identity[:min_len]) self.target_id.append(target_id) self.n_frames_total += min_len else: # test for i in range(0,len(self.test_sequence_names)): target_id = self.test_sequence_targets[i] dataroot = os.path.join(opt.dataroot, self.train_sequence_names[target_id]) audio_feature_dir = os.path.join(opt.dataroot, self.test_sequence_names[i][0], 'audio_feature') image_dir = os.path.join(opt.dataroot, self.train_sequence_names[target_id], 'images') uvs_dir = os.path.join(opt.dataroot, self.train_sequence_names[target_id], 'uvs') print('load test sequence:', self.test_sequence_names[i]) print('\tidentity_dir:', dataroot) print('\taudio_feature_dir:', audio_feature_dir) print('\timage_dir:', image_dir) print('\tuvs_dir:', uvs_dir) audio_ids = make_ids(make_dataset(audio_feature_dir), os.path.join(opt.dataroot, self.test_sequence_names[i][0])) image_ids = make_dataset_ids_png(image_dir) # [-1] * len(audio_ids) #make_ids(make_dataset(image_dir), dataroot) intrinsics = load_intrinsics(dataroot) extrinsics = load_rigids(dataroot) expressions = load_expressions(os.path.join(opt.dataroot, self.test_sequence_names[i][0])) identity = load_identity(dataroot) min_len = min(len(audio_ids), len(image_ids), len(extrinsics), len(expressions)) self.audio_feature_dir.append(audio_feature_dir) self.image_dir.append(image_dir) self.uvs_dir.append(uvs_dir) self.audio_ids.append(audio_ids[:min_len]) self.image_ids.append(image_ids[:min_len]) self.intrinsics.append(intrinsics) self.extrinsics.append(extrinsics[:min_len]) self.expressions.append(expressions[:min_len]) self.identities.append(identity[:min_len]) self.target_id.append(target_id) self.n_frames_total += min_len print('frames_total:', self.n_frames_total) #global_target_ids = [] #for i in range(0,len(self.audio_ids)): # for j in range(0,len(self.audio_ids[i])): # global_target_ids.append(self.target_id[i]) #global_target_ids=np.array(global_target_ids) #self.weights = np.where(global_target_ids==2, 1.0 * np.ones((self.n_frames_total)), 0.01 * np.ones((self.n_frames_total)) ) self.weights = [] for i in range(0,len(self.audio_ids)): l = len(self.audio_ids[i]) for j in range(0,l): self.weights.append(1.0 / l) self.weights = np.array(self.weights) assert(opt.resize_or_crop == 'resize_and_crop') # mapping global to internal self.mapping_global2internal = [] self.mapping_global2internal_offset = [] self.dsf = [] offset = 0 with progressbar.ProgressBar(max_value=self.n_frames_total) as bar: for i in range(0,len(self.audio_ids)): l = len(self.audio_ids[i]) dsf_seq = [] for k in range(0,l): self.mapping_global2internal.append(i) self.mapping_global2internal_offset.append(offset) dsf_fname = os.path.join(self.audio_feature_dir[i], str(self.audio_ids[i][k]) + '.deepspeech.npy') feature_array = np.load(dsf_fname) dsf_np = np.resize(feature_array, (16,29,1)) dsf_seq.append(dsf_np.astype(np.float32)) bar.update(offset + k) self.dsf.append(dsf_seq) offset += l def getSampleWeights(self): return self.weights def getitem(self, global_index): # select sequence internal_sequence_id = self.mapping_global2internal[global_index] sum_frames = self.mapping_global2internal_offset[global_index] # select frame from sequence index = (global_index-sum_frames) % len(self.audio_ids[internal_sequence_id]) # get data ids audio_id = self.audio_ids[internal_sequence_id][index] image_id = self.image_ids[internal_sequence_id][index] #print('GET ITEM: ', index) #img_path = self.frame_paths[sequence_id][index] # intrinsics and extrinsics intrinsics = self.intrinsics[internal_sequence_id] extrinsics = self.extrinsics[internal_sequence_id][image_id] # expressions expressions = np.asarray(self.expressions[internal_sequence_id][audio_id], dtype=np.float32) #print('expressions:', expressions.shape) expressions[32] *= 0.0 # remove eye brow movements expressions[41] *= 0.0 # remove eye brow movements expressions[71:75] *= 0.0 # remove eye brow movements expressions = torch.tensor(expressions) # identity identity = torch.tensor(self.identities[internal_sequence_id][image_id]) target_id = self.target_id[internal_sequence_id] # sequence id refers to the target sequence (of the training corpus) # load deepspeech feature #print('audio_id', audio_id) dsf_fname = os.path.join(self.audio_feature_dir[internal_sequence_id], str(audio_id) + '.deepspeech.npy') dsf_np = self.dsf[internal_sequence_id][index] dsf = transforms.ToTensor()(dsf_np) # load sequence data if necessary if self.opt.look_ahead:# use prev and following frame infos r = self.opt.seq_len//2 for i in range(1,r): # prev frames index_seq = index - i if index_seq < 0: index_seq = 0 dsf_np = self.dsf[internal_sequence_id][index_seq] dsf_seq = transforms.ToTensor()(dsf_np) # 1 x 16 x 29 dsf = torch.cat([dsf_seq, dsf], 0) # seq_len x 16 x 29 # note the ordering [old ... current] for i in range(1,self.opt.seq_len - r + 1): # following frames index_seq = index + i max_idx = len(self.audio_ids[internal_sequence_id])-1 if index_seq > max_idx: index_seq = max_idx dsf_np = self.dsf[internal_sequence_id][index_seq] dsf_seq = transforms.ToTensor()(dsf_np) # 1 x 16 x 29 dsf = torch.cat([dsf, dsf_seq], 0) # seq_len x 16 x 29 # note the ordering [old ... current ... future] else: for i in range(1,self.opt.seq_len): index_seq = index - i if index_seq < 0: index_seq = 0 dsf_np = self.dsf[internal_sequence_id][index_seq] dsf_seq = transforms.ToTensor()(dsf_np) # 1 x 16 x 29 dsf = torch.cat([dsf_seq, dsf], 0) # seq_len x 16 x 29 # note the ordering [old ... current] #weight = 1.0 / len(self.audio_feature_dir[internal_sequence_id]) weight = self.weights[global_index] return {'paths': dsf_fname, #img_path, 'intrinsics': np.array(intrinsics), 'extrinsics': np.array(extrinsics), 'expressions': expressions, 'identity': identity, 'audio_deepspeech': dsf, # deepspeech feature 'target_id':target_id, 'internal_id':internal_sequence_id, 'weight': np.array([weight]).astype(np.float32)} def __getitem__(self, global_index): # select frame from sequence index = global_index current = self.getitem(index) prv = self.getitem(max(index-1, 0)) nxt = self.getitem(min(index+1, self.n_frames_total-1)) return { 'paths': current['paths'], #img_path, 'target_id': current['target_id'], 'internal_id': current['internal_id'], 'weight': current['weight'], 'identity': current['identity'], 'intrinsics': current['intrinsics'], 'extrinsics': current['extrinsics'], 'expressions': current['expressions'], 'audio_deepspeech': current['audio_deepspeech'], 'extrinsics_prv': prv['extrinsics'], 'expressions_prv': prv['expressions'], 'audio_deepspeech_prv': prv['audio_deepspeech'], 'extrinsics_nxt': nxt['extrinsics'], 'expressions_nxt': nxt['expressions'], 'audio_deepspeech_nxt': nxt['audio_deepspeech'], } def __len__(self): return self.n_frames_total #len(self.frame_paths[0]) def name(self): return 'MultiFaceAudioEQTmpCachedDataset'
[ "numpy.load", "numpy.resize", "numpy.asarray", "torch.cat", "numpy.array", "progressbar.ProgressBar", "torch.tensor", "torchvision.transforms.ToTensor" ]
[((14669, 14691), 'numpy.array', 'np.array', (['self.weights'], {}), '(self.weights)\n', (14677, 14691), True, 'import numpy as np\n'), ((16559, 16637), 'numpy.asarray', 'np.asarray', (['self.expressions[internal_sequence_id][audio_id]'], {'dtype': 'np.float32'}), '(self.expressions[internal_sequence_id][audio_id], dtype=np.float32)\n', (16569, 16637), True, 'import numpy as np\n'), ((16914, 16939), 'torch.tensor', 'torch.tensor', (['expressions'], {}), '(expressions)\n', (16926, 16939), False, 'import torch\n'), ((16979, 17040), 'torch.tensor', 'torch.tensor', (['self.identities[internal_sequence_id][image_id]'], {}), '(self.identities[internal_sequence_id][image_id])\n', (16991, 17040), False, 'import torch\n'), ((14932, 14986), 'progressbar.ProgressBar', 'progressbar.ProgressBar', ([], {'max_value': 'self.n_frames_total'}), '(max_value=self.n_frames_total)\n', (14955, 14986), False, 'import progressbar\n'), ((17435, 17456), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (17454, 17456), True, 'import torchvision.transforms as transforms\n'), ((19134, 19154), 'numpy.array', 'np.array', (['intrinsics'], {}), '(intrinsics)\n', (19142, 19154), True, 'import numpy as np\n'), ((19186, 19206), 'numpy.array', 'np.array', (['extrinsics'], {}), '(extrinsics)\n', (19194, 19206), True, 'import numpy as np\n'), ((17904, 17932), 'torch.cat', 'torch.cat', (['[dsf_seq, dsf]', '(0)'], {}), '([dsf_seq, dsf], 0)\n', (17913, 17932), False, 'import torch\n'), ((18411, 18439), 'torch.cat', 'torch.cat', (['[dsf, dsf_seq]', '(0)'], {}), '([dsf, dsf_seq], 0)\n', (18420, 18439), False, 'import torch\n'), ((18833, 18861), 'torch.cat', 'torch.cat', (['[dsf_seq, dsf]', '(0)'], {}), '([dsf_seq, dsf], 0)\n', (18842, 18861), False, 'import torch\n'), ((15450, 15468), 'numpy.load', 'np.load', (['dsf_fname'], {}), '(dsf_fname)\n', (15457, 15468), True, 'import numpy as np\n'), ((15498, 15535), 'numpy.resize', 'np.resize', (['feature_array', '(16, 29, 1)'], {}), '(feature_array, (16, 29, 1))\n', (15507, 15535), True, 'import numpy as np\n'), ((17838, 17859), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (17857, 17859), True, 'import torchvision.transforms as transforms\n'), ((18345, 18366), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (18364, 18366), True, 'import torchvision.transforms as transforms\n'), ((18767, 18788), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (18786, 18788), True, 'import torchvision.transforms as transforms\n'), ((19486, 19504), 'numpy.array', 'np.array', (['[weight]'], {}), '([weight])\n', (19494, 19504), True, 'import numpy as np\n')]
#!/usr/bin/env python3 #------------------------------------------------------------------------------ # LDO MODEL WRAPPER # IDEA & POSH # Date: 12/21/2018 #------------------------------------------------------------------------------ import sys import getopt import math import subprocess as sp import fileinput import re import os import shutil import numpy as np import matplotlib.pyplot as plt import argparse import json import glob import datetime #------------------------------------------------------------------------------ # Get the folder/file paths #------------------------------------------------------------------------------ genDir = os.path.join(os.path.dirname(os.path.relpath(__file__)),"../") head_tail_0 = os.path.split(os.path.abspath(genDir)) head_tail_1 = os.path.split(head_tail_0[0]) pvtGenDir = os.path.relpath(os.path.join(genDir, '../../', 'private', head_tail_1[1], head_tail_0[1])) flowDir = os.path.join(pvtGenDir, './flow') extDir = os.path.join(pvtGenDir, './extraction') simDir = os.path.join(pvtGenDir, './simulation') pyModulesDir = os.path.join(pvtGenDir, './pymodules') #------------------------------------------------------------------------------ # Parse the command line arguments #------------------------------------------------------------------------------ print('#---------------------------------------------------------------------') print('# Parsing command line arguments...') print('#---------------------------------------------------------------------') print(sys.argv) parser = argparse.ArgumentParser(description='Digital LDO model generator') parser.add_argument('--platform', required=True, help='PDK/process kit for cadre flow (.e.g tsmc16)') parser.add_argument('--clean', action='store_true', help='To clean the workspace.') args = parser.parse_args() if args.platform != 'tsmc65lp' and args.platform != 'gfbicmos8hp' and \ args.platform != 'gf12lp': print('Error: Only supports TSMC65lp, GFBiCmos8hp and GF12LP kits ' + \ 'as of now.') sys.exit(1) if not os.path.isdir(pvtGenDir): print('Error: Private directory does not exist. \n ' + \ 'Model generation is only supported in \'macro\' and \'full\' modes.') sys.exit(1) else: sys.path.append(pyModulesDir) import clean_up as clc import cfg_digital_flow as cfg import run_digital_flow as rdf import run_pex_flow as pex import run_sim_flow as sim # Load json config file print('Loading platform_config file...') try: with open(genDir + '../../config/platform_config.json') as file: jsonConfig = json.load(file) except ValueError as e: print('Error: platform_config.json file has an invalid format. %s' % str(e)) sys.exit(1) # Define the config & design variables mFile = '' simTool = '' extTool = '' netlistTool = '' calibreRulesDir = '' # Define the internal variables used ptCell = 'PT_UNIT_CELL' # Get the config variable from platfom config file simTool = jsonConfig['simTool'] if simTool != 'hspice' and simTool != 'finesim': print('Error: Supported simulators are \'hspice\' or \'finesim\' as of now') sys.exit(1) extTool = jsonConfig['extractionTool'] if extTool != 'calibre': print('Error: Only support calibre extraction now') sys.exit(1) netlistTool = jsonConfig['netlistTool'] if netlistTool != 'calibredrv': print('Error: Only support calibredrv netlist tool now') sys.exit(1) try: platformConfig = jsonConfig['platforms'][args.platform] except KeyError as e: print('Error: \"' + args.platform + '\" config not available') sys.exit(1) mFile = platformConfig['model_lib'] + '/ldoModel.json' calibreRulesDir = platformConfig['calibreRules'] print('Run Config:') print('Aux Lib - \"' + platformConfig['aux_lib'] + '\"') print('PT Cell Used - \"' + ptCell + '\"') print('Model File - \"' + mFile + '\"') print('Netlisting Tool - \"' + netlistTool + '\"') print('Extraction Tool - \"' + extTool + '\"') print('Simulation Tool - \"' + simTool + '\"') print('Calibre Rules Directory - \"' + calibreRulesDir + '\"') print('Digital Flow Directory - \"' + flowDir + '\"') print('Extraction Directory - \"' + extDir + '\"') print('Simulation Directory - \"' + simDir + '\"') #------------------------------------------------------------------------------ # Clean the workspace #------------------------------------------------------------------------------ print('#---------------------------------------------------------------------') print('# Cleaning the workspace...') print('#---------------------------------------------------------------------') clc.wrkspace_clean(flowDir, extDir, simDir) if (args.clean): print('Workspace clean done. Exiting the flow.') sys.exit(0) try: os.mkdir(flowDir + '/src') except OSError: print('Unable to create the "src" directory in "flow" folder') try: os.mkdir(extDir + '/layout') except OSError: print('Unable to create the "layout" directory in "extraction" folder') try: os.mkdir(extDir + '/run') except OSError: print('Unable to create the "run" directory in "extraction" folder') try: os.mkdir(extDir + '/sch') except OSError: print('Unable to create the "sch" directory in "extraction" folder') try: os.mkdir(simDir + '/run') except OSError: print('Unable to create the "run" directory in "simulation" folder') #------------------------------------------------------------------------------ # Configure Synth and APR scripts #------------------------------------------------------------------------------ print('#---------------------------------------------------------------------') print('# Configuring Synth and APR scripts...') print('#---------------------------------------------------------------------') cfg.ldo_model_dg_flow_cfg(args.platform, platformConfig['nominal_voltage'], \ platformConfig['aux_lib'], flowDir) #------------------------------------------------------------------------------ # Initialize the local variables #------------------------------------------------------------------------------ results = [] areaValues = [] numIter = 0 startDT = datetime.datetime.now() for arrSize in [3, 4, 5, 6, 7, 8, 9, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, \ 110, 120, 130, 140, 150, 160, 170, 180, 190, 200, 210, 220]: print('#---------------------------------------------------------------' + \ '------') print('# Running the sim loop for array size = %s...' % arrSize) print('#---------------------------------------------------------------' + \ '------') #--------------------------------------------------------------------------- # Change the design name & Generate the Behavioral Verilog #--------------------------------------------------------------------------- # Get the design name designName = 'LDO_' + str(arrSize) # Generate behavioral verilog of the testbench print('# Array Size %s - Generating the Behavioral Verilog...' % arrSize) p = sp.Popen(['python',genDir+'./tools/ldo_model_verilog_gen.py','-a', \ ptCell,str(arrSize)]) p.wait() print('# Array Size %s - Behavioral Verilog Generated' % arrSize) #--------------------------------------------------------------------------- # Update design name & source file list in the digital flow directory #--------------------------------------------------------------------------- # Update the design name with open(flowDir + '/include.mk', 'r') as file: filedata = file.read() filedata = re.sub(r'export DESIGN_NAME :=.*', r'export DESIGN_NAME := ' + \ designName, filedata) with open(flowDir + '/include.mk', 'w') as file: file.write(filedata) # Update the verilog file list for Synthesis with open(flowDir + '/scripts/dc/dc.filelist.tcl', 'r') as file: filedata = file.read() filedata = re.sub(r'append MAIN_SOURCE_FILE.*', r'append ' + \ 'MAIN_SOURCE_FILE \"' + designName + '.v\"', filedata) with open(flowDir + '/scripts/dc/dc.filelist.tcl', 'w') as file: file.write(filedata) #--------------------------------------------------------------------------- # Run Synthesis and APR #--------------------------------------------------------------------------- print('# Array Size %s - Running Synthesis and APR...' % arrSize) designArea = rdf.run_synth_n_apr(args.platform, designName, flowDir) p = sp.Popen(['cp',flowDir+'/reports/innovus/'+designName+'.main.htm.ascii',simDir+'/run/']) print('# Array Size %s - Synthesis and APR finished' % arrSize) #--------------------------------------------------------------------------- # Generate post PEX netlist #--------------------------------------------------------------------------- print('# Array Size %s - Generating post PEX netist...' % arrSize) pex.gen_post_pex_netlist(args.platform, designName, flowDir, extDir, \ calibreRulesDir) print('# Array Size %s - Post PEX netlist Generated' % arrSize) #--------------------------------------------------------------------------- # Run Hspice Sims #--------------------------------------------------------------------------- print('# Array Size %s - Running Hspice Sims...' % arrSize) sim.run_post_pex_model_imax_worst(args.platform, \ platformConfig['hspiceModels'], \ designName, extDir, simDir, \ simTool, arrSize) print('# Array Size %s - Hspice Sim Completed' % arrSize) #--------------------------------------------------------------------------- # Parse the Sim Results #--------------------------------------------------------------------------- print('# Array Size %s - Parsing the Sim Results...' % arrSize) simResult = open(simDir+'/run/'+designName+'.mt0', 'r') numSkipLines = 3 numLine = 1 numDataLine = 0 for line in simResult.readlines(): if (numLine > numSkipLines): if ((numLine % 2) == 1) or (simTool == 'finesim'): words = line.split() if numIter == 0: results.append([float(words[1])]) results[numDataLine].append([int(arrSize), float(words[2])]) numDataLine = numDataLine + 1 numLine = numLine + 1 simResult.close() numIter = numIter + 1 results.sort(key=lambda x: x[0]) areaValues.append([int(arrSize), float(designArea)]) print('# Array Size %s - Sim Results Parsed' % arrSize) #------------------------------------------------------------------------------ # Generate the Model File #------------------------------------------------------------------------------ print('#---------------------------------------------------------------------') print('# Generating the Model File...') print('#---------------------------------------------------------------------') jsonModel = {} jsonModel['Iload,max'] = {} jsonModel['area'] = [] jsonModel['power'] = {} labels = [] # Iload,max Model for i in range(len(results)): jsonModel['Iload,max'][results[i][0]] = [] x = [item[1] for item in results[i][1:]] y = [item[0] for item in results[i][1:]] xt = [float(1000000)*item for item in x] plt.semilogx(y, xt) labels.append('Vin = %s' % results[i][0]) z = np.polyfit(x,y,8) for item in z: jsonModel['Iload,max'][results[i][0]].append(item) # Area Model print(areaValues) x = [item[0] for item in areaValues[0:]] y = [item[1] for item in areaValues[0:]] z = np.polyfit(x,y,8) for item in z: jsonModel['area'].append(item) # Dump the model into a json file with open(mFile, 'w') as file: json.dump(jsonModel, file, indent=2) endDT = datetime.datetime.now() print('Start Time - ' + str(startDT)) print('End Time - ' + str(endDT)) plt.xlim(results[0][1][0], results[0][numIter][0]) plt.legend(labels, loc='upper left') plt.xlabel('No. of unit cells in parallel') plt.ylabel('Id (uA)') plt.title('Id vs Array size') #plt.show() #------------------------------------------------------------------------------ # Print the Finish message #------------------------------------------------------------------------------ print('#---------------------------------------------------------------------') print('Script Finished - Model File saved as \"' + mFile +'\"') print('#---------------------------------------------------------------------')
[ "matplotlib.pyplot.title", "os.mkdir", "argparse.ArgumentParser", "numpy.polyfit", "run_digital_flow.run_synth_n_apr", "os.path.join", "matplotlib.pyplot.xlabel", "sys.path.append", "os.path.abspath", "run_sim_flow.run_post_pex_model_imax_worst", "datetime.datetime.now", "re.sub", "json.dump...
[((804, 833), 'os.path.split', 'os.path.split', (['head_tail_0[0]'], {}), '(head_tail_0[0])\n', (817, 833), False, 'import os\n'), ((963, 996), 'os.path.join', 'os.path.join', (['pvtGenDir', '"""./flow"""'], {}), "(pvtGenDir, './flow')\n", (975, 996), False, 'import os\n'), ((1016, 1055), 'os.path.join', 'os.path.join', (['pvtGenDir', '"""./extraction"""'], {}), "(pvtGenDir, './extraction')\n", (1028, 1055), False, 'import os\n'), ((1075, 1114), 'os.path.join', 'os.path.join', (['pvtGenDir', '"""./simulation"""'], {}), "(pvtGenDir, './simulation')\n", (1087, 1114), False, 'import os\n'), ((1134, 1172), 'os.path.join', 'os.path.join', (['pvtGenDir', '"""./pymodules"""'], {}), "(pvtGenDir, './pymodules')\n", (1146, 1172), False, 'import os\n'), ((1600, 1666), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Digital LDO model generator"""'}), "(description='Digital LDO model generator')\n", (1623, 1666), False, 'import argparse\n'), ((4711, 4754), 'clean_up.wrkspace_clean', 'clc.wrkspace_clean', (['flowDir', 'extDir', 'simDir'], {}), '(flowDir, extDir, simDir)\n', (4729, 4754), True, 'import clean_up as clc\n'), ((5858, 5973), 'cfg_digital_flow.ldo_model_dg_flow_cfg', 'cfg.ldo_model_dg_flow_cfg', (['args.platform', "platformConfig['nominal_voltage']", "platformConfig['aux_lib']", 'flowDir'], {}), "(args.platform, platformConfig['nominal_voltage'],\n platformConfig['aux_lib'], flowDir)\n", (5883, 5973), True, 'import cfg_digital_flow as cfg\n'), ((6243, 6266), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (6264, 6266), False, 'import datetime\n'), ((11674, 11693), 'numpy.polyfit', 'np.polyfit', (['x', 'y', '(8)'], {}), '(x, y, 8)\n', (11684, 11693), True, 'import numpy as np\n'), ((11856, 11879), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (11877, 11879), False, 'import datetime\n'), ((11953, 12003), 'matplotlib.pyplot.xlim', 'plt.xlim', (['results[0][1][0]', 'results[0][numIter][0]'], {}), '(results[0][1][0], results[0][numIter][0])\n', (11961, 12003), True, 'import matplotlib.pyplot as plt\n'), ((12004, 12040), 'matplotlib.pyplot.legend', 'plt.legend', (['labels'], {'loc': '"""upper left"""'}), "(labels, loc='upper left')\n", (12014, 12040), True, 'import matplotlib.pyplot as plt\n'), ((12041, 12084), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""No. of unit cells in parallel"""'], {}), "('No. of unit cells in parallel')\n", (12051, 12084), True, 'import matplotlib.pyplot as plt\n'), ((12085, 12106), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Id (uA)"""'], {}), "('Id (uA)')\n", (12095, 12106), True, 'import matplotlib.pyplot as plt\n'), ((12107, 12136), 'matplotlib.pyplot.title', 'plt.title', (['"""Id vs Array size"""'], {}), "('Id vs Array size')\n", (12116, 12136), True, 'import matplotlib.pyplot as plt\n'), ((760, 783), 'os.path.abspath', 'os.path.abspath', (['genDir'], {}), '(genDir)\n', (775, 783), False, 'import os\n'), ((869, 942), 'os.path.join', 'os.path.join', (['genDir', '"""../../"""', '"""private"""', 'head_tail_1[1]', 'head_tail_0[1]'], {}), "(genDir, '../../', 'private', head_tail_1[1], head_tail_0[1])\n", (881, 942), False, 'import os\n'), ((2124, 2135), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (2132, 2135), False, 'import sys\n'), ((2144, 2168), 'os.path.isdir', 'os.path.isdir', (['pvtGenDir'], {}), '(pvtGenDir)\n', (2157, 2168), False, 'import os\n'), ((2322, 2333), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (2330, 2333), False, 'import sys\n'), ((2343, 2372), 'sys.path.append', 'sys.path.append', (['pyModulesDir'], {}), '(pyModulesDir)\n', (2358, 2372), False, 'import sys\n'), ((3234, 3245), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (3242, 3245), False, 'import sys\n'), ((3369, 3380), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (3377, 3380), False, 'import sys\n'), ((3517, 3528), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (3525, 3528), False, 'import sys\n'), ((4827, 4838), 'sys.exit', 'sys.exit', (['(0)'], {}), '(0)\n', (4835, 4838), False, 'import sys\n'), ((4848, 4874), 'os.mkdir', 'os.mkdir', (["(flowDir + '/src')"], {}), "(flowDir + '/src')\n", (4856, 4874), False, 'import os\n'), ((4966, 4994), 'os.mkdir', 'os.mkdir', (["(extDir + '/layout')"], {}), "(extDir + '/layout')\n", (4974, 4994), False, 'import os\n'), ((5095, 5120), 'os.mkdir', 'os.mkdir', (["(extDir + '/run')"], {}), "(extDir + '/run')\n", (5103, 5120), False, 'import os\n'), ((5218, 5243), 'os.mkdir', 'os.mkdir', (["(extDir + '/sch')"], {}), "(extDir + '/sch')\n", (5226, 5243), False, 'import os\n'), ((5341, 5366), 'os.mkdir', 'os.mkdir', (["(simDir + '/run')"], {}), "(simDir + '/run')\n", (5349, 5366), False, 'import os\n'), ((7656, 7742), 're.sub', 're.sub', (['"""export DESIGN_NAME :=.*"""', "('export DESIGN_NAME := ' + designName)", 'filedata'], {}), "('export DESIGN_NAME :=.*', 'export DESIGN_NAME := ' + designName,\n filedata)\n", (7662, 7742), False, 'import re\n'), ((8003, 8107), 're.sub', 're.sub', (['"""append MAIN_SOURCE_FILE.*"""', '(\'append \' + \'MAIN_SOURCE_FILE "\' + designName + \'.v"\')', 'filedata'], {}), '(\'append MAIN_SOURCE_FILE.*\', \'append \' + \'MAIN_SOURCE_FILE "\' +\n designName + \'.v"\', filedata)\n', (8009, 8107), False, 'import re\n'), ((8499, 8554), 'run_digital_flow.run_synth_n_apr', 'rdf.run_synth_n_apr', (['args.platform', 'designName', 'flowDir'], {}), '(args.platform, designName, flowDir)\n', (8518, 8554), True, 'import run_digital_flow as rdf\n'), ((8562, 8664), 'subprocess.Popen', 'sp.Popen', (["['cp', flowDir + '/reports/innovus/' + designName + '.main.htm.ascii', \n simDir + '/run/']"], {}), "(['cp', flowDir + '/reports/innovus/' + designName +\n '.main.htm.ascii', simDir + '/run/'])\n", (8570, 8664), True, 'import subprocess as sp\n'), ((8983, 9072), 'run_pex_flow.gen_post_pex_netlist', 'pex.gen_post_pex_netlist', (['args.platform', 'designName', 'flowDir', 'extDir', 'calibreRulesDir'], {}), '(args.platform, designName, flowDir, extDir,\n calibreRulesDir)\n', (9007, 9072), True, 'import run_pex_flow as pex\n'), ((9414, 9545), 'run_sim_flow.run_post_pex_model_imax_worst', 'sim.run_post_pex_model_imax_worst', (['args.platform', "platformConfig['hspiceModels']", 'designName', 'extDir', 'simDir', 'simTool', 'arrSize'], {}), "(args.platform, platformConfig[\n 'hspiceModels'], designName, extDir, simDir, simTool, arrSize)\n", (9447, 9545), True, 'import run_sim_flow as sim\n'), ((11391, 11410), 'matplotlib.pyplot.semilogx', 'plt.semilogx', (['y', 'xt'], {}), '(y, xt)\n', (11403, 11410), True, 'import matplotlib.pyplot as plt\n'), ((11463, 11482), 'numpy.polyfit', 'np.polyfit', (['x', 'y', '(8)'], {}), '(x, y, 8)\n', (11473, 11482), True, 'import numpy as np\n'), ((11810, 11846), 'json.dump', 'json.dump', (['jsonModel', 'file'], {'indent': '(2)'}), '(jsonModel, file, indent=2)\n', (11819, 11846), False, 'import json\n'), ((693, 718), 'os.path.relpath', 'os.path.relpath', (['__file__'], {}), '(__file__)\n', (708, 718), False, 'import os\n'), ((2706, 2721), 'json.load', 'json.load', (['file'], {}), '(file)\n', (2715, 2721), False, 'import json\n'), ((2829, 2840), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (2837, 2840), False, 'import sys\n'), ((3685, 3696), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (3693, 3696), False, 'import sys\n')]
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Thu Feb 14 07:48:06 2019 @author: thomas """ import numpy as np import matplotlib.pyplot as plt # function to create the square pulse def square(t,T): f=(t<=T/2.0) * (t>=-T/2.0) return(f) font = {'family' : 'serif', 'weight' : 'normal', 'size' : 16} plt.rc('font', **font) # time axis T=4; Tmax=30.0 N=1024 n=np.arange(-N/2.0,N/2.0,1) Dt=2*Tmax/N t = n*Dt # frequency axis Df=1.0/2.0/Tmax f=n*Df # signal in the time domain x=square(t,T) # signal in the frequency domain X=Dt*np.fft.fftshift(np.fft.fft(np.fft.fftshift(x))) # Analytical expression for the spectrum X2=T*np.sinc(f*T) # Plot results plt.figure(1) plt.xlabel('$t$ [msec]',**font) plt.ylabel('$x(t)$ [V]') plt.tight_layout() plt.plot(t,x) plt.savefig('square2.png') plt.figure(2) plt.plot(t,np.real(X2),t,X,'o') plt.xlim(-3,3) plt.legend(['analytical','numerical']) plt.xlabel('$f$ [kHz]',**font) plt.ylabel('$X(f)$') plt.tight_layout() plt.savefig('fftcomp.png')
[ "matplotlib.pyplot.xlim", "matplotlib.pyplot.plot", "matplotlib.pyplot.legend", "matplotlib.pyplot.figure", "numpy.sinc", "numpy.arange", "matplotlib.pyplot.rc", "numpy.real", "numpy.fft.fftshift", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.tight_layout", "mat...
[((355, 377), 'matplotlib.pyplot.rc', 'plt.rc', (['"""font"""'], {}), "('font', **font)\n", (361, 377), True, 'import matplotlib.pyplot as plt\n'), ((415, 446), 'numpy.arange', 'np.arange', (['(-N / 2.0)', '(N / 2.0)', '(1)'], {}), '(-N / 2.0, N / 2.0, 1)\n', (424, 446), True, 'import numpy as np\n'), ((709, 722), 'matplotlib.pyplot.figure', 'plt.figure', (['(1)'], {}), '(1)\n', (719, 722), True, 'import matplotlib.pyplot as plt\n'), ((723, 755), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""$t$ [msec]"""'], {}), "('$t$ [msec]', **font)\n", (733, 755), True, 'import matplotlib.pyplot as plt\n'), ((755, 779), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""$x(t)$ [V]"""'], {}), "('$x(t)$ [V]')\n", (765, 779), True, 'import matplotlib.pyplot as plt\n'), ((780, 798), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (796, 798), True, 'import matplotlib.pyplot as plt\n'), ((799, 813), 'matplotlib.pyplot.plot', 'plt.plot', (['t', 'x'], {}), '(t, x)\n', (807, 813), True, 'import matplotlib.pyplot as plt\n'), ((813, 839), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""square2.png"""'], {}), "('square2.png')\n", (824, 839), True, 'import matplotlib.pyplot as plt\n'), ((841, 854), 'matplotlib.pyplot.figure', 'plt.figure', (['(2)'], {}), '(2)\n', (851, 854), True, 'import matplotlib.pyplot as plt\n'), ((887, 902), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(-3)', '(3)'], {}), '(-3, 3)\n', (895, 902), True, 'import matplotlib.pyplot as plt\n'), ((902, 941), 'matplotlib.pyplot.legend', 'plt.legend', (["['analytical', 'numerical']"], {}), "(['analytical', 'numerical'])\n", (912, 941), True, 'import matplotlib.pyplot as plt\n'), ((941, 972), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""$f$ [kHz]"""'], {}), "('$f$ [kHz]', **font)\n", (951, 972), True, 'import matplotlib.pyplot as plt\n'), ((972, 992), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""$X(f)$"""'], {}), "('$X(f)$')\n", (982, 992), True, 'import matplotlib.pyplot as plt\n'), ((993, 1011), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (1009, 1011), True, 'import matplotlib.pyplot as plt\n'), ((1012, 1038), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""fftcomp.png"""'], {}), "('fftcomp.png')\n", (1023, 1038), True, 'import matplotlib.pyplot as plt\n'), ((680, 694), 'numpy.sinc', 'np.sinc', (['(f * T)'], {}), '(f * T)\n', (687, 694), True, 'import numpy as np\n'), ((866, 877), 'numpy.real', 'np.real', (['X2'], {}), '(X2)\n', (873, 877), True, 'import numpy as np\n'), ((612, 630), 'numpy.fft.fftshift', 'np.fft.fftshift', (['x'], {}), '(x)\n', (627, 630), True, 'import numpy as np\n')]
import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from sklearn.metrics import mean_squared_error from src.model.datasets.datasets import * from src.model.configs import configs import pipeline import mlflow import mlflow.sklearn mlflow.set_experiment("train") def eval_metrics(target: np.array, predictions: np.array) -> float: output = np.exp(predictions) rmse = mean_squared_error(target, output) return rmse def run_training() -> None: """Train the model.""" with mlflow.start_run(): # read training data data = load_dataset(file_name=configs.TRAINING_DATA_FILE) # logging data artifacts mlflow.log_param('data_path', configs.TRAINING_DATA_FILE) mlflow.log_param('data_version', configs.TRAIN_DATA_VERSION) mlflow.log_param('input_rows', data.shape[0]) mlflow.log_param('input_cols', data.shape[1]) # divide train and test X_train, X_test, y_train, y_test = train_test_split( data[configs.FEATURES], data[configs.TARGET], test_size=0.1, random_state=0 ) # we are setting the seed here # logging the columns used for training columns_x = pd.DataFrame(list(X_train.columns)) columns_y = pd.DataFrame(list(y_train.name)) columns_x.to_csv(configs.TRAIN_X_COLUMNS, header=False, index=False) columns_y.to_csv(configs.TRAIN_Y_COLUMNS, header=False, index=False) mlflow.log_artifact(configs.TRAIN_X_COLUMNS) mlflow.log_artifact(configs.TRAIN_Y_COLUMNS) # transform the target y_train = np.log(y_train) pipeline.model_pipeline.fit(X_train[configs.FEATURES], y_train) predictions = pipeline.model_pipeline.predict(X_test) rmse = eval_metrics(y_test, predictions) mlflow.log_metric("rmse", rmse) mlflow.sklearn.log_model(rmse, "model") save_pipeline(pipeline_to_persist=pipeline.model_pipeline) mlflow.end_run() if __name__ == "__main__": run_training()
[ "mlflow.start_run", "mlflow.end_run", "mlflow.log_param", "numpy.log", "pipeline.model_pipeline.fit", "mlflow.sklearn.log_model", "mlflow.set_experiment", "sklearn.model_selection.train_test_split", "pipeline.model_pipeline.predict", "mlflow.log_artifact", "numpy.exp", "mlflow.log_metric", "...
[((273, 303), 'mlflow.set_experiment', 'mlflow.set_experiment', (['"""train"""'], {}), "('train')\n", (294, 303), False, 'import mlflow\n'), ((386, 405), 'numpy.exp', 'np.exp', (['predictions'], {}), '(predictions)\n', (392, 405), True, 'import numpy as np\n'), ((418, 452), 'sklearn.metrics.mean_squared_error', 'mean_squared_error', (['target', 'output'], {}), '(target, output)\n', (436, 452), False, 'from sklearn.metrics import mean_squared_error\n'), ((1983, 1999), 'mlflow.end_run', 'mlflow.end_run', ([], {}), '()\n', (1997, 1999), False, 'import mlflow\n'), ((535, 553), 'mlflow.start_run', 'mlflow.start_run', ([], {}), '()\n', (551, 553), False, 'import mlflow\n'), ((692, 749), 'mlflow.log_param', 'mlflow.log_param', (['"""data_path"""', 'configs.TRAINING_DATA_FILE'], {}), "('data_path', configs.TRAINING_DATA_FILE)\n", (708, 749), False, 'import mlflow\n'), ((758, 818), 'mlflow.log_param', 'mlflow.log_param', (['"""data_version"""', 'configs.TRAIN_DATA_VERSION'], {}), "('data_version', configs.TRAIN_DATA_VERSION)\n", (774, 818), False, 'import mlflow\n'), ((827, 872), 'mlflow.log_param', 'mlflow.log_param', (['"""input_rows"""', 'data.shape[0]'], {}), "('input_rows', data.shape[0])\n", (843, 872), False, 'import mlflow\n'), ((881, 926), 'mlflow.log_param', 'mlflow.log_param', (['"""input_cols"""', 'data.shape[1]'], {}), "('input_cols', data.shape[1])\n", (897, 926), False, 'import mlflow\n'), ((1003, 1101), 'sklearn.model_selection.train_test_split', 'train_test_split', (['data[configs.FEATURES]', 'data[configs.TARGET]'], {'test_size': '(0.1)', 'random_state': '(0)'}), '(data[configs.FEATURES], data[configs.TARGET], test_size=\n 0.1, random_state=0)\n', (1019, 1101), False, 'from sklearn.model_selection import train_test_split\n'), ((1471, 1515), 'mlflow.log_artifact', 'mlflow.log_artifact', (['configs.TRAIN_X_COLUMNS'], {}), '(configs.TRAIN_X_COLUMNS)\n', (1490, 1515), False, 'import mlflow\n'), ((1524, 1568), 'mlflow.log_artifact', 'mlflow.log_artifact', (['configs.TRAIN_Y_COLUMNS'], {}), '(configs.TRAIN_Y_COLUMNS)\n', (1543, 1568), False, 'import mlflow\n'), ((1619, 1634), 'numpy.log', 'np.log', (['y_train'], {}), '(y_train)\n', (1625, 1634), True, 'import numpy as np\n'), ((1644, 1707), 'pipeline.model_pipeline.fit', 'pipeline.model_pipeline.fit', (['X_train[configs.FEATURES]', 'y_train'], {}), '(X_train[configs.FEATURES], y_train)\n', (1671, 1707), False, 'import pipeline\n'), ((1731, 1770), 'pipeline.model_pipeline.predict', 'pipeline.model_pipeline.predict', (['X_test'], {}), '(X_test)\n', (1762, 1770), False, 'import pipeline\n'), ((1830, 1861), 'mlflow.log_metric', 'mlflow.log_metric', (['"""rmse"""', 'rmse'], {}), "('rmse', rmse)\n", (1847, 1861), False, 'import mlflow\n'), ((1870, 1909), 'mlflow.sklearn.log_model', 'mlflow.sklearn.log_model', (['rmse', '"""model"""'], {}), "(rmse, 'model')\n", (1894, 1909), False, 'import mlflow\n')]
import operator from itertools import product from itertools import accumulate import numpy as np import random import pickle from scipy.interpolate import BSpline from sklearn import linear_model from sklearn.linear_model import LinearRegression from numpy.linalg import inv from functools import reduce from scipy.stats import norm from scipy import integrate from .utility import * from .AGENT import * from tqdm import tqdm ## construct target policy def target_policy(S): if S[0] > 0 and S[1] > 0: return 1 else: return 0 ## get the true value estimation by MC repetition def main_get_value(T_List = [30], rep = 1000000): value_store = {} for T in T_List: value_store[T] = [] n = 100 env = setting(T = T) a = simulation(env) a.gen_buffer(total_N = 64000, S_init = None, policy = a.obs_policy ) a.B_spline(L = 7, d = 3) output, A_percent, _ = a.evaluate_policy(policy = target_policy, seed = None, S_init = None, n = rep) est_mean = np.mean(output) value_store[T].append(est_mean) filename = 'value_int_store' outfile = open(filename,'wb') pickle.dump(value_store, outfile) ## main function def main(seed = 1, T = 30, n = 25, N = 50, beta = 3/7, U_int_store = None): """ input: seed: random seed T : trajectory length n: sample size N: repetitions beta: it is used to calculate the size of bspline basis U_int_store = None : we use MC to get numerical integration for U output: store inference result in filename_CI """ ### CI store filename_CI = 'CI_store_T_%d_n_%d_S_init_int_simulation_1_2' %(T, n) outfile_CI = open(filename_CI, 'ab') ##### total_N = T * n L = int(np.sqrt((n*T)**beta)) env = setting(T = T) a = simulation(env) try: filename = 'value_int_store' outfile = open(filename,'rb') est_mean = pickle.load(outfile)[T][0] outfile.close() except: est_mean = 0.288 count = 0 for i in range(N): np.random.seed(((1 + seed) * N + (i + 1)) * 1234567) a.buffer = {} ## when using gen_buffer, we should empty the buffer first!! a.gen_buffer(total_N = total_N, S_init = None, policy = a.obs_policy ) a.B_spline(L = max(7,(L + 3)), d = 3) L = max(7,(L + 3)) - 3 ## L can not be 3 .. should be at least 4 lower_bound, upper_bound = a.inference_int(policy = target_policy, U_int_store = U_int_store) pickle.dump([lower_bound, upper_bound], outfile_CI) if lower_bound < est_mean and est_mean < upper_bound: count += 1 print(count / N) outfile_CI.close() f = open("result_T_%d_n_%d_S_integration_L_%d.txt" %(T,n, L ), "a+") f.write("Count %d in %d \r\n" % (count, N)) f.close() ############################################################################################################## ############################################################################################################## """ Below are implement about DR Method (Doubly robust off-policy value evaluation for reinforcement learning) """ #V^H = Vhat + rho(r + gamma V^{H-1} - Q) #V^H - 1 = Vhat + rho(r + gamma V^{H-2} - Q) #V^H - 2 = Vhat + rho(r + gamma V^{H-3} - Q) #. #. #. #V^1 = Vhat + rho(r_H + gamma V^{0} - Q_H) def train_target_policy(T = 30, n = 25, policy = target_policy): total_N = T * n beta = 3/7 L = int(np.sqrt((n*T)**beta)) env = setting(T = T) a = simulation(env) a.gen_buffer(total_N = total_N, S_init = None, policy = a.obs_policy ) a.B_spline(L = max(7,(L + 3)), d = 3) ### estimate beta a._beta_hat(policy) a._store_para(a.est_beta) ### pickle the trained model filename_train = 'train_target_policy_with_T_%d_n_%d' %(T, n) outfile_train = open(filename_train, 'wb') pickle.dump({'scaler' : a.scaler, 'bspline' : a.bspline, 'para' : a.para}, outfile_train) ## get the model which can obtain Q function for target policy outfile_train.close() #train_target_policy(T = 140, n = 1000) def main_DR(seed = 1, T = 30, n = 25, alpha = 0.05, policy = target_policy, filename_train = 'train_target_policy_with_T_140_n_1000'): ### CI store filename_CI = 'CI_store_T_%d_n_%d_S_init_int_DR' % (T, n) outfile_CI = open(filename_CI, 'ab') ## get true value filename = 'value_int_store' outfile = open(filename,'rb') est_mean = pickle.load(outfile)[T][0] outfile.close() count = 0 N = 50 for i in range(N): np.random.seed(((1 + seed) * N + (i + 1)) * 1234567) V_output = V_DR(T = T, n = n, policy = target_policy, filename_train = filename_train ) ## obtain value estimation lower_bound = np.mean(V_output) - norm.ppf(1 - alpha/2) * np.std(V_output)/(n**0.5) upper_bound = np.mean(V_output) + norm.ppf(1 - alpha/2) * np.std(V_output)/(n**0.5) CI_length = 2 * norm.ppf(1 - alpha/2) * np.std(V_output)/(n**0.5) pickle.dump([lower_bound,upper_bound], outfile_CI) if lower_bound < est_mean and est_mean < upper_bound: count += 1 print("Lower bound %.3f and upper bound %.3f for true mean %.3f" %(lower_bound,upper_bound, est_mean)) outfile_CI.close() print(count / N) f = open("result_T_%d_n_%d_S_integration_DR.txt" %(T,n), "a+") f.write("Count %d in %d \r\n" % (count, N)) f.close() def V_DR(T, n, policy = target_policy, filename_train = 'train_target_policy_with_T_140_n_1000'): ### filename_train 就是只用当前的数据(就是切一半)来算Q 和 V 值 if filename_train is None: ## obtain trained model ### use half data to train the model and get Q function store in objective b total_N = T * (n // 2) beta = 3/7 L = int(np.sqrt((n*T)**beta)) ## generate data and basis spline env = setting(T = T) b = simulation(env) b.gen_buffer(total_N = total_N, S_init = None, policy = b.obs_policy ) b.B_spline(L = max(7,(L + 3)), d = 3) ### estimate beta b._beta_hat(policy) b._store_para(b.est_beta) ## use the rest data to get V output total_N = T * n - total_N beta = 3/7 L = int(np.sqrt((n*T)**beta)) env = setting(T = T) a = simulation(env) a.gen_buffer(total_N = total_N, S_init = None, policy = a.obs_policy ) ## unpack the trained model a.scaler = b.scaler a.bspline = b.bspline a.para = b.para ## V_output = [] for traj in a.buffer.values(): S, A, U, T = traj dp = [0] * (T + 1) for i in reversed(range(T)): Q_hat = a.Q(S[i], A[i]) ## 用trained model 来算Q和V r = U[i] V_hat = a.V(S[i], policy) if policy(S[i]) == A[i]: rho = 0.5 else: rho = 0 dp[i] = V_hat + rho * (r + a.gamma * dp[i + 1] - Q_hat) V_output.append(dp[0]) return V_output ## filename_train 有的话 就是可以用(其他数据)train 好的模型来得到Q,然后来算V else: outfile_train = open(filename_train, 'rb') output = pickle.load(outfile_train) outfile_train.close() total_N = T * n beta = 3/7 L = int(np.sqrt((n*T)**beta)) env = setting(T = T) a = simulation(env) a.gen_buffer(total_N = total_N, S_init = None, policy = a.obs_policy ) ## unpack the trained model a.scaler = output['scaler'] a.bspline = output['bspline'] a.para = output['para'] ## V_output = [] for traj in a.buffer.values(): S, A, U, T = traj dp = [0] * (T + 1) for i in reversed(range(T)): Q_hat = a.Q(S[i], A[i]) ## 用trained model 来算Q和V r = U[i] V_hat = a.V(S[i], policy) if policy(S[i]) == A[i]: rho = 0.5 else: rho = 0 dp[i] = V_hat + rho * (r + a.gamma * dp[i + 1] - Q_hat) V_output.append(dp[0]) return V_output
[ "scipy.stats.norm.ppf", "pickle.dump", "numpy.random.seed", "numpy.std", "pickle.load", "numpy.mean", "numpy.sqrt" ]
[((1182, 1215), 'pickle.dump', 'pickle.dump', (['value_store', 'outfile'], {}), '(value_store, outfile)\n', (1193, 1215), False, 'import pickle\n'), ((3939, 4029), 'pickle.dump', 'pickle.dump', (["{'scaler': a.scaler, 'bspline': a.bspline, 'para': a.para}", 'outfile_train'], {}), "({'scaler': a.scaler, 'bspline': a.bspline, 'para': a.para},\n outfile_train)\n", (3950, 4029), False, 'import pickle\n'), ((1045, 1060), 'numpy.mean', 'np.mean', (['output'], {}), '(output)\n', (1052, 1060), True, 'import numpy as np\n'), ((1817, 1841), 'numpy.sqrt', 'np.sqrt', (['((n * T) ** beta)'], {}), '((n * T) ** beta)\n', (1824, 1841), True, 'import numpy as np\n'), ((2124, 2176), 'numpy.random.seed', 'np.random.seed', (['(((1 + seed) * N + (i + 1)) * 1234567)'], {}), '(((1 + seed) * N + (i + 1)) * 1234567)\n', (2138, 2176), True, 'import numpy as np\n'), ((2568, 2619), 'pickle.dump', 'pickle.dump', (['[lower_bound, upper_bound]', 'outfile_CI'], {}), '([lower_bound, upper_bound], outfile_CI)\n', (2579, 2619), False, 'import pickle\n'), ((3525, 3549), 'numpy.sqrt', 'np.sqrt', (['((n * T) ** beta)'], {}), '((n * T) ** beta)\n', (3532, 3549), True, 'import numpy as np\n'), ((4640, 4692), 'numpy.random.seed', 'np.random.seed', (['(((1 + seed) * N + (i + 1)) * 1234567)'], {}), '(((1 + seed) * N + (i + 1)) * 1234567)\n', (4654, 4692), True, 'import numpy as np\n'), ((5092, 5143), 'pickle.dump', 'pickle.dump', (['[lower_bound, upper_bound]', 'outfile_CI'], {}), '([lower_bound, upper_bound], outfile_CI)\n', (5103, 5143), False, 'import pickle\n'), ((7338, 7364), 'pickle.load', 'pickle.load', (['outfile_train'], {}), '(outfile_train)\n', (7349, 7364), False, 'import pickle\n'), ((4532, 4552), 'pickle.load', 'pickle.load', (['outfile'], {}), '(outfile)\n', (4543, 4552), False, 'import pickle\n'), ((4839, 4856), 'numpy.mean', 'np.mean', (['V_output'], {}), '(V_output)\n', (4846, 4856), True, 'import numpy as np\n'), ((4931, 4948), 'numpy.mean', 'np.mean', (['V_output'], {}), '(V_output)\n', (4938, 4948), True, 'import numpy as np\n'), ((5891, 5915), 'numpy.sqrt', 'np.sqrt', (['((n * T) ** beta)'], {}), '((n * T) ** beta)\n', (5898, 5915), True, 'import numpy as np\n'), ((6360, 6384), 'numpy.sqrt', 'np.sqrt', (['((n * T) ** beta)'], {}), '((n * T) ** beta)\n', (6367, 6384), True, 'import numpy as np\n'), ((7455, 7479), 'numpy.sqrt', 'np.sqrt', (['((n * T) ** beta)'], {}), '((n * T) ** beta)\n', (7462, 7479), True, 'import numpy as np\n'), ((1991, 2011), 'pickle.load', 'pickle.load', (['outfile'], {}), '(outfile)\n', (2002, 2011), False, 'import pickle\n'), ((5049, 5065), 'numpy.std', 'np.std', (['V_output'], {}), '(V_output)\n', (5055, 5065), True, 'import numpy as np\n'), ((4859, 4882), 'scipy.stats.norm.ppf', 'norm.ppf', (['(1 - alpha / 2)'], {}), '(1 - alpha / 2)\n', (4867, 4882), False, 'from scipy.stats import norm\n'), ((4883, 4899), 'numpy.std', 'np.std', (['V_output'], {}), '(V_output)\n', (4889, 4899), True, 'import numpy as np\n'), ((4951, 4974), 'scipy.stats.norm.ppf', 'norm.ppf', (['(1 - alpha / 2)'], {}), '(1 - alpha / 2)\n', (4959, 4974), False, 'from scipy.stats import norm\n'), ((4975, 4991), 'numpy.std', 'np.std', (['V_output'], {}), '(V_output)\n', (4981, 4991), True, 'import numpy as np\n'), ((5025, 5048), 'scipy.stats.norm.ppf', 'norm.ppf', (['(1 - alpha / 2)'], {}), '(1 - alpha / 2)\n', (5033, 5048), False, 'from scipy.stats import norm\n')]
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 18-7-31 上午11:48 # @Author : xiezheng # @Site : # @File : train_detect.py import time import numpy as np import torch import torchvision.transforms as transforms import cv2 import os from models.onet import ONet from models.pnet import PNet from models.rnet import RNet from checkpoint import CheckPoint from tools.image_tools import * import tools.utils as utils class MtcnnDetector(object): ''' P, R, O net for face detection and landmark alignment''' def __init__(self, p_model_path=None, r_model_path=None, o_model_path=None, min_face_size=12, stride=2, threshold=[0.6, 0.7, 0.7], scale_factor=0.709, use_cuda=True): self.pnet_detector, self.rnet_detector, self.onet_detector = self.create_mtcnn_net( p_model_path, r_model_path, o_model_path, use_cuda) self.min_face_size = min_face_size self.stride = stride self.thresh = threshold self.scale_factor = scale_factor def create_mtcnn_net(self, p_model_path=None, r_model_path=None, o_model_path=None, use_cuda=True): dirname, _ = os.path.split(p_model_path) checkpoint = CheckPoint(dirname) pnet, rnet, onet = None, None, None self.device = torch.device( "cuda:0" if use_cuda and torch.cuda.is_available() else "cpu") if p_model_path is not None: pnet = PNet() pnet_model_state = checkpoint.load_model(p_model_path) pnet = checkpoint.load_state(pnet, pnet_model_state) if (use_cuda): pnet.to(self.device) pnet.eval() if r_model_path is not None: rnet = RNet() rnet_model_state = checkpoint.load_model(r_model_path) rnet = checkpoint.load_state(rnet, rnet_model_state) if (use_cuda): rnet.to(self.device) rnet.eval() if o_model_path is not None: onet = ONet() onet_model_state = checkpoint.load_model(o_model_path) onet = checkpoint.load_state(onet, onet_model_state) if (use_cuda): onet.to(self.device) onet.eval() return pnet, rnet, onet def generate_bounding_box(self, map, reg, scale, threshold): ''' generate bbox from feature map for PNet, there exists no fc layer, only convolution layer ,so feature map n x m x 1/4 Parameters: map: numpy array , n x m x 1, detect score for each position reg: numpy array , n x m x 4, bbox scale: float number, scale of this detection threshold: float number, detect threshold Returns: bbox array ''' stride = 2 cellsize = 12 t_index = np.where(map > threshold) # find nothing if t_index[0].size == 0: return np.array([]) dx1, dy1, dx2, dy2 = [reg[0, t_index[0], t_index[1], i] for i in range(4)] reg = np.array([dx1, dy1, dx2, dy2]) score = map[t_index[0], t_index[1], 0] boundingbox = np.vstack([np.round((stride * t_index[1]) / scale), np.round((stride * t_index[0]) / scale), np.round( (stride * t_index[1] + cellsize) / scale), np.round( (stride * t_index[0] + cellsize) / scale), score, reg, # landmarks ]) return boundingbox.T def resize_image(self, img, scale): """ resize image and transform dimention to [batchsize, channel, height, width] Parameters: ---------- img: numpy array , height x width x channel,input image, channels in BGR order here scale: float number, scale factor of resize operation Returns: ------- transformed image tensor , 1 x channel x height x width """ height, width, channels = img.shape new_height = int(height * scale) # resized new height new_width = int(width * scale) # resized new width new_dim = (new_width, new_height) img_resized = cv2.resize( img, new_dim, interpolation=cv2.INTER_LINEAR) # resized image return img_resized def pad(self, bboxes, w, h): """ pad the the boxes Parameters: ---------- bboxes: numpy array, n x 5, input bboxes w: float number, width of the input image h: float number, height of the input image Returns : ------ dy, dx : numpy array, n x 1, start point of the bbox in target image edy, edx : numpy array, n x 1, end point of the bbox in target image y, x : numpy array, n x 1, start point of the bbox in original image ey, ex : numpy array, n x 1, end point of the bbox in original image tmph, tmpw: numpy array, n x 1, height and width of the bbox """ tmpw = (bboxes[:, 2] - bboxes[:, 0]).astype(np.int32) tmph = (bboxes[:, 3] - bboxes[:, 1]).astype(np.int32) numbox = bboxes.shape[0] dx = np.zeros((numbox,)) dy = np.zeros((numbox,)) edx, edy = tmpw.copy(), tmph.copy() x, y, ex, ey = bboxes[:, 0], bboxes[:, 1], bboxes[:, 2], bboxes[:, 3] tmp_index = np.where(ex > w) edx[tmp_index] = tmpw[tmp_index] + w - ex[tmp_index] ex[tmp_index] = w tmp_index = np.where(ey > h) edy[tmp_index] = tmph[tmp_index] + h - ey[tmp_index] ey[tmp_index] = h tmp_index = np.where(x < 0) dx[tmp_index] = 0 - x[tmp_index] x[tmp_index] = 0 tmp_index = np.where(y < 0) dy[tmp_index] = 0 - y[tmp_index] y[tmp_index] = 0 return_list = [dy, edy, dx, edx, y, ey, x, ex, tmpw, tmph] return_list = [item.astype(np.int32) for item in return_list] return return_list def detect_pnet(self, im): """Get face candidates through pnet Parameters: ---------- im: numpy array, input image array Returns: ------- boxes: numpy array detected boxes before calibration boxes_align: numpy array boxes after calibration """ h, w, c = im.shape net_size = 12 current_scale = float(net_size) / \ self.min_face_size # find initial scale im_resized = self.resize_image(im, current_scale) current_height, current_width, _ = im_resized.shape # fcn for pnet all_boxes = list() while min(current_height, current_width) > net_size: image_tensor = convert_image_to_tensor(im_resized) feed_imgs = image_tensor.unsqueeze(0) feed_imgs = feed_imgs.to(self.device) cls_map, reg = self.pnet_detector(feed_imgs) cls_map_np = convert_chwTensor_to_hwcNumpy(cls_map.cpu()) reg_np = convert_chwTensor_to_hwcNumpy(reg.cpu()) boxes = self.generate_bounding_box( cls_map_np[0, :, :], reg_np, current_scale, self.thresh[0]) current_scale *= self.scale_factor im_resized = self.resize_image(im, current_scale) current_height, current_width, _ = im_resized.shape if boxes.size == 0: continue keep = utils.nms(boxes[:, :5], 0.5, 'Union') boxes = boxes[keep] all_boxes.append(boxes) if len(all_boxes) == 0: return None, None all_boxes = np.vstack(all_boxes) # merge the detection from first stage keep = utils.nms(all_boxes[:, 0:5], 0.7, 'Union') all_boxes = all_boxes[keep] bw = all_boxes[:, 2] - all_boxes[:, 0] bh = all_boxes[:, 3] - all_boxes[:, 1] boxes = np.vstack([all_boxes[:, 0], all_boxes[:, 1], all_boxes[:, 2], all_boxes[:, 3], all_boxes[:, 4] ]) boxes = boxes.T align_topx = all_boxes[:, 0] + all_boxes[:, 5] * bw align_topy = all_boxes[:, 1] + all_boxes[:, 6] * bh align_bottomx = all_boxes[:, 2] + all_boxes[:, 7] * bw align_bottomy = all_boxes[:, 3] + all_boxes[:, 8] * bh # refine the boxes boxes_align = np.vstack([align_topx, align_topy, align_bottomx, align_bottomy, all_boxes[:, 4] ]) boxes_align = boxes_align.T return boxes, boxes_align def detect_rnet(self, im, dets): """Get face candidates using rnet Parameters: ---------- im: numpy array input image array dets: numpy array detection results of pnet Returns: ------- boxes: numpy array detected boxes before calibration boxes_align: numpy array boxes after calibration """ h, w, c = im.shape if dets is None: return None, None dets = utils.convert_to_square(dets) dets[:, 0:4] = np.round(dets[:, 0:4]) [dy, edy, dx, edx, y, ey, x, ex, tmpw, tmph] = self.pad(dets, w, h) num_boxes = dets.shape[0] cropped_ims_tensors = [] for i in range(num_boxes): try: if tmph[i] > 0 and tmpw[i] > 0: tmp = np.zeros((tmph[i], tmpw[i], 3), dtype=np.uint8) tmp[dy[i]:edy[i], dx[i]:edx[i], :] = im[y[i]:ey[i], x[i]:ex[i], :] crop_im = cv2.resize(tmp, (24, 24)) crop_im_tensor = convert_image_to_tensor(crop_im) # cropped_ims_tensors[i, :, :, :] = crop_im_tensor cropped_ims_tensors.append(crop_im_tensor) except ValueError as e: print('dy: {}, edy: {}, dx: {}, edx: {}'.format(dy[i], edy[i], dx[i], edx[i])) print('y: {}, ey: {}, x: {}, ex: {}'.format(y[i], ey[i], x[i], ex[i])) print(e) feed_imgs = torch.stack(cropped_ims_tensors) feed_imgs = feed_imgs.to(self.device) cls_map, reg = self.rnet_detector(feed_imgs) cls_map = cls_map.cpu().data.numpy() reg = reg.cpu().data.numpy() keep_inds = np.where(cls_map > self.thresh[1])[0] if len(keep_inds) > 0: boxes = dets[keep_inds] cls = cls_map[keep_inds] reg = reg[keep_inds] else: return None, None keep = utils.nms(boxes, 0.7) if len(keep) == 0: return None, None keep_cls = cls[keep] keep_boxes = boxes[keep] keep_reg = reg[keep] bw = keep_boxes[:, 2] - keep_boxes[:, 0] bh = keep_boxes[:, 3] - keep_boxes[:, 1] boxes = np.vstack([keep_boxes[:, 0], keep_boxes[:, 1], keep_boxes[:, 2], keep_boxes[:, 3], keep_cls[:, 0] ]) align_topx = keep_boxes[:, 0] + keep_reg[:, 0] * bw align_topy = keep_boxes[:, 1] + keep_reg[:, 1] * bh align_bottomx = keep_boxes[:, 2] + keep_reg[:, 2] * bw align_bottomy = keep_boxes[:, 3] + keep_reg[:, 3] * bh boxes_align = np.vstack([align_topx, align_topy, align_bottomx, align_bottomy, keep_cls[:, 0] ]) boxes = boxes.T boxes_align = boxes_align.T return boxes, boxes_align def detect_onet(self, im, dets): """Get face candidates using onet Parameters: ---------- im: numpy array input image array dets: numpy array detection results of rnet Returns: ------- boxes_align: numpy array boxes after calibration landmarks_align: numpy array landmarks after calibration """ h, w, c = im.shape if dets is None: return None, None dets = utils.convert_to_square(dets) dets[:, 0:4] = np.round(dets[:, 0:4]) [dy, edy, dx, edx, y, ey, x, ex, tmpw, tmph] = self.pad(dets, w, h) num_boxes = dets.shape[0] cropped_ims_tensors = [] for i in range(num_boxes): try: if tmph[i] > 0 and tmpw[i] > 0: tmp = np.zeros((tmph[i], tmpw[i], 3), dtype=np.uint8) tmp[dy[i]:edy[i], dx[i]:edx[i], :] = im[y[i]:ey[i], x[i]:ex[i], :] crop_im = cv2.resize(tmp, (48, 48)) crop_im_tensor = convert_image_to_tensor(crop_im) cropped_ims_tensors.append(crop_im_tensor) except ValueError as e: print(e) feed_imgs = torch.stack(cropped_ims_tensors) feed_imgs = feed_imgs.to(self.device) cls_map, reg, landmark = self.onet_detector(feed_imgs) cls_map = cls_map.cpu().data.numpy() reg = reg.cpu().data.numpy() landmark = landmark.cpu().data.numpy() keep_inds = np.where(cls_map > self.thresh[2])[0] if len(keep_inds) > 0: boxes = dets[keep_inds] cls = cls_map[keep_inds] reg = reg[keep_inds] landmark = landmark[keep_inds] else: return None, None keep = utils.nms(boxes, 0.7, mode="Minimum") if len(keep) == 0: return None, None keep_cls = cls[keep] keep_boxes = boxes[keep] keep_reg = reg[keep] keep_landmark = landmark[keep] bw = keep_boxes[:, 2] - keep_boxes[:, 0] bh = keep_boxes[:, 3] - keep_boxes[:, 1] align_topx = keep_boxes[:, 0] + keep_reg[:, 0] * bw align_topy = keep_boxes[:, 1] + keep_reg[:, 1] * bh align_bottomx = keep_boxes[:, 2] + keep_reg[:, 2] * bw align_bottomy = keep_boxes[:, 3] + keep_reg[:, 3] * bh align_landmark_topx = keep_boxes[:, 0] align_landmark_topy = keep_boxes[:, 1] boxes_align = np.vstack([align_topx, align_topy, align_bottomx, align_bottomy, keep_cls[:, 0] ]) boxes_align = boxes_align.T landmark = np.vstack([ align_landmark_topx + keep_landmark[:, 0] * bw, align_landmark_topy + keep_landmark[:, 1] * bh, align_landmark_topx + keep_landmark[:, 2] * bw, align_landmark_topy + keep_landmark[:, 3] * bh, align_landmark_topx + keep_landmark[:, 4] * bw, align_landmark_topy + keep_landmark[:, 5] * bh, align_landmark_topx + keep_landmark[:, 6] * bw, align_landmark_topy + keep_landmark[:, 7] * bh, align_landmark_topx + keep_landmark[:, 8] * bw, align_landmark_topy + keep_landmark[:, 9] * bh, ]) landmark_align = landmark.T return boxes_align, landmark_align def detect_face(self, img): ''' Detect face over image ''' boxes_align = np.array([]) landmark_align = np.array([]) t = time.time() # pnet if self.pnet_detector: boxes, boxes_align = self.detect_pnet(img) if boxes_align is None: return np.array([]), np.array([]) t1 = time.time() - t t = time.time() # rnet if self.rnet_detector: boxes, boxes_align = self.detect_rnet(img, boxes_align) if boxes_align is None: return np.array([]), np.array([]) t2 = time.time() - t t = time.time() # onet if self.onet_detector: boxes_align, landmark_align = self.detect_onet(img, boxes_align) if boxes_align is None: return np.array([]), np.array([]) t3 = time.time() - t t = time.time() print( "time cost " + '{:.3f}'.format(t1 + t2 + t3) + ' pnet {:.3f} rnet {:.3f} onet {:.3f}'.format(t1, t2, t3)) return boxes_align, landmark_align
[ "torch.stack", "numpy.zeros", "time.time", "models.pnet.PNet", "models.rnet.RNet", "numpy.vstack", "numpy.where", "numpy.array", "tools.utils.convert_to_square", "models.onet.ONet", "torch.cuda.is_available", "checkpoint.CheckPoint", "os.path.split", "numpy.round", "tools.utils.nms", "...
[((1264, 1291), 'os.path.split', 'os.path.split', (['p_model_path'], {}), '(p_model_path)\n', (1277, 1291), False, 'import os\n'), ((1313, 1332), 'checkpoint.CheckPoint', 'CheckPoint', (['dirname'], {}), '(dirname)\n', (1323, 1332), False, 'from checkpoint import CheckPoint\n'), ((2949, 2974), 'numpy.where', 'np.where', (['(map > threshold)'], {}), '(map > threshold)\n', (2957, 2974), True, 'import numpy as np\n'), ((3191, 3221), 'numpy.array', 'np.array', (['[dx1, dy1, dx2, dy2]'], {}), '([dx1, dy1, dx2, dy2])\n', (3199, 3221), True, 'import numpy as np\n'), ((4539, 4595), 'cv2.resize', 'cv2.resize', (['img', 'new_dim'], {'interpolation': 'cv2.INTER_LINEAR'}), '(img, new_dim, interpolation=cv2.INTER_LINEAR)\n', (4549, 4595), False, 'import cv2\n'), ((5544, 5563), 'numpy.zeros', 'np.zeros', (['(numbox,)'], {}), '((numbox,))\n', (5552, 5563), True, 'import numpy as np\n'), ((5577, 5596), 'numpy.zeros', 'np.zeros', (['(numbox,)'], {}), '((numbox,))\n', (5585, 5596), True, 'import numpy as np\n'), ((5741, 5757), 'numpy.where', 'np.where', (['(ex > w)'], {}), '(ex > w)\n', (5749, 5757), True, 'import numpy as np\n'), ((5866, 5882), 'numpy.where', 'np.where', (['(ey > h)'], {}), '(ey > h)\n', (5874, 5882), True, 'import numpy as np\n'), ((5991, 6006), 'numpy.where', 'np.where', (['(x < 0)'], {}), '(x < 0)\n', (5999, 6006), True, 'import numpy as np\n'), ((6094, 6109), 'numpy.where', 'np.where', (['(y < 0)'], {}), '(y < 0)\n', (6102, 6109), True, 'import numpy as np\n'), ((7997, 8017), 'numpy.vstack', 'np.vstack', (['all_boxes'], {}), '(all_boxes)\n', (8006, 8017), True, 'import numpy as np\n'), ((8081, 8123), 'tools.utils.nms', 'utils.nms', (['all_boxes[:, 0:5]', '(0.7)', '"""Union"""'], {}), "(all_boxes[:, 0:5], 0.7, 'Union')\n", (8090, 8123), True, 'import tools.utils as utils\n'), ((8272, 8373), 'numpy.vstack', 'np.vstack', (['[all_boxes[:, 0], all_boxes[:, 1], all_boxes[:, 2], all_boxes[:, 3],\n all_boxes[:, 4]]'], {}), '([all_boxes[:, 0], all_boxes[:, 1], all_boxes[:, 2], all_boxes[:, \n 3], all_boxes[:, 4]])\n', (8281, 8373), True, 'import numpy as np\n'), ((8827, 8914), 'numpy.vstack', 'np.vstack', (['[align_topx, align_topy, align_bottomx, align_bottomy, all_boxes[:, 4]]'], {}), '([align_topx, align_topy, align_bottomx, align_bottomy, all_boxes[\n :, 4]])\n', (8836, 8914), True, 'import numpy as np\n'), ((9671, 9700), 'tools.utils.convert_to_square', 'utils.convert_to_square', (['dets'], {}), '(dets)\n', (9694, 9700), True, 'import tools.utils as utils\n'), ((9724, 9746), 'numpy.round', 'np.round', (['dets[:, 0:4]'], {}), '(dets[:, 0:4])\n', (9732, 9746), True, 'import numpy as np\n'), ((10677, 10709), 'torch.stack', 'torch.stack', (['cropped_ims_tensors'], {}), '(cropped_ims_tensors)\n', (10688, 10709), False, 'import torch\n'), ((11150, 11171), 'tools.utils.nms', 'utils.nms', (['boxes', '(0.7)'], {}), '(boxes, 0.7)\n', (11159, 11171), True, 'import tools.utils as utils\n'), ((11435, 11539), 'numpy.vstack', 'np.vstack', (['[keep_boxes[:, 0], keep_boxes[:, 1], keep_boxes[:, 2], keep_boxes[:, 3],\n keep_cls[:, 0]]'], {}), '([keep_boxes[:, 0], keep_boxes[:, 1], keep_boxes[:, 2], keep_boxes\n [:, 3], keep_cls[:, 0]])\n', (11444, 11539), True, 'import numpy as np\n'), ((11940, 12025), 'numpy.vstack', 'np.vstack', (['[align_topx, align_topy, align_bottomx, align_bottomy, keep_cls[:, 0]]'], {}), '([align_topx, align_topy, align_bottomx, align_bottomy, keep_cls[:,\n 0]])\n', (11949, 12025), True, 'import numpy as np\n'), ((12812, 12841), 'tools.utils.convert_to_square', 'utils.convert_to_square', (['dets'], {}), '(dets)\n', (12835, 12841), True, 'import tools.utils as utils\n'), ((12865, 12887), 'numpy.round', 'np.round', (['dets[:, 0:4]'], {}), '(dets[:, 0:4])\n', (12873, 12887), True, 'import numpy as np\n'), ((13565, 13597), 'torch.stack', 'torch.stack', (['cropped_ims_tensors'], {}), '(cropped_ims_tensors)\n', (13576, 13597), False, 'import torch\n'), ((14139, 14176), 'tools.utils.nms', 'utils.nms', (['boxes', '(0.7)'], {'mode': '"""Minimum"""'}), "(boxes, 0.7, mode='Minimum')\n", (14148, 14176), True, 'import tools.utils as utils\n'), ((14830, 14915), 'numpy.vstack', 'np.vstack', (['[align_topx, align_topy, align_bottomx, align_bottomy, keep_cls[:, 0]]'], {}), '([align_topx, align_topy, align_bottomx, align_bottomy, keep_cls[:,\n 0]])\n', (14839, 14915), True, 'import numpy as np\n'), ((15135, 15652), 'numpy.vstack', 'np.vstack', (['[align_landmark_topx + keep_landmark[:, 0] * bw, align_landmark_topy + \n keep_landmark[:, 1] * bh, align_landmark_topx + keep_landmark[:, 2] *\n bw, align_landmark_topy + keep_landmark[:, 3] * bh, align_landmark_topx +\n keep_landmark[:, 4] * bw, align_landmark_topy + keep_landmark[:, 5] *\n bh, align_landmark_topx + keep_landmark[:, 6] * bw, align_landmark_topy +\n keep_landmark[:, 7] * bh, align_landmark_topx + keep_landmark[:, 8] *\n bw, align_landmark_topy + keep_landmark[:, 9] * bh]'], {}), '([align_landmark_topx + keep_landmark[:, 0] * bw, \n align_landmark_topy + keep_landmark[:, 1] * bh, align_landmark_topx + \n keep_landmark[:, 2] * bw, align_landmark_topy + keep_landmark[:, 3] *\n bh, align_landmark_topx + keep_landmark[:, 4] * bw, align_landmark_topy +\n keep_landmark[:, 5] * bh, align_landmark_topx + keep_landmark[:, 6] *\n bw, align_landmark_topy + keep_landmark[:, 7] * bh, align_landmark_topx +\n keep_landmark[:, 8] * bw, align_landmark_topy + keep_landmark[:, 9] * bh])\n', (15144, 15652), True, 'import numpy as np\n'), ((15933, 15945), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (15941, 15945), True, 'import numpy as np\n'), ((15971, 15983), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (15979, 15983), True, 'import numpy as np\n'), ((15997, 16008), 'time.time', 'time.time', ([], {}), '()\n', (16006, 16008), False, 'import time\n'), ((1546, 1552), 'models.pnet.PNet', 'PNet', ([], {}), '()\n', (1550, 1552), False, 'from models.pnet import PNet\n'), ((1830, 1836), 'models.rnet.RNet', 'RNet', ([], {}), '()\n', (1834, 1836), False, 'from models.rnet import RNet\n'), ((2114, 2120), 'models.onet.ONet', 'ONet', ([], {}), '()\n', (2118, 2120), False, 'from models.onet import ONet\n'), ((3050, 3062), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (3058, 3062), True, 'import numpy as np\n'), ((7807, 7844), 'tools.utils.nms', 'utils.nms', (['boxes[:, :5]', '(0.5)', '"""Union"""'], {}), "(boxes[:, :5], 0.5, 'Union')\n", (7816, 7844), True, 'import tools.utils as utils\n'), ((10914, 10948), 'numpy.where', 'np.where', (['(cls_map > self.thresh[1])'], {}), '(cls_map > self.thresh[1])\n', (10922, 10948), True, 'import numpy as np\n'), ((13860, 13894), 'numpy.where', 'np.where', (['(cls_map > self.thresh[2])'], {}), '(cls_map > self.thresh[2])\n', (13868, 13894), True, 'import numpy as np\n'), ((16247, 16258), 'time.time', 'time.time', ([], {}), '()\n', (16256, 16258), False, 'import time\n'), ((16510, 16521), 'time.time', 'time.time', ([], {}), '()\n', (16519, 16521), False, 'import time\n'), ((16782, 16793), 'time.time', 'time.time', ([], {}), '()\n', (16791, 16793), False, 'import time\n'), ((3303, 3340), 'numpy.round', 'np.round', (['(stride * t_index[1] / scale)'], {}), '(stride * t_index[1] / scale)\n', (3311, 3340), True, 'import numpy as np\n'), ((3377, 3414), 'numpy.round', 'np.round', (['(stride * t_index[0] / scale)'], {}), '(stride * t_index[0] / scale)\n', (3385, 3414), True, 'import numpy as np\n'), ((3451, 3501), 'numpy.round', 'np.round', (['((stride * t_index[1] + cellsize) / scale)'], {}), '((stride * t_index[1] + cellsize) / scale)\n', (3459, 3501), True, 'import numpy as np\n'), ((3574, 3624), 'numpy.round', 'np.round', (['((stride * t_index[0] + cellsize) / scale)'], {}), '((stride * t_index[0] + cellsize) / scale)\n', (3582, 3624), True, 'import numpy as np\n'), ((16215, 16226), 'time.time', 'time.time', ([], {}), '()\n', (16224, 16226), False, 'import time\n'), ((16478, 16489), 'time.time', 'time.time', ([], {}), '()\n', (16487, 16489), False, 'import time\n'), ((16750, 16761), 'time.time', 'time.time', ([], {}), '()\n', (16759, 16761), False, 'import time\n'), ((1451, 1476), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (1474, 1476), False, 'import torch\n'), ((10018, 10065), 'numpy.zeros', 'np.zeros', (['(tmph[i], tmpw[i], 3)'], {'dtype': 'np.uint8'}), '((tmph[i], tmpw[i], 3), dtype=np.uint8)\n', (10026, 10065), True, 'import numpy as np\n'), ((10183, 10208), 'cv2.resize', 'cv2.resize', (['tmp', '(24, 24)'], {}), '(tmp, (24, 24))\n', (10193, 10208), False, 'import cv2\n'), ((13159, 13206), 'numpy.zeros', 'np.zeros', (['(tmph[i], tmpw[i], 3)'], {'dtype': 'np.uint8'}), '((tmph[i], tmpw[i], 3), dtype=np.uint8)\n', (13167, 13206), True, 'import numpy as np\n'), ((13324, 13349), 'cv2.resize', 'cv2.resize', (['tmp', '(48, 48)'], {}), '(tmp, (48, 48))\n', (13334, 13349), False, 'import cv2\n'), ((16170, 16182), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (16178, 16182), True, 'import numpy as np\n'), ((16184, 16196), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (16192, 16196), True, 'import numpy as np\n'), ((16433, 16445), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (16441, 16445), True, 'import numpy as np\n'), ((16447, 16459), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (16455, 16459), True, 'import numpy as np\n'), ((16705, 16717), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (16713, 16717), True, 'import numpy as np\n'), ((16719, 16731), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (16727, 16731), True, 'import numpy as np\n')]
""" Title: Random forest digital twin template Authors: <NAME>, <NAME>, <NAME> Date created: 2020/11/09 Last modified: 2020/11/09 Description: Templates for creation and execution through the VLAB on DestinationEarth VirtualCloud of random forest based digital twins. Version: 0.1 """ import json, csv import os, sys, getopt, math import numpy as np import math, copy, time from pathlib import Path from sklearn.ensemble import RandomForestRegressor, RandomForestClassifier from sklearn.model_selection import train_test_split from joblib import dump, load from prepare_image import loadTrainData, loadClassifyData from utils import blockshaped, unblockshaped, Setcmap from generate_raster import numpy_array_to_raster, NO_DATA, GDAL_DATA_TYPE, SPATIAL_REFERENCE_SYSTEM_WKID, GEOTIFF_DRIVER_NAME, do_parse from prepare_sentinel_product import subset_and_resample, do_transform from soil_moisture_ftp_client import download_to from prepare_edge_data import invoke_prepare # csv edgestream # west,south,east,north,YYYY,MM,DD,value from sklearn.model_selection import RandomizedSearchCV, GridSearchCV def searchBestParamsGridCV(rf, base_model, train_features, train_labels,test_features, test_labels ): param_grid = { 'bootstrap': [True], 'max_depth': [1, 4, 8, 10], 'max_features': [2, 3], 'min_samples_leaf': [3, 4, 5], 'min_samples_split': [8, 10, 12], 'n_estimators': [20, 40, 50, 100] } # rf = RandomForestRegressor() grid_search = GridSearchCV(estimator = rf, param_grid = param_grid, cv = 3, n_jobs = -1, verbose = 2) grid_search.fit(train_features, train_labels) pprint(grid_search.best_params_) # base_model = RandomForestRegressor(n_estimators = 10, random_state = 42) base_model.fit(train_features, train_labels) base_accuracy = evaluate(base_model, test_features, test_labels) best_grid = grid_search.best_estimator_ grid_accuracy = evaluate(best_grid, test_features, test_labels) print("grid_accuracy: ",grid_accuracy) print('Improvement of {:0.2f}%.'.format( 100 * (grid_accuracy - base_accuracy) / base_accuracy)) def getVlabParams(): # bbox i west,south,east,north with open('vlabparams.json') as json_file: return json.load(json_file) def trainClass(): vlabparams=getVlabParams() bbox = vlabparams['bbox'].split(',') features = vlabparams['features'].split(',') targets = vlabparams['targets'].split(',') X, Y, origshape = loadTrainData('data/inputs/', features = features, targets=targets) X = np.rollaxis(X, 0, 4) X = X.reshape(X.shape[0]*X.shape[1]*X.shape[2],X.shape[3]) Y = Y.flatten() Y = np.digitize(Y,bins=[0.1, 0.2, 0.3, 0.4, 0.5]) #, 0.6, 0.7, 0.8, 0.9, 1.0]) print("X.shape: ", X.shape) print("Y.shape: ", Y.shape) X[np.isnan(X)]=0 Y[np.isnan(Y)]=0 print("Train/Test split") X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.33, random_state=0) del X,Y rf = RandomForestClassifier(n_estimators=50, oob_score=True, max_depth=4, n_jobs=-1, verbose=2, bootstrap=True) print("Train") rf.fit(X_train, y_train) print("train score: ", rf.score(X_train,y_train)) print("Dump") dump(rf, 'data/outputs/model.joblib') print("Test") print(rf.score(X_test,y_test)) del X_train, X_test, y_train, y_test flds = list(os.walk('data/satproduct/'))[0][1] X,origshape = loadClassifyData('data/inputs/{}'.format(flds[0]), features = features, modifiers={}) X = np.rollaxis(X, 0, 4) X = X.reshape(X.shape[0]*X.shape[1]*X.shape[2],X.shape[3]) Y = (rf.predict(X)) Y=Y.reshape(-1,32, 32) Y=unblockshaped(Y,int(origshape[0]), int(origshape[1])) numpy_array_to_raster('data/outputs/prediction.tif', Y, (float(bbox[0]), float(bbox[3])), 0.000091903317710, 1, NO_DATA, GDAL_DATA_TYPE, SPATIAL_REFERENCE_SYSTEM_WKID, GEOTIFF_DRIVER_NAME) def trainRegr(): vlabparams=getVlabParams() bbox = vlabparams['bbox'].split(',') features = vlabparams['features'].split(',') targets = vlabparams['targets'].split(',') X_train, X_test, y_train, y_test = getTestTrainData(features, targets) regr = RandomForestRegressor(max_depth=100, min_samples_leaf=3,min_samples_split=8, bootstrap=True, random_state=0, n_estimators = 100, verbose=2, n_jobs=-1, warm_start=True) print("Train") regr.fit(X_train, y_train) print("train score: ", regr.score(X_train,y_train)) print("Dump") dump(regr, 'data/outputs/model.joblib') print("Test") print(regr.score(X_test,y_test)) del X_train, X_test, y_train, y_test flds = list(os.walk('data/satproduct/'))[0][1] X,origshape = loadClassifyData('data/inputs/{}'.format(flds[0]), features = features, modifiers={}) X = np.rollaxis(X, 0, 4) X = X.reshape(X.shape[0]*X.shape[1]*X.shape[2],X.shape[3]) Y = (regr.predict(X)) Y=Y.reshape(-1,32, 32) Y=unblockshaped(Y,int(origshape[0]), int(origshape[1])) numpy_array_to_raster('data/outputs/prediction.tif', Y, (float(bbox[0]), float(bbox[3])), 0.000091903317710, 1, NO_DATA, GDAL_DATA_TYPE, SPATIAL_REFERENCE_SYSTEM_WKID, GEOTIFF_DRIVER_NAME) def run(): vlabparams=getVlabParams() bbox = vlabparams['bbox'].split(',') features = vlabparams['features'].split(',') modifiers = json.loads(vlabparams['modifiers']) flds = list(os.walk('data/satproduct/'))[0][1] X, origshape = loadClassifyData('data/inputs/{}'.format(flds[0]), features = features, modifiers=modifiers) X = np.rollaxis(X, 0, 4) X=X.reshape(X.shape[0]*X.shape[1]*X.shape[2],X.shape[3]) regr = load('data/model.joblib') Y = (regr.predict(X)) Y=Y.reshape(-1,32, 32) Y=unblockshaped(Y,int(origshape[0]), int(origshape[1])) # Y = np.flip(Y, 0) numpy_array_to_raster('data/outputs/prediction.tif', Y, (float(bbox[0]), float(bbox[3])), 0.000091903317710, 1, NO_DATA, GDAL_DATA_TYPE, SPATIAL_REFERENCE_SYSTEM_WKID, GEOTIFF_DRIVER_NAME) def getTestTrainData(features, targets): X, Y, origshape = loadTrainData('data/inputs/', features = features, targets=targets) X = np.rollaxis(X, 0, 4) X = X.reshape(X.shape[0]*X.shape[1]*X.shape[2],X.shape[3]) Y = Y.flatten() Y = np.digitize(Y,bins=[0.1, 0.2, 0.3, 0.4, 0.5]) #, 0.6, 0.7, 0.8, 0.9, 1.0]) print("X.shape: ", X.shape) print("Y.shape: ", Y.shape) X[np.isnan(X)]=0 Y[np.isnan(Y)]=0 print("Train/Test split") X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.33, random_state=0) del X,Y return X_train, X_test, y_train, y_test def optimizeRegr(): vlabparams=getVlabParams() bbox = vlabparams['bbox'].split(',') features = vlabparams['features'].split(',') targets = vlabparams['targets'].split(',') rf = RandomForestRegressor() base_model = RandomForestRegressor(n_estimators = 10, random_state = 42) X_train, X_test, y_train, y_test = getTestTrainData(features, targets) searchBestParamsGridCV(rf, base_model, X_train, y_train,X_test, y_test ) def optimizeClassifier(): vlabparams=getVlabParams() bbox = vlabparams['bbox'].split(',') features = vlabparams['features'].split(',') targets = vlabparams['targets'].split(',') rf = RandomForestClassifier() base_model = RandomForestClassifier(n_estimators = 10, random_state = 42) X_train, X_test, y_train, y_test = getTestTrainData(features, targets) searchBestParamsGridCV(rf, base_model, X_train, y_train,X_test, y_test ) def main(argv): #data/satproduct/ vlabparams=getVlabParams() bbox = vlabparams['bbox'].split(',') Path("data/inputs/").mkdir(parents=True, exist_ok=True) flds = list(os.walk('data/satproduct/'))[0][1] mode = int(sys.argv[1]) shape = None for fld in flds: Path('data/inputs/{}/'.format(fld)).mkdir(parents=True, exist_ok=True) Path('data/edge/{}/'.format(fld)).mkdir(parents=True, exist_ok=True) shape = subset_and_resample("data/satproduct/{}/".format(fld), 'data/inputs/{}/'.format(fld), bbox ) _, y, m, d = do_parse(fld) if 'SOIL' in vlabparams['features'].split(',') or 'SOIL' in vlabparams['targets'].split(','): download_to('data/edge/{}/'.format(fld),'data/inputs/{}/'.format(fld),y,m,d, bbox) invoke_prepare('data/edge/','data/inputs/{}/'.format(fld),y,m,d, bbox, shape) if mode==0: run() elif mode==1: trainRegr() elif mode==3: optimizeRegr() elif mode==4: optimizeClassifier() elif mode==2: trainRegr() if __name__ == "__main__": main(sys.argv[1:])
[ "sklearn.ensemble.RandomForestClassifier", "sklearn.model_selection.GridSearchCV", "json.load", "json.loads", "sklearn.model_selection.train_test_split", "generate_raster.do_parse", "os.walk", "joblib.dump", "numpy.isnan", "prepare_image.loadTrainData", "sklearn.ensemble.RandomForestRegressor", ...
[((1543, 1620), 'sklearn.model_selection.GridSearchCV', 'GridSearchCV', ([], {'estimator': 'rf', 'param_grid': 'param_grid', 'cv': '(3)', 'n_jobs': '(-1)', 'verbose': '(2)'}), '(estimator=rf, param_grid=param_grid, cv=3, n_jobs=-1, verbose=2)\n', (1555, 1620), False, 'from sklearn.model_selection import RandomizedSearchCV, GridSearchCV\n'), ((2590, 2655), 'prepare_image.loadTrainData', 'loadTrainData', (['"""data/inputs/"""'], {'features': 'features', 'targets': 'targets'}), "('data/inputs/', features=features, targets=targets)\n", (2603, 2655), False, 'from prepare_image import loadTrainData, loadClassifyData\n'), ((2667, 2687), 'numpy.rollaxis', 'np.rollaxis', (['X', '(0)', '(4)'], {}), '(X, 0, 4)\n', (2678, 2687), True, 'import numpy as np\n'), ((2782, 2828), 'numpy.digitize', 'np.digitize', (['Y'], {'bins': '[0.1, 0.2, 0.3, 0.4, 0.5]'}), '(Y, bins=[0.1, 0.2, 0.3, 0.4, 0.5])\n', (2793, 2828), True, 'import numpy as np\n'), ((3040, 3094), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X', 'Y'], {'test_size': '(0.33)', 'random_state': '(0)'}), '(X, Y, test_size=0.33, random_state=0)\n', (3056, 3094), False, 'from sklearn.model_selection import train_test_split\n'), ((3120, 3231), 'sklearn.ensemble.RandomForestClassifier', 'RandomForestClassifier', ([], {'n_estimators': '(50)', 'oob_score': '(True)', 'max_depth': '(4)', 'n_jobs': '(-1)', 'verbose': '(2)', 'bootstrap': '(True)'}), '(n_estimators=50, oob_score=True, max_depth=4, n_jobs\n =-1, verbose=2, bootstrap=True)\n', (3142, 3231), False, 'from sklearn.ensemble import RandomForestRegressor, RandomForestClassifier\n'), ((3505, 3542), 'joblib.dump', 'dump', (['rf', '"""data/outputs/model.joblib"""'], {}), "(rf, 'data/outputs/model.joblib')\n", (3509, 3542), False, 'from joblib import dump, load\n'), ((3815, 3835), 'numpy.rollaxis', 'np.rollaxis', (['X', '(0)', '(4)'], {}), '(X, 0, 4)\n', (3826, 3835), True, 'import numpy as np\n'), ((4551, 4727), 'sklearn.ensemble.RandomForestRegressor', 'RandomForestRegressor', ([], {'max_depth': '(100)', 'min_samples_leaf': '(3)', 'min_samples_split': '(8)', 'bootstrap': '(True)', 'random_state': '(0)', 'n_estimators': '(100)', 'verbose': '(2)', 'n_jobs': '(-1)', 'warm_start': '(True)'}), '(max_depth=100, min_samples_leaf=3, min_samples_split=\n 8, bootstrap=True, random_state=0, n_estimators=100, verbose=2, n_jobs=\n -1, warm_start=True)\n', (4572, 4727), False, 'from sklearn.ensemble import RandomForestRegressor, RandomForestClassifier\n'), ((4853, 4892), 'joblib.dump', 'dump', (['regr', '"""data/outputs/model.joblib"""'], {}), "(regr, 'data/outputs/model.joblib')\n", (4857, 4892), False, 'from joblib import dump, load\n'), ((5167, 5187), 'numpy.rollaxis', 'np.rollaxis', (['X', '(0)', '(4)'], {}), '(X, 0, 4)\n', (5178, 5187), True, 'import numpy as np\n'), ((5777, 5812), 'json.loads', 'json.loads', (["vlabparams['modifiers']"], {}), "(vlabparams['modifiers'])\n", (5787, 5812), False, 'import json, csv\n'), ((5988, 6008), 'numpy.rollaxis', 'np.rollaxis', (['X', '(0)', '(4)'], {}), '(X, 0, 4)\n', (5999, 6008), True, 'import numpy as np\n'), ((6083, 6108), 'joblib.load', 'load', (['"""data/model.joblib"""'], {}), "('data/model.joblib')\n", (6087, 6108), False, 'from joblib import dump, load\n'), ((6565, 6630), 'prepare_image.loadTrainData', 'loadTrainData', (['"""data/inputs/"""'], {'features': 'features', 'targets': 'targets'}), "('data/inputs/', features=features, targets=targets)\n", (6578, 6630), False, 'from prepare_image import loadTrainData, loadClassifyData\n'), ((6642, 6662), 'numpy.rollaxis', 'np.rollaxis', (['X', '(0)', '(4)'], {}), '(X, 0, 4)\n', (6653, 6662), True, 'import numpy as np\n'), ((6757, 6803), 'numpy.digitize', 'np.digitize', (['Y'], {'bins': '[0.1, 0.2, 0.3, 0.4, 0.5]'}), '(Y, bins=[0.1, 0.2, 0.3, 0.4, 0.5])\n', (6768, 6803), True, 'import numpy as np\n'), ((7015, 7069), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X', 'Y'], {'test_size': '(0.33)', 'random_state': '(0)'}), '(X, Y, test_size=0.33, random_state=0)\n', (7031, 7069), False, 'from sklearn.model_selection import train_test_split\n'), ((7336, 7359), 'sklearn.ensemble.RandomForestRegressor', 'RandomForestRegressor', ([], {}), '()\n', (7357, 7359), False, 'from sklearn.ensemble import RandomForestRegressor, RandomForestClassifier\n'), ((7378, 7433), 'sklearn.ensemble.RandomForestRegressor', 'RandomForestRegressor', ([], {'n_estimators': '(10)', 'random_state': '(42)'}), '(n_estimators=10, random_state=42)\n', (7399, 7433), False, 'from sklearn.ensemble import RandomForestRegressor, RandomForestClassifier\n'), ((7812, 7836), 'sklearn.ensemble.RandomForestClassifier', 'RandomForestClassifier', ([], {}), '()\n', (7834, 7836), False, 'from sklearn.ensemble import RandomForestRegressor, RandomForestClassifier\n'), ((7855, 7911), 'sklearn.ensemble.RandomForestClassifier', 'RandomForestClassifier', ([], {'n_estimators': '(10)', 'random_state': '(42)'}), '(n_estimators=10, random_state=42)\n', (7877, 7911), False, 'from sklearn.ensemble import RandomForestRegressor, RandomForestClassifier\n'), ((2340, 2360), 'json.load', 'json.load', (['json_file'], {}), '(json_file)\n', (2349, 2360), False, 'import json, csv\n'), ((2932, 2943), 'numpy.isnan', 'np.isnan', (['X'], {}), '(X)\n', (2940, 2943), True, 'import numpy as np\n'), ((2954, 2965), 'numpy.isnan', 'np.isnan', (['Y'], {}), '(Y)\n', (2962, 2965), True, 'import numpy as np\n'), ((6907, 6918), 'numpy.isnan', 'np.isnan', (['X'], {}), '(X)\n', (6915, 6918), True, 'import numpy as np\n'), ((6929, 6940), 'numpy.isnan', 'np.isnan', (['Y'], {}), '(Y)\n', (6937, 6940), True, 'import numpy as np\n'), ((8675, 8688), 'generate_raster.do_parse', 'do_parse', (['fld'], {}), '(fld)\n', (8683, 8688), False, 'from generate_raster import numpy_array_to_raster, NO_DATA, GDAL_DATA_TYPE, SPATIAL_REFERENCE_SYSTEM_WKID, GEOTIFF_DRIVER_NAME, do_parse\n'), ((8191, 8211), 'pathlib.Path', 'Path', (['"""data/inputs/"""'], {}), "('data/inputs/')\n", (8195, 8211), False, 'from pathlib import Path\n'), ((3663, 3690), 'os.walk', 'os.walk', (['"""data/satproduct/"""'], {}), "('data/satproduct/')\n", (3670, 3690), False, 'import os, sys, getopt, math\n'), ((5015, 5042), 'os.walk', 'os.walk', (['"""data/satproduct/"""'], {}), "('data/satproduct/')\n", (5022, 5042), False, 'import os, sys, getopt, math\n'), ((5830, 5857), 'os.walk', 'os.walk', (['"""data/satproduct/"""'], {}), "('data/satproduct/')\n", (5837, 5857), False, 'import os, sys, getopt, math\n'), ((8264, 8291), 'os.walk', 'os.walk', (['"""data/satproduct/"""'], {}), "('data/satproduct/')\n", (8271, 8291), False, 'import os, sys, getopt, math\n')]
# Loading packages here import sys import argparse import numpy as np # import skbio as sb # Use this for ANOSIM import pandas as pd # Use this for working with dataframes import os import networkx import scipy.stats as stats # import scipy.spatial.distance as distance # conda install scipy # from skbio.diversity import beta_diversity # for bray curtis conditioning from sklearn.decomposition import PCA # Use for PCA import matplotlib.pyplot as plt # Use this for plotting # from skbio.stats.distance import anosim import math import csv import minepy # pip install minepy import time import seaborn as sb global min_count global window_size global outdir global disjoint global connectedness global detailed_ def remove_min_count(df, min_count): """ Function remove_min_count: This function removes data that is all zeros in a column best used once merging has taken place to get rid of all features that are zero in both conditions :param df: @type pandas dataframe: The data to remove counts below min_count :return: @type pandas dataframe: The resulting dataframe after removal """ return (df.loc[:, (df > min_count).any(axis=0)]) def add_one_smoothing(df): """ Function add_one_smoothing: Add one accounts for the possibility of unseen events (0s) occurring in the future. :param df: @type pandas dataframe: The data to smooth :return: @type pandas dataframe: The smoothed data """ temp = df.copy() + 1 temp = temp / temp.sum() return temp def bray_curtis(df): """ Function bray_curtis: Performs a bray-curtis dissimilarity :param df: @type pandas dataframe: The data to do the dissimilarity on :return: @type pandas dataframe: The bray-curtis'ed data Computes the Bray-Curtis distance between two 1-D arrays. """ temp = df.copy() ids = df.columns.values.tolist() bc = beta_diversity("braycurtis", temp.transpose(), ids) bc_df = pd.DataFrame(data=bc.data, index=bc.ids, columns=bc.ids) return bc_df def hellinger(df): """ Function hellinger: The hellinger transformation deals with the double zero problem in ecology. The hellinger transformation is the square root of the result of the current row divided by the sum of all rows. This is done for each element in the dataframe. :param df: @type pandas dataframe: The data to do the transformation on. :return: @type pandas dataframe: A dataframe of the hellinger transformed data. """ temp = df.copy() hellinger_data = np.sqrt(temp.div(temp.sum(axis=1), axis=0)) # Hellinger transformation return hellinger_data def condition(df, cond_type): """ Function condition: A preprocessing step to condition the data based on the type specidied :param data: @type pandas dataframe - The data to be conditioned :param cond_type: @type string - The type of conditioning to run. Valid values: add_one, hellinger :return: @type pandas dataframe - The conditioned dataframe. """ # print('conditioning type', cond_type) temp = df.copy() temp = temp.loc[(temp != 0).any(axis=1)] if cond_type == 'add_one': conditioned_data = add_one_smoothing(temp) elif cond_type == 'hellinger': conditioned_data = hellinger(temp) elif cond_type == 'bray_curtis': conditioned_data = bray_curtis(temp) else: conditioned_data = temp return conditioned_data def smooth(df, type): """ Function smooth: Smoothing function to filter out noise :param df: @type pandas dataframe: The data to be smoothed :param type: @type string: The type of smoothing to do (currently sliding_window is the only option) :return: @type pandas dataframe: A dataframe of the smoothed data """ temp = df.copy() if type == 'sliding_window': result = temp.rolling(window_size, min_periods=1, center=True).mean() else: result = temp return result def pca_abundance(df, num_pca_components=4, cond_type='hellinger'): """ Function pca_abundance: running PCA iteratively on the data, removing the highest/lowest abundance features (based on sorting of abundances array). The gradient is used to find the greatest change in inertia when features are removed. Then we select all the features up to that point. These are the most important features :param data: @type pandas dataframe: The data to run pca on :param num_pca_components: @type integer: The number of components to use for pca :param cond_type: @type string: The conditioning type to use for pca (eg. hellinger, add_one) :param smoothing_type: @type string: The type of smoothing to do on the dataframe of total eigenvalues found by PCA :return: important_features - a list of the most important features as found by running the PCA """ pca = PCA(n_components=num_pca_components) # Run a PCA with n components data = df.copy() # copy the data into a dataframe to manipulate eigen_df = pd.DataFrame() # create a dataframe to hold the eigenvalues from the pca abundances_arr = pd.unique(data.sum(axis=0)) # get the set of unique values abundances_arr = np.sort(abundances_arr)[::-1] # sort highest to lowest # now we want to loop through all the abundances and find those with the most variance # once we find those we'll have to match them back up to the features with those abundances # so that we can send back the list of sorted features for i in range(len(abundances_arr)): if len(abundances_arr) - i == num_pca_components: break conditioned_df = condition(data, cond_type) # condition data result = pca.fit(conditioned_df) # Run the PCA on the conditioned data here variance_arr = result.explained_variance_ratio_ # Output the variance associated with each eigenvector drop_list = list( data.columns[data.sum(axis=0) == abundances_arr[i]]) # Find all features with the current abundance components = result.components_ variance_df = pd.DataFrame(variance_arr, columns=[ str(abundances_arr[i])]).transpose() # Convert the eigenvalues to a data frame of OTU rows x N components # variance_df = pd.DataFrame(variance_arr).transpose() # Convert the eigenvalues to a data frame of OTU rows x N components eigen_df = eigen_df.append(variance_df) # Append to the eigenvalue df data.drop(drop_list, inplace=True, axis=1) # Drop all the features with the current abundance # You can only iterate over the number of features minus the number of components. if len(abundances_arr) - i == num_pca_components: break eigen_df['Total'] = eigen_df.sum(axis=1) # sum up the eigenvalues to get the total variance of all components # print('eigen df', eigen_df) total_eigen = eigen_df.copy().iloc[:, [-1]] total_eigen.sort_values(by='Total', ascending=0, inplace=True) # order the values in descending order, since we want to remove the highest eigenvalues # loop through each row and get the feature name and the abundance. # Match the feature name to the eigenvector variance from the total_eigen dataframe. # Then we'll return a dataframe with the feature as an index and the variance as the value ordered_features = pd.DataFrame(columns=['variance']) for index, row in df.sum(axis=0).iteritems(): if str(row) in total_eigen.index: # print('variance = ',total_eigen['Total'].loc[str(row)]) ordered_features.loc[index] = total_eigen['Total'].loc[str(row)] ordered_features.sort_values(by='variance', ascending=0, inplace=True) return ordered_features def pca_importance(df, num_pca_components=4, cond_type='hellinger'): """ Function pca_importance: running PCA and selecting the most important features as found by the eigenvectors. :param data: @type pandas dataframe: The data to run pca on :param num_pca_components: @type integer: The number of components to use for pca :param select_n: @type integer: The number of important features to return :param cond_type: @type string: The conditioning type to use for pca (eg. hellinger, add_one) :param smoothing_type: @type string: The type of smoothing to do on the dataframe of total eigenvalues found by PCA :return: ordered_features - a numpy array of the features ordered from most important to least, as found by running the PCA """ pca = PCA(n_components=num_pca_components) # Run a PCA with n components data = df.copy() # copy the data into a dataframe to manipulate conditioned_df = condition(data, cond_type) # condition data result = pca.fit(conditioned_df) # Run the PCA on the conditioned data here components = result.components_ # the eigenvectors/components eigenvectors = pd.DataFrame(components, columns=[data.columns]) abs_eigens = np.absolute(eigenvectors) # element wise absolute value to get rid of negatives variance = pd.DataFrame({'metric': abs_eigens.sum( axis=0)}) # sum up the components to get the amount of variance across all components for each feature variance['pca1'], variance['pca2'] = eigenvectors.iloc[0], eigenvectors.iloc[1] # order the features from largest to smallest to return as our sorted dataframe ordered_features = variance.sort_values(by='metric', ascending=0) # print('ordered_features columns', ordered_features.index.values[0]) if( type( ordered_features.index.values[0] ) is tuple ): # this means that a function has covereted indecis to sparse series, must convert this back to # a dense dataframe. This should be able to be removed after Qiime updates ordered_feature = pd.DataFrame(columns=["OTU","metric","pca1","pca2"]) for index, row in ordered_features.iterrows(): ordered_feature = ordered_feature.append( {"OTU": index[0], "metric": row["metric"], "pca1": row["pca1"], "pca2": row["pca2"] }, ignore_index=True ) ordered_feature = ordered_feature.set_index("OTU") return ordered_feature else: return ordered_features def pca_legendre(df, num_pca_components, cond_type='hellinger'): return 0 def abundance(df): data = df.copy() summed_vals = data.sum(axis=0) sorted_abundances = summed_vals.sort_values(ascending=0) return sorted_abundances def find_correlation(df, corr_type='spearman'): df_r = 0 data = df.copy() if corr_type == 'MIC': # the pstats output for the mic and tic are condensed 1D arrays # we need to turn the output into a 2D upper triangular matrix and then mirror it to get the # full correlation matrix micp, ticp = minepy.pstats(data.T, alpha=0.6, c=15, est="mic_approx") num_features = data.shape[1] tri = np.zeros((num_features, num_features)) tri[np.triu_indices(num_features, 1)] = micp full_corr = tri + tri.T df_r = pd.DataFrame(full_corr) df_r.columns = data.columns.values df_r.index = data.columns.values else: df_r = data.corr(corr_type) if isinstance(df_r, pd.DataFrame): df_r.fillna(0, inplace=True) # ugly hack to make the NAs go away, should work for sampling but not advisable df_r = df_r[(df_r != 0).any(axis=1)] df_r = df_r.loc[:, (df_r != 0).any(axis=0)] return df_r # this function returns the sorted centrality for a given centrality # given a dataframe organized as an adjacency matrix, build a graph and compute the centrality # return sorted centrality and the graph in networkx format def graph_centrality(df, cent_type='betweenness', keep_thresh=0.5, cond_type='add_one', corr_type='spearman', weighted=False, corr_dir='none', min_connected=0): """ :param df: @type pandas DataFrame :param cent_type: @type string - valid values: betweenness, degree, closeness, eigenvector :param keep_thresh: @type float - default 0.5 :param cond_type: @type: string - valid values: add_one, hellinger, bray_curtis :param corr_type: @type: string - valid values: spearman, kendall, pearson, MIC :param weighted: @type: boolean - True if you want to produce a graph with weighted edges, False otherwise :param corr_dir: @type: string - valid values: none, positive, negative :return: """ print('In Graph Centrality Function') data = df.copy() conditioned_df = condition(data, cond_type) # condition data w_corr_df = find_correlation(conditioned_df, corr_type) if corr_dir == 'positive': w_corr_df_b = 1 - w_corr_df.copy() # only keep strong positive correlations (small positive numbers) elif corr_dir == 'negative': w_corr_df_b = 1 + w_corr_df.copy() # only keep strong negative correlations (small negative numbers) else: w_corr_df_b = 1 - abs(w_corr_df.copy()) # keep both strong positive and negative correlations w_corr_df_b[ (w_corr_df_b >= 1 - keep_thresh)] = 1 # set anything greater than the threshold value to 1 so we can remove it. labels = list(w_corr_df_b.index) temp = abs(w_corr_df_b.copy()) temp.insert(0, 'var1', labels) if weighted == True: attr = 'weight' else: attr = 'edge' df_b = pd.melt(temp, 'var1', var_name='var2', value_name=attr) df_b = df_b.loc[((df_b[attr] <= 1 - keep_thresh) & (df_b[attr] >= 0.0)), :] # take only those edge pairs that are at or above the threshold df_g = networkx.from_pandas_edgelist(df_b, 'var1', 'var2', attr) # takes a list of valid edges # create a graphml file # graph_filename = "graph-{}.graphml".format(process_id) # networkx.write_graphml(df_g, os.path.join(outdir,graph_filename)) # draw and display the graph with labels # networkx.draw(df_g, with_labels=True) # networkx.draw(df_g) # pylab.show() # store the adjacency matrix in a pandas dataframe and then export it to a csv # if there isn't an adjacency matrix csv with this id, create a csv file # am = networkx.to_pandas_adjacency(df_g) # adjacency_filename = "adj_matrix-{}.csv".format(process_id) # am.to_csv(os.path.join(outdir,adjacency_filename)) # check to see if the graph is disjoint. If it is, we just want to return an empty dataframe # and stop the winnowing process num_subgraphs = networkx.number_connected_components(df_g) total_nodes = networkx.number_of_nodes(df_g) subgraphs = [ df_g.subgraph(c) for c in networkx.connected_components( df_g ) ] try: largest_subgraph = max(subgraphs, key=len) except ValueError: largest_subgraph = networkx.empty_graph() nodes_sg = networkx.number_of_nodes(largest_subgraph) print(f"total, {total_nodes}, largest, {nodes_sg}") if( nodes_sg <= 0 ): percent_connected = 0 else: percent_connected = nodes_sg/total_nodes*100 print(f"percent connected, {percent_connected}") global connectedness connectedness.append((nodes_sg, total_nodes, float(str(round(percent_connected, 2))))) print(f"connectedness, {connectedness}") if percent_connected == 0 or percent_connected < float(min_connected): print('graph under min connectedness... returning') disjoint = True return pd.DataFrame() else: if cent_type == 'betweenness': centrality = networkx.betweenness_centrality(largest_subgraph) elif cent_type == 'degree': centrality = networkx.degree_centrality(largest_subgraph) elif cent_type == 'closeness': centrality = networkx.closeness_centrality(largest_subgraph) elif cent_type == 'eigenvector': try: centrality = networkx.eigenvector_centrality(largest_subgraph) except: print('eigenvector failed to converge... returning') disjoint = True return pd.DataFrame() else: raise Exception("Error: No centrality type given. Must be either: betweenness, degree, closeness, or eigenvector.") centrality_df = pd.DataFrame.from_dict(centrality, orient='index') centrality_df.columns = ['metric'] if not centrality_df.empty: centrality_df = centrality_df[centrality_df.iloc[:, 0] > 0] if not centrality_df.empty: centrality_df.sort_values('metric', axis=0, ascending=False, inplace=True) '''fig = plt.figure() plt.hist(centrality_df, bins=20) plt.xlabel('Centrality') plt.ylabel('Frequency') plt.title('Graph Centrality Distribution') plt.tight_layout() #fig.savefig(os.path.join(outdir,'test.jpg')) plt.show()''' return centrality_df def selection(func, s_total, s_per_iter, df, *args): """ Function selection: does N loops of the metric before going to the evaluation step :param type: are we selecting features to remove or to retain :param N: the number of features for selection :return: not sure yet """ data = df.copy() feature_list = [] selected_df = pd.DataFrame() # the metric (func) returns a dataframe of the most important features # when we get back this dataframe, we need to select a specified number of features (select_per_iter) # until we select the total number of features desired (select_total) selected = 0 if s_total == 'all': select_total = len(data.columns) else: try: select_total = int(s_total) except: raise('not a valid select total value') if s_per_iter == 'all': select_per_iter = len(data.columns) else: try: select_per_iter = int(s_per_iter) except: raise('not a valid select per iteration value') # make sure they aren't trying to select more features per iter than total features select_per_iter = min(select_per_iter, select_total) select = select_per_iter for i in range(0, math.ceil(select_total / select_per_iter)): # call the metric with the current data sorted_df = func(data, *args) if not sorted_df.empty: if ((i + 1) * select_per_iter > select_total): select = select_total % selected # take the top n features returned by the metric top_features = sorted_df.iloc[:select].index.values selected_df = selected_df.append(sorted_df.iloc[:select]) selected += select # if this is the last time we're selecting features, # look at the metric value of last feature selected # and see if there were others in the list with the same # value. Include those too. if selected == select_total: last_row = selected_df.tail(1) last_feature = last_row.index.values[0] last_value = last_row.iloc[0]['metric'] same_vals = sorted_df[(sorted_df['metric'] == last_value) & (~sorted_df.index.isin(selected_df.index))] selected_df = selected_df.append(same_vals) # add to the list of features selected feature_list.extend(top_features) #remove the top features from the data frame data.drop(top_features.tolist(), axis=1, inplace=True) else: return selected_df results = selected_df return results def evaluation(func, *args): result = func(*args) return result def pca_inertia_eval(df, num_pca_components, cond_type, smoothing_type): """ Function pca_abundance: running PCA iteratively on the data, removing the highest/lowest abundance features (based on sorting of abundances array). The gradient is used to find the greatest change in inertia when features are removed. Then we select all the features up to that point. These are the most important features :param data: @type pandas dataframe: The data to run pca on :param num_pca_components: @type integer: The number of components to use for pca :param cond_type: @type string: The conditioning type to use for pca (eg. hellinger, add_one, bray_curtis) :param smoothing_type: @type string: The type of smoothing to do on the dataframe of total eigenvalues found by PCA :return: important_features - a list of the most important features as found by running the PCA """ pca = PCA(n_components=num_pca_components) # Run a PCA with n components data = df.copy() # copy the data into a dataframe to manipulate eigen_df = pd.DataFrame() # create a dataframe to hold the eigenvalues from the pca abundances_arr = pd.unique(data.sum(axis=0)) # get the set of unique values # ------------ QUESTION ---------- # if it's sorted from lowest to highest, it can't run the PCA on the four biggest abundances # so they aren't in the eigen_df dataframe, meaning they aren't added to the important OTU list # Should we always sort highest to lowest, or should I be creating the important_OTUS list differently? abundances_arr = np.sort(abundances_arr)[::-1] # sort highest to lowest for i in range(len(abundances_arr)): conditioned_df = condition(data, cond_type) # condition data result = pca.fit(conditioned_df) # Run the PCA on the conditioned data here variance_arr = result.explained_variance_ratio_ # Output the variance associated with each eigenvector drop_list = list(data.columns[data.sum(axis=0) == abundances_arr[i]]) # Find the top features variance_df = pd.DataFrame(variance_arr, columns=[ str(abundances_arr[i])]).transpose() # Convert the eigenvalues to a data frame of OTU rows x N components eigen_df = eigen_df.append(variance_df) # Append to the eigenvalue df data.drop(drop_list, inplace=True, axis=1) # Drop all the features with the current abundance # You can only iterate over the number of features minus the number of components. if len(abundances_arr) - i == num_pca_components: break eigen_df['Total'] = eigen_df.sum(axis=1) # sum up the eigenvalues to get the total variance of all components total_eigen = eigen_df.copy().iloc[:, [-1]] # sorted list to return total_eigen.sort_values(by='Total', ascending=0, inplace=True) # order the values in descending order, since we want to remove the highest eigenvalues # evaluation smoothed = smooth(total_eigen, smoothing_type) # then smooth the values using a sliding window # use the gradient function to find the greatest slope between two abundances # this is our max inertia and we will return features above that point gradient = abs(np.gradient(smoothed.values.flatten())) smoothed['Gradient'] = gradient maxGradient = smoothed['Gradient'].argmax() topAbundances = smoothed.loc[:maxGradient].index.values # get all the features that have the abundance totals selected important_features = [] for i in range(len(topAbundances)): important_features.extend(data.columns[data.sum(axis=0) == int(topAbundances[i])].values) # show the graph of the smoothed summed eigenvalues from running the PCA at each step. fig = plt.figure() ax = fig.add_subplot(111) smoothed['Total'].plot(kind='bar', title='Total Variation') ax.set_xticklabels([]) # plt.show() return important_features def kl_divergence(A, B, features, select_per_iter, cond_type): """ :param A: @type: pandas dataframe - data file 1 :param B: @type: pandas dataframe :param selected_features: @type - list :param select_per_iter: @type - int :return: @type list - the list of kl divergence values """ selected_features = list(features) # condition(data, cond_type) data1 = condition(A.sum(axis=0).transpose(), cond_type) # KL divergence requires that histograms are the same size so sum to remove differences in number of samples data2 = condition(B.sum(axis=0).transpose(), cond_type) num_features = len(selected_features) diverge_vals = [] feature_count = 0 select = select_per_iter for i in range(0, math.ceil(num_features / select_per_iter)): if ((i + 1) * select_per_iter > num_features): select = num_features % feature_count # need to drop the first 'select' features from the list selections = selected_features[:select] del selected_features[:select] data1.drop(selections, inplace=True) data2.drop(selections, inplace=True) if len(data1.shape) > 1: # if there is more than one dimension, flatten tempA = data1.values.flatten() else: tempA = data1.values if len(data2.shape) > 1: # if there is more than one dimension, flatten tempB = data2.values.flatten() else: tempB = data2.values feature_count += select kl_diverge = stats.entropy(tempA, tempB, 2.0) # find the KL-Divergence base 2 if kl_diverge > 1e50: kl_diverge = 1e50 diverge_vals.append(kl_diverge) # determine if the remaining histograms are more alike after elimination return diverge_vals def create_pca_plot(features ): data = features.copy() plt.figure() plt.scatter(data['pca1'], data['pca2']) plt.xlabel('Principle Component 1') plt.ylabel('Principle Component 2') plt.title('Scatter Plot of Principle Components 1 and 2') plt.tight_layout() plt.savefig(os.path.join(outdir, "pca_scatter.png")) # plt.show() def plot_graph_centrality(features, cond_type, corr_type, corr_dir, keep_thresh, weighted ): data = features.copy() plt.figure() # create a graph of the edges/nodes using the same centrality type as used to select the features # this is the top25 file stuff conditioned_df = condition(data, cond_type) # condition data w_corr_df = find_correlation(conditioned_df, corr_type) if corr_dir == 'positive': w_corr_df_b = 1 - w_corr_df.copy() # only keep strong positive correlations (small positive numbers) elif corr_dir == 'negative': w_corr_df_b = 1 + w_corr_df.copy() # only keep strong negative correlations (small negative numbers) else: w_corr_df_b = 1 - abs(w_corr_df.copy()) # keep both strong positive and negative correlations w_corr_df_b[ (w_corr_df_b >= 1 - keep_thresh)] = 1 # set anything greater than the threshold value to 1 so we can remove it. labels = list(w_corr_df_b.index) temp = abs(w_corr_df_b.copy()) temp.insert(0, 'var1', labels) if weighted == True: attr = 'weight' else: attr = 'edge' df_b = pd.melt(temp, 'var1', var_name='var2', value_name=attr) df_b = df_b.loc[((df_b[attr] <= 1 - keep_thresh) & (df_b[attr] > 0.0)), :] # take only those edge pairs that made the cut df_g = networkx.from_pandas_edgelist(df_b, 'var1', 'var2', attr) # takes a list of valid edges networkx.write_graphml(df_g, os.path.join(outdir, "graph_network.graphml") ) networkx.draw(df_g, node_color='dodgerblue', edge_color='dimgrey', with_labels=True) plt.savefig(os.path.join(outdir, f"graph_network.png")) create_ecological_network(df_b.copy(), data.copy()) # plt.show() def create_ecological_network(df, data ): feature_names = data.columns metric_matrix = pd.DataFrame(columns=feature_names, index=feature_names, dtype='float64') metric_matrix.fillna(value=0.0, inplace=True) for i in df.index: row = df.loc[i].tolist() metric_matrix.loc[row[0]][row[1]] = row[2] # print("Rows:0 "+str(row[0])+" Row:1 "+str(row[1])+" Row:2 "+str(row[2])+" Set Value: "+str(metric_matrix[row[0]][row[1]])) metric_matrix.to_csv(os.path.join(outdir, "Metric Network.csv")) if (detailed_): plt.figure() plt.title("Feature Metric Heatmap") plt.tight_layout() sb.heatmap(metric_matrix, annot=True, cmap=['Grey', 'Blue'], cbar=False) plt.savefig(fname=os.path.join(outdir, "metric_network.png"), format='png', dpi=600, bbox_inches='tight', papertype='ledger') def plot_feature_metric(features ): # x-axis is the OTU (feature) in ranked order # y-axis is the metric value data = features.copy() plt.figure() data['metric'].plot(style='.-') plt.xticks(np.arange(0, len(data['metric'])), data.index.values, rotation=45, ha='center') plt.xlabel('Feature Label') plt.ylabel('Metric Value') plt.title('Metric Value Per Feature') plt.tight_layout() plt.savefig(os.path.join(outdir, "metric_value.png")) # plt.show() def log_transfrom_balance(df, cond_type='add_one'): print("In the Log Transfom Balance Function") data = condition(df.copy(), cond_type) mertic_result = pd.DataFrame(columns=['OTU', 'metric']) for col in data.columns: k_pos = int(data[col].count() / 2) k_neg = int(data[col].count() / 2) # data[col]+=1 sum_k_pos_log = 0 sum_k_neg_log = 0 for j in range(0, k_pos): sum_k_pos_log += math.log(data[col][j]) sum_k_neg_log += math.log(data[col][j + k_pos]) balance = 1 / k_pos * sum_k_pos_log - 1 / k_neg * sum_k_neg_log mertic_result = mertic_result.append({'OTU': col, 'metric': balance}, ignore_index=True) mertic_result.set_index('OTU', inplace=True) return mertic_result def log_transfrom(df, cond_type='add_one'): print("In the log Transfom Function") conditioned = np.log(condition(df.copy(), cond_type)) return conditioned def main(ab_comp, dataframe1, dataframe2, metric_name, c_type, min_count, total_select, iteration_select, pca_components, smooth_type, window_size, centrality_type, keep_threshold, correlation, weighted, corr_prop, evaluation_type, min_connected, detailed=False ): t_start = time.perf_counter() global detailed_ # Using global since this will not change and passing detailed_ to all methods will be confusing detailed_ = detailed # read the file(s) into a pandas dataframe and condition it dataframe1.reset_index( drop=True, inplace=True ) dataframe1.fillna(0, inplace=True) global disjoint disjoint = False global outdir outdir = f"{os.path.dirname(os.path.realpath(__file__))}/output/{metric_name}_{correlation}_{str(keep_threshold)}_{centrality_type}_{dataframe1.name}" resultsOutdir = f"{os.path.dirname(os.path.realpath(__file__))}/output" # allows for cleaner execution and use of relative paths os.makedirs(outdir, exist_ok=True) global connectedness connectedness = [] # set up the metric variables and the file names if ab_comp: metric_header = ["ab_comp", "dataframe1", "dataframe2", "metric", "centrality", "total select", "iteration select", "min count", "smooth type", "conditioning", "keep threshold", "correlation", "weighted", "correlation property", "min connected", "run time" ] metric_params = [ab_comp, dataframe1.name, dataframe2.name, metric_name, centrality_type, total_select, iteration_select, min_count, smooth_type, c_type, keep_threshold, correlation, weighted, corr_prop, min_connected] eval_params = [ab_comp, dataframe1.name, dataframe2.name, evaluation, c_type, total_select, iteration_select] dataframe2.fillna(0, inplace=True) data_file = pd.concat([dataframe2, dataframe1]) if( detailed_ ): metric_filename = f"{dataframe1.name}-{dataframe2.name}-results.csv" abundance_filename = f"{dataframe1.name}-{dataframe2.name}-abundances.csv" else: metric_header = ["ab_comp", "dataframe1", "metric", "centrality", "total select", "iteration select", "min count", "smooth type", "conditioning", "keep threshold", "correlation", "weighted", "correlation property", "run time" ] metric_params = [ab_comp, dataframe1.name, metric_name, centrality_type, total_select, iteration_select, min_count, smooth_type, c_type, keep_threshold, correlation, weighted, corr_prop] eval_params = [ab_comp, dataframe1.name, evaluation, c_type, total_select, iteration_select] data_file = dataframe1 if( detailed_ ): metric_filename = f"{dataframe1.name}-importantFeatures.csv" abundance_filename = f"{dataframe1.name}-abundances.csv" if min_count != -1: data = remove_min_count(data_file, min_count) else: data = data_file # log_transfrom(data) # run the metric selection step to return the important features important_features = pd.DataFrame() if metric_name == 'graph_centrality': metric = graph_centrality important_features = selection(metric, total_select, iteration_select, data, centrality_type, keep_threshold, c_type, correlation, weighted, corr_prop, min_connected) elif metric_name == 'pca_importance': metric = pca_importance important_features = selection(metric, total_select, iteration_select, data, pca_components, c_type) elif metric_name == 'log_transform': metric = graph_centrality important_features = selection(metric, total_select, iteration_select, log_transfrom(data, c_type), centrality_type, keep_threshold, c_type, correlation, weighted, corr_prop, min_connected) # print("Printing Log Transformed Important Features") # print(important_features) t_end = time.perf_counter() runtime = t_end - t_start metric_params.append(runtime) # add the abundance totals to the resulting dataframe and create a list of the important feature names important_features['abundances'] = data[important_features.index.values].sum(axis=0) #add abundances to the df important_feature_list = list(important_features.index.values) #create a dataframe with the abundances of the features determined as 'important' feature_abundances = data[important_feature_list] if important_features.empty: important_features.loc[1] = 'Warning: No features returned.' if disjoint: important_features.loc[2] = 'Graph is disjoint' # elif naming_file: # important_features = name_imp_features(important_features, naming_file) # feature_abundances = name_feature_list(feature_abundances, naming_file) # Create graphs if wanted if detailed_: # plot_metric plot_feature_metric(important_features ) if detailed_ and (metric == pca_importance or metric == pca_abundance): # plot_pca create_pca_plot(important_features ) if detailed_ and metric == graph_centrality: # graph centrality plot_graph_centrality(feature_abundances, c_type, correlation, corr_prop, keep_threshold, weighted ) # # create csv files for all the outputs. # # add the metric information to the important features and append to the metric results dataframe feature_row = metric_params + important_feature_list metric_header.extend( range( 1, abs( len(feature_row) - len(metric_header) ) +1 )) feature_df = pd.DataFrame( [feature_row], columns=metric_header) # format list into data frame before output # get the abundances for each of the important features and write those to a new file # print('final important features', important_features) if( detailed_ ): # if files exist just append row to them, else want to keep the headers metric_path = os.path.join(outdir, f"metric_results.csv") if( os.path.exists( metric_path )): with open( metric_path, 'a') as f: writer = csv.writer(f) writer.writerow(feature_row) else: feature_df.to_csv( metric_path, index=False ) # rewrite these since it's entire output important_features.to_csv(os.path.join(outdir, metric_filename)) feature_abundances.to_csv(os.path.join(outdir, abundance_filename), index=False) if( ab_comp ): param_dict = {'ab_comp': ab_comp, 'dataframe1': dataframe1.name, 'dataframe2': dataframe2.name, 'metric_name': metric_name, 'c_type': c_type, 'min_count': min_count, 'total_select': total_select, 'iteration_select': iteration_select, 'pca_components': pca_components, 'smooth_type': smooth_type, 'window_size': window_size, 'centrality_type': centrality_type, 'keep_threshold': keep_threshold, 'correlation': correlation, 'weighted': weighted, 'corr_prop': corr_prop, 'evaluation_type': evaluation_type, 'runtime': runtime, 'min_connected': min_connected, 'connectedness': connectedness} else: param_dict = {'ab_comp': ab_comp, 'dataframe1': dataframe1.name, 'dataframe2': "", 'metric_name': metric_name, 'c_type': c_type, 'min_count': min_count, 'total_select': total_select, 'iteration_select': iteration_select, 'pca_components': pca_components, 'smooth_type': smooth_type, 'window_size': window_size, 'centrality_type': centrality_type, 'keep_threshold': keep_threshold, 'correlation': correlation, 'weighted': weighted, 'corr_prop': corr_prop, 'evaluation_type': evaluation_type, 'runtime': runtime, 'min_connected': min_connected, 'connectedness': connectedness} if( detailed_ ): parameter_df = pd.DataFrame(list(param_dict.items()), columns=['Parameter', 'Values']) param_filename = f'parameter_list.csv' parameter_df.to_csv(os.path.join(outdir, param_filename)) # precautionary re-index of files feature_df.reset_index( drop=True, inplace=True ) important_features.reset_index( drop=True, inplace=True ) feature_abundances.reset_index( drop=True, inplace=True ) return ( feature_df, important_features, feature_abundances ) # graph information loss, kl outlier divergence. # % of total information loss since removal has occurred. or look at inflection point and how far away your N otus are from that. # front end takes in a file parses each line to set the selection parameters. # for each selection parameter, put the output files into a folder. # Then output the folder at the end.
[ "matplotlib.pyplot.title", "numpy.absolute", "seaborn.heatmap", "matplotlib.pyplot.figure", "networkx.connected_components", "networkx.closeness_centrality", "networkx.from_pandas_edgelist", "networkx.empty_graph", "networkx.degree_centrality", "matplotlib.pyplot.tight_layout", "os.path.join", ...
[((1953, 2009), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': 'bc.data', 'index': 'bc.ids', 'columns': 'bc.ids'}), '(data=bc.data, index=bc.ids, columns=bc.ids)\n', (1965, 2009), True, 'import pandas as pd\n'), ((4881, 4917), 'sklearn.decomposition.PCA', 'PCA', ([], {'n_components': 'num_pca_components'}), '(n_components=num_pca_components)\n', (4884, 4917), False, 'from sklearn.decomposition import PCA\n'), ((5033, 5047), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (5045, 5047), True, 'import pandas as pd\n'), ((7398, 7432), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': "['variance']"}), "(columns=['variance'])\n", (7410, 7432), True, 'import pandas as pd\n'), ((8573, 8609), 'sklearn.decomposition.PCA', 'PCA', ([], {'n_components': 'num_pca_components'}), '(n_components=num_pca_components)\n', (8576, 8609), False, 'from sklearn.decomposition import PCA\n'), ((8944, 8992), 'pandas.DataFrame', 'pd.DataFrame', (['components'], {'columns': '[data.columns]'}), '(components, columns=[data.columns])\n', (8956, 8992), True, 'import pandas as pd\n'), ((9011, 9036), 'numpy.absolute', 'np.absolute', (['eigenvectors'], {}), '(eigenvectors)\n', (9022, 9036), True, 'import numpy as np\n'), ((13444, 13499), 'pandas.melt', 'pd.melt', (['temp', '"""var1"""'], {'var_name': '"""var2"""', 'value_name': 'attr'}), "(temp, 'var1', var_name='var2', value_name=attr)\n", (13451, 13499), True, 'import pandas as pd\n'), ((13668, 13725), 'networkx.from_pandas_edgelist', 'networkx.from_pandas_edgelist', (['df_b', '"""var1"""', '"""var2"""', 'attr'], {}), "(df_b, 'var1', 'var2', attr)\n", (13697, 13725), False, 'import networkx\n'), ((14540, 14582), 'networkx.number_connected_components', 'networkx.number_connected_components', (['df_g'], {}), '(df_g)\n', (14576, 14582), False, 'import networkx\n'), ((14601, 14631), 'networkx.number_of_nodes', 'networkx.number_of_nodes', (['df_g'], {}), '(df_g)\n', (14625, 14631), False, 'import networkx\n'), ((14865, 14907), 'networkx.number_of_nodes', 'networkx.number_of_nodes', (['largest_subgraph'], {}), '(largest_subgraph)\n', (14889, 14907), False, 'import networkx\n'), ((17300, 17314), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (17312, 17314), True, 'import pandas as pd\n'), ((20631, 20667), 'sklearn.decomposition.PCA', 'PCA', ([], {'n_components': 'num_pca_components'}), '(n_components=num_pca_components)\n', (20634, 20667), False, 'from sklearn.decomposition import PCA\n'), ((20783, 20797), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (20795, 20797), True, 'import pandas as pd\n'), ((23494, 23506), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (23504, 23506), True, 'import matplotlib.pyplot as plt\n'), ((25570, 25582), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (25580, 25582), True, 'import matplotlib.pyplot as plt\n'), ((25587, 25626), 'matplotlib.pyplot.scatter', 'plt.scatter', (["data['pca1']", "data['pca2']"], {}), "(data['pca1'], data['pca2'])\n", (25598, 25626), True, 'import matplotlib.pyplot as plt\n'), ((25631, 25666), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Principle Component 1"""'], {}), "('Principle Component 1')\n", (25641, 25666), True, 'import matplotlib.pyplot as plt\n'), ((25671, 25706), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Principle Component 2"""'], {}), "('Principle Component 2')\n", (25681, 25706), True, 'import matplotlib.pyplot as plt\n'), ((25711, 25768), 'matplotlib.pyplot.title', 'plt.title', (['"""Scatter Plot of Principle Components 1 and 2"""'], {}), "('Scatter Plot of Principle Components 1 and 2')\n", (25720, 25768), True, 'import matplotlib.pyplot as plt\n'), ((25773, 25791), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (25789, 25791), True, 'import matplotlib.pyplot as plt\n'), ((25992, 26004), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (26002, 26004), True, 'import matplotlib.pyplot as plt\n'), ((27007, 27062), 'pandas.melt', 'pd.melt', (['temp', '"""var1"""'], {'var_name': '"""var2"""', 'value_name': 'attr'}), "(temp, 'var1', var_name='var2', value_name=attr)\n", (27014, 27062), True, 'import pandas as pd\n'), ((27212, 27269), 'networkx.from_pandas_edgelist', 'networkx.from_pandas_edgelist', (['df_b', '"""var1"""', '"""var2"""', 'attr'], {}), "(df_b, 'var1', 'var2', attr)\n", (27241, 27269), False, 'import networkx\n'), ((27386, 27474), 'networkx.draw', 'networkx.draw', (['df_g'], {'node_color': '"""dodgerblue"""', 'edge_color': '"""dimgrey"""', 'with_labels': '(True)'}), "(df_g, node_color='dodgerblue', edge_color='dimgrey',\n with_labels=True)\n", (27399, 27474), False, 'import networkx\n'), ((27702, 27775), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': 'feature_names', 'index': 'feature_names', 'dtype': '"""float64"""'}), "(columns=feature_names, index=feature_names, dtype='float64')\n", (27714, 27775), True, 'import pandas as pd\n'), ((28637, 28649), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (28647, 28649), True, 'import matplotlib.pyplot as plt\n'), ((28785, 28812), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Feature Label"""'], {}), "('Feature Label')\n", (28795, 28812), True, 'import matplotlib.pyplot as plt\n'), ((28817, 28843), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Metric Value"""'], {}), "('Metric Value')\n", (28827, 28843), True, 'import matplotlib.pyplot as plt\n'), ((28848, 28885), 'matplotlib.pyplot.title', 'plt.title', (['"""Metric Value Per Feature"""'], {}), "('Metric Value Per Feature')\n", (28857, 28885), True, 'import matplotlib.pyplot as plt\n'), ((28890, 28908), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (28906, 28908), True, 'import matplotlib.pyplot as plt\n'), ((29153, 29192), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': "['OTU', 'metric']"}), "(columns=['OTU', 'metric'])\n", (29165, 29192), True, 'import pandas as pd\n'), ((30264, 30283), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (30281, 30283), False, 'import time\n'), ((30944, 30978), 'os.makedirs', 'os.makedirs', (['outdir'], {'exist_ok': '(True)'}), '(outdir, exist_ok=True)\n', (30955, 30978), False, 'import os\n'), ((33186, 33200), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (33198, 33200), True, 'import pandas as pd\n'), ((34131, 34150), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (34148, 34150), False, 'import time\n'), ((35784, 35834), 'pandas.DataFrame', 'pd.DataFrame', (['[feature_row]'], {'columns': 'metric_header'}), '([feature_row], columns=metric_header)\n', (35796, 35834), True, 'import pandas as pd\n'), ((5210, 5233), 'numpy.sort', 'np.sort', (['abundances_arr'], {}), '(abundances_arr)\n', (5217, 5233), True, 'import numpy as np\n'), ((9846, 9901), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': "['OTU', 'metric', 'pca1', 'pca2']"}), "(columns=['OTU', 'metric', 'pca1', 'pca2'])\n", (9858, 9901), True, 'import pandas as pd\n'), ((10869, 10925), 'minepy.pstats', 'minepy.pstats', (['data.T'], {'alpha': '(0.6)', 'c': '(15)', 'est': '"""mic_approx"""'}), "(data.T, alpha=0.6, c=15, est='mic_approx')\n", (10882, 10925), False, 'import minepy\n'), ((10977, 11015), 'numpy.zeros', 'np.zeros', (['(num_features, num_features)'], {}), '((num_features, num_features))\n', (10985, 11015), True, 'import numpy as np\n'), ((11117, 11140), 'pandas.DataFrame', 'pd.DataFrame', (['full_corr'], {}), '(full_corr)\n', (11129, 11140), True, 'import pandas as pd\n'), ((15473, 15487), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (15485, 15487), True, 'import pandas as pd\n'), ((16293, 16343), 'pandas.DataFrame.from_dict', 'pd.DataFrame.from_dict', (['centrality'], {'orient': '"""index"""'}), "(centrality, orient='index')\n", (16315, 16343), True, 'import pandas as pd\n'), ((18200, 18241), 'math.ceil', 'math.ceil', (['(select_total / select_per_iter)'], {}), '(select_total / select_per_iter)\n', (18209, 18241), False, 'import math\n'), ((21307, 21330), 'numpy.sort', 'np.sort', (['abundances_arr'], {}), '(abundances_arr)\n', (21314, 21330), True, 'import numpy as np\n'), ((24450, 24491), 'math.ceil', 'math.ceil', (['(num_features / select_per_iter)'], {}), '(num_features / select_per_iter)\n', (24459, 24491), False, 'import math\n'), ((25240, 25272), 'scipy.stats.entropy', 'stats.entropy', (['tempA', 'tempB', '(2.0)'], {}), '(tempA, tempB, 2.0)\n', (25253, 25272), True, 'import scipy.stats as stats\n'), ((25808, 25847), 'os.path.join', 'os.path.join', (['outdir', '"""pca_scatter.png"""'], {}), "(outdir, 'pca_scatter.png')\n", (25820, 25847), False, 'import os\n'), ((27334, 27379), 'os.path.join', 'os.path.join', (['outdir', '"""graph_network.graphml"""'], {}), "(outdir, 'graph_network.graphml')\n", (27346, 27379), False, 'import os\n'), ((27488, 27530), 'os.path.join', 'os.path.join', (['outdir', 'f"""graph_network.png"""'], {}), "(outdir, f'graph_network.png')\n", (27500, 27530), False, 'import os\n'), ((28093, 28135), 'os.path.join', 'os.path.join', (['outdir', '"""Metric Network.csv"""'], {}), "(outdir, 'Metric Network.csv')\n", (28105, 28135), False, 'import os\n'), ((28166, 28178), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (28176, 28178), True, 'import matplotlib.pyplot as plt\n'), ((28187, 28222), 'matplotlib.pyplot.title', 'plt.title', (['"""Feature Metric Heatmap"""'], {}), "('Feature Metric Heatmap')\n", (28196, 28222), True, 'import matplotlib.pyplot as plt\n'), ((28231, 28249), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (28247, 28249), True, 'import matplotlib.pyplot as plt\n'), ((28258, 28330), 'seaborn.heatmap', 'sb.heatmap', (['metric_matrix'], {'annot': '(True)', 'cmap': "['Grey', 'Blue']", 'cbar': '(False)'}), "(metric_matrix, annot=True, cmap=['Grey', 'Blue'], cbar=False)\n", (28268, 28330), True, 'import seaborn as sb\n'), ((28925, 28965), 'os.path.join', 'os.path.join', (['outdir', '"""metric_value.png"""'], {}), "(outdir, 'metric_value.png')\n", (28937, 28965), False, 'import os\n'), ((31876, 31911), 'pandas.concat', 'pd.concat', (['[dataframe2, dataframe1]'], {}), '([dataframe2, dataframe1])\n', (31885, 31911), True, 'import pandas as pd\n'), ((36154, 36197), 'os.path.join', 'os.path.join', (['outdir', 'f"""metric_results.csv"""'], {}), "(outdir, f'metric_results.csv')\n", (36166, 36197), False, 'import os\n'), ((36210, 36237), 'os.path.exists', 'os.path.exists', (['metric_path'], {}), '(metric_path)\n', (36224, 36237), False, 'import os\n'), ((11028, 11060), 'numpy.triu_indices', 'np.triu_indices', (['num_features', '(1)'], {}), '(num_features, 1)\n', (11043, 11060), True, 'import numpy as np\n'), ((14676, 14711), 'networkx.connected_components', 'networkx.connected_components', (['df_g'], {}), '(df_g)\n', (14705, 14711), False, 'import networkx\n'), ((14827, 14849), 'networkx.empty_graph', 'networkx.empty_graph', ([], {}), '()\n', (14847, 14849), False, 'import networkx\n'), ((15562, 15611), 'networkx.betweenness_centrality', 'networkx.betweenness_centrality', (['largest_subgraph'], {}), '(largest_subgraph)\n', (15593, 15611), False, 'import networkx\n'), ((29448, 29470), 'math.log', 'math.log', (['data[col][j]'], {}), '(data[col][j])\n', (29456, 29470), False, 'import math\n'), ((29500, 29530), 'math.log', 'math.log', (['data[col][j + k_pos]'], {}), '(data[col][j + k_pos])\n', (29508, 29530), False, 'import math\n'), ((36529, 36566), 'os.path.join', 'os.path.join', (['outdir', 'metric_filename'], {}), '(outdir, metric_filename)\n', (36541, 36566), False, 'import os\n'), ((36602, 36642), 'os.path.join', 'os.path.join', (['outdir', 'abundance_filename'], {}), '(outdir, abundance_filename)\n', (36614, 36642), False, 'import os\n'), ((38446, 38482), 'os.path.join', 'os.path.join', (['outdir', 'param_filename'], {}), '(outdir, param_filename)\n', (38458, 38482), False, 'import os\n'), ((15673, 15717), 'networkx.degree_centrality', 'networkx.degree_centrality', (['largest_subgraph'], {}), '(largest_subgraph)\n', (15699, 15717), False, 'import networkx\n'), ((28357, 28399), 'os.path.join', 'os.path.join', (['outdir', '"""metric_network.png"""'], {}), "(outdir, 'metric_network.png')\n", (28369, 28399), False, 'import os\n'), ((30680, 30706), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (30696, 30706), False, 'import os\n'), ((30842, 30868), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (30858, 30868), False, 'import os\n'), ((36314, 36327), 'csv.writer', 'csv.writer', (['f'], {}), '(f)\n', (36324, 36327), False, 'import csv\n'), ((15782, 15829), 'networkx.closeness_centrality', 'networkx.closeness_centrality', (['largest_subgraph'], {}), '(largest_subgraph)\n', (15811, 15829), False, 'import networkx\n'), ((15917, 15966), 'networkx.eigenvector_centrality', 'networkx.eigenvector_centrality', (['largest_subgraph'], {}), '(largest_subgraph)\n', (15948, 15966), False, 'import networkx\n'), ((16111, 16125), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (16123, 16125), True, 'import pandas as pd\n')]
from numpy import exp, ones_like, zeros_like, arange, multiply, \ subtract, add, minimum, maximum, sign, c_, argmax, \ array, where, hstack, logical_not, sqrt from numpy import sum as npsum from numpy import abs as npabs from numpy import round as npround from scipy.integrate import trapz import matplotlib.pyplot as plt from math import isclose try: import typereduction isThereTypereduction = True except: isThereTypereduction = False def zero_mf(x, params=[]): """ All zero membership function. Parameters ---------- x : numpy (n,) shaped array The array like input x indicates the points from the universe of discourse, in which the membership function would be evaluated. params : List Additional parameters for the membership function, which is not needed for zero memebership function. Returns ------- ndarray Returns an array of membership values corresponding with the input. Examples -------- >>> x = linspace(0, 1, 201) >>> membership_value = zero_mf(x) """ return zeros_like(x) def singleton_mf(x, params): """ Singleton membership function. Parameters ---------- x : numpy (n,) shaped array The array like input x indicates the points from universe of discourse in which the membership function would be evaluated. params : List Additional parameters for the membership function. params[0] indicates singleton center and params[1] indicates singleton height. Returns ------- ndarray Returns membership values corresponding with the input. Notes ----- The singleton center, params[0], must be in the discretized universe of discourse. Examples -------- >>> x = linspace(0, 1, 201) >>> membership_value = singleton_mf(x, [0.5, 1]) """ return multiply(params[1], x == params[0]) def const_mf(x, params): """ Constant membership function. Parameters ---------- x : numpy (n,) shaped array The array like input x indicates the points from universe of discourse in which the membership function would be evaluated. params : List Additional parameters for the membership function. params[0] indicates constant membership function's height. Returns ------- ndarray Returns membership values corresponding with the input. Examples -------- >>> x = linspace(0, 1, 201) >>> membership_value = const_mf(x, [0.5]) """ return multiply(params[0], ones_like(x)) def tri_mf(x, params): """ Triangular membership function. Parameters ---------- x : numpy (n,) shaped array The array like input x indicates the points from universe of discourse in which the membership function would be evaluated. params : List Additional parameters for the membership function. The left end, center, right end, and height of the triangular membership function are indicated by params[0], params[1], params[2], and params[3], respectively. Returns ------- ndarray Returns membership values corresponding with the input. Examples -------- >>> x = linspace(0, 1, 201) >>> membership_value = tri_mf(x, [0.1, 0.3, 0.5, 1]) """ return minimum(1, maximum(0, ((params[3] * (x - params[0]) / (params[1] - params[0])) * (x <= params[1]) + \ ((params[3] * ((params[2] - x) / (params[2] - params[1]))) * (x > params[1]))) )) def rtri_mf(x, params): """ Right triangular membership function. Parameters ---------- x : numpy (n,) shaped array The array like input x indicates the points from universe of discourse in which the membership function would be evaluated. params : List Additional parameters for the membership function. The right end, center, and height of the triangular membership function are indicated by params[0], params[1], and params[2], respectively. Returns ------- ndarray Returns membership values corresponding with the input. Examples -------- >>> x = linspace(0, 1, 201) >>> membership_value = ltri_mf(x, [0.5, 0.2, 1]) """ return minimum(1, maximum(0, (params[2] * (x <= params[1]) + \ ((params[2] * ((params[0] - x) / (params[0] - params[1]))) * (x > params[1]))) )) def ltri_mf(x, params): """ Left triangular membership function. Parameters ---------- x : numpy (n,) shaped array The array like input x indicates the points from universe of discourse in which the membership function would be evaluated. params : List Additional parameters for the membership function. The left end, center, and height of the triangular membership function are indicated by params[0], params[1] and params[2], respectively. Returns ------- ndarray Returns membership values corresponding with the input. Examples -------- >>> x = linspace(0, 1, 201) >>> membership_value = rtri_mf(x, [0.3, 0.5, 1]) """ return minimum(1, maximum(0, ((params[2] * (x - params[0]) / (params[1] - params[0])) * (x <= params[1]) + \ (params[2] * (x > params[1])) ))) def trapezoid_mf(x, params): """ Trapezoidal membership function Parameters ---------- x : numpy (n,) shaped array The array like input x indicates the points from universe of discourse in which the membership function would be evaluated. params : List Additional parameters for the membership function. The left end, left center, right center, right end, and height of the trapezoidal membership function are indicated by params[0], params[1], params[2], params[3], and params[4], respectively. Returns ------- ndarray Returns membership values corresponding with the input. Examples -------- >>> x = linspace(0, 1, 201) >>> membership_value = trapezoid_mf(x, [0.1, 0.3, 0.5, 0.7, 1]) """ return minimum(1, maximum(0, ((((params[4] * ((x - params[0]) / (params[1] - params[0]))) * (x <= params[1])) + ((params[4] * ((params[3] - x) / (params[3] - params[2]))) * (x >= params[2]))) + (params[4] * ((x > params[1]) * (x < params[2])))) )) def gaussian_mf(x, params): """ Gaussian membership function Parameters ---------- x : numpy (n,) shaped array The array like input x indicates the points from universe of discourse in which the membership function would be evaluated. params : List Additional parameters for the membership function. The center, standard deviation, and height of the gaussian membership function are indicated by params[0], params[1], and params[2], respectively. Returns ------- ndarray Returns membership values corresponding with the input. Examples -------- >>> x = linspace(0, 1, 201) >>> membership_value = gaussian_mf(x, [0.5, 0.05, 1]) """ return params[2] * exp(-(((params[0] - x) ** 2) / (2 * params[1] ** 2))) def gauss_uncert_mean_umf(x, params): """ Gaussian with uncertain mean UMF Parameters ---------- x : numpy (n,) shaped array The array like input x indicates the points from universe of discourse in which the membership function would be evaluated. params : List Additional parameters for the membership function. The lower limit of mean, upper limit of mean, standard deviation, and height of the gaussian membership function are indicated by params[0], params[1], params[2], and params[3], respectively. Returns ------- ndarray Returns membership values corresponding with the input. Examples -------- >>> x = linspace(0, 1, 201) >>> membership_value = gauss_uncert_mean_umf(x, [0.3, 0.7, 0.05, 1]) """ return (((gaussian_mf(x, [params[0], params[2], params[3]]) * (x <= params[0])) + (gaussian_mf(x, [params[1], params[2], params[3]]) * (x >= params[1]))) + (params[3] * ((x > params[0]) * (x < params[1])))) def gauss_uncert_mean_lmf(x, params): """ Gaussian with uncertain mean LMF Parameters ---------- x : numpy (n,) shaped array The array like input x indicates the points from universe of discourse in which the membership function would be evaluated. params : List Additional parameters for the membership function. The lower limit of mean, upper limit of mean, standard deviation, and height of the gaussian membership function are indicated by params[0], params[1], params[2], and params[3], respectively. Returns ------- ndarray Returns membership values corresponding with the input. Examples -------- >>> x = linspace(0, 1, 201) >>> membership_value = gauss_uncert_mean_lmf(x, [0.3, 0.7, 0.2, 1]) """ return ((gaussian_mf(x, [params[0], params[2], params[3]]) * (x >= (params[0] + params[1]) / 2)) + (gaussian_mf(x, [params[1], params[2], params[3]]) * (x < (params[0] + params[1]) / 2))) def gauss_uncert_std_umf(x, params): """ Gaussian with uncertain standard deviation UMF Parameters ---------- x : numpy (n,) shaped array The array like input x indicates the points from universe of discourse in which the membership function would be evaluated. params : List Additional parameters for the membership function. The center, lower limit of std., upper limit of std., and height of the gaussian membership function are indicated by params[0], params[1], params[2], and params[3], respectively. Returns ------- ndarray Returns membership values corresponding with the input. Examples -------- >>> x = linspace(0, 1, 201) >>> membership_value = gauss_uncert_std_umf(x, [0.5, 0.2, 0.5, 1]) """ return gaussian_mf(x, [params[0], params[2], params[3]]) def gauss_uncert_std_lmf(x, params): """ Gaussian with uncertain standard deviation LMF Parameters ---------- x : numpy (n,) shaped array The array like input x indicates the points from universe of discourse in which the membership function would be evaluated. params : List Additional parameters for the membership function. The center, lower limit of std., upper limit of std., and height of the gaussian membership function are indicated by params[0], params[1], params[2], and params[3], respectively. Returns ------- ndarray Returns membership values corresponding with the input. Examples -------- >>> x = linspace(0, 1, 201) >>> membership_value = gauss_uncert_std_lmf(x, [0.5, 0.2, 0.5, 1]) """ return gaussian_mf(x, [params[0], params[1], params[3]]) def rgauss_uncert_std_umf(x, params): """ Right Gaussian with uncertain standard deviation UMF Parameters ---------- x : numpy (n,) shaped array The array like input x indicates the points from universe of discourse in which the membership function would be evaluated. params : List Additional parameters for the membership function. The center, lower limit of std., upper limit of std., and height of the gaussian membership function are indicated by params[0], params[1], params[2], and params[3], respectively. Returns ------- ndarray Returns membership values corresponding with the input. Examples -------- >>> x = linspace(0, 1, 201) >>> membership_value = rgauss_uncert_std_umf(x, [0.5, 0.2, 0.5, 1]) """ return (x < params[0]) * params[3] + gauss_uncert_std_umf(x, params) * (x >= params[0]) def rgauss_uncert_std_lmf(x, params): """ Right Gaussian with uncertain standard deviation LMF Parameters ---------- x : numpy (n,) shaped array The array like input x indicates the points from universe of discourse in which the membership function would be evaluated. params : List Additional parameters for the membership function. The center, lower limit of std., upper limit of std., and height of the gaussian membership function are indicated by params[0], params[1], params[2], and params[3], respectively. Returns ------- ndarray Returns membership values corresponding with the input. Examples -------- >>> x = linspace(0, 1, 201) >>> membership_value = rgauss_uncert_std_lmf(x, [0.5, 0.2, 0.5, 1]) """ return (x < params[0]) * params[3] + gauss_uncert_std_lmf(x, params) * (x >= params[0]) def lgauss_uncert_std_umf(x, params): """ Left Gaussian with uncertain standard deviation UMF Parameters ---------- x : numpy (n,) shaped array The array like input x indicates the points from universe of discourse in which the membership function would be evaluated. params : List Additional parameters for the membership function. The center, lower limit of std., upper limit of std., and height of the gaussian membership function are indicated by params[0], params[1], params[2], and params[3], respectively. Returns ------- ndarray Returns membership values corresponding with the input. Examples -------- >>> x = linspace(0, 1, 201) >>> membership_value = lgauss_uncert_std_umf(x, [0.5, 0.2, 0.5, 1]) """ return (x > params[0]) * params[3] + gauss_uncert_std_umf(x, params) * (x <= params[0]) def lgauss_uncert_std_lmf(x, params): """ Left Gaussian with uncertain standard deviation LMF Parameters ---------- x : numpy (n,) shaped array The array like input x indicates the points from universe of discourse in which the membership function would be evaluated. params : List Additional parameters for the membership function. The center, lower limit of std., upper limit of std., and height of the gaussian membership function are indicated by params[0], params[1], params[2], and params[3], respectively. Returns ------- ndarray Returns membership values corresponding with the input. Examples -------- >>> x = linspace(0, 1, 201) >>> membership_value = lgauss_uncert_std_lmf(x, [0.5, 0.2, 0.5, 1]) """ return (x > params[0]) * params[3] + gauss_uncert_std_lmf(x, params) * (x <= params[0]) def elliptic_mf(x, params): """ Elliptic membership function. Parameters ---------- x : numpy (n,) shaped array The array like input x indicates the points from universe of discourse in which the membership function would be evaluated. params : list Parameters of the elliptic membership function. The center, width, exponent, and height of the elliptic membership function are indicated by params[0], params[1], params[2], and params[3]. Returns ------- ndarray Returns membership values corresponding with the input. Examples -------- >>> x = linspace(0, 1, 201) >>> membership_value = eliptic_mf(x, [0.5, 0.25, 1.3, 1.]) """ to_evaluate = ((x <= params[0] + params[1]) * (params[0] - params[1] <= x)) x = x * to_evaluate + (params[0] + params[1]) * logical_not(to_evaluate) return params[3] * (1 - abs((x - params[0]) / params[1]) ** params[2]) ** (1. / params[2]) def semi_elliptic_mf(x, params): """ Semi-elliptic membership function. Parameters ---------- x : numpy (n,) shaped array The array like input x indicates the points from universe of discourse in which the membership function would be evaluated. params : list Parameters of the semi-elliptic membership function. The center, width, and height of the semi-elliptic membership function are indicated by params[0], params[1], and params[2]. Returns ------- ndarray Returns membership values corresponding with the input. Examples -------- >>> x = linspace(0, 1, 201) >>> membership_value = eliptic_mf(x, [0.5, 0.25, 1.3, 1.]) """ to_evaluate = ((x <= params[0] + params[1]) * (params[0] - params[1] <= x)) x = x * to_evaluate + (params[0] + params[1]) * logical_not(to_evaluate) return params[2] * npround(sqrt(abs(1 - ((params[0] - x) ** 2) / (params[1] ** 2))), decimals=6) def gbell_mf(x, params): """ Generalized bell shaped membership function. Parameters ---------- x : numpy (n,) shaped array The array like input x indicates the points from universe of discourse in which the membership function would be evaluated. params : list Parameters of the generalized bell shaped membership function. The a, b, and c values and height of the generalized bell shaped membership function formula are indicated by params[0], params[1], params[2], and params[3]. Returns ------- ndarray Returns membership values corresponding with the input. Examples -------- >>> x = linspace(0., 1., 201) >>> membership_value = gbell_mf(x, [0.1, 1., 0.5, 1.]) """ return params[3] / (1 + npabs((x - params[2]) / params[0]) ** (2 * params[1])) class T1FS: """ Type 1 Fuzzy Set (T1FS). Parameters ---------- Parameters of the constructor function: domain: numpy (n,) shaped array Indicates the universe of discourse dedicated to the T1FS. mf: Membership function params: List of parameters of the membership function Functions ---------- Functions defined in T1FS class: copy: Returns a copy of the T1FS. plot: Plots the T1FS. negation operator -: Returns the negated T1FS. Examples -------- >>> mySet = T1FS(linspace(0., 1., 100), trapezoid_mf, [0, 0.4, 0.6, 1., 1.]) >>> mySet.plot() """ def __init__(self, domain, mf=zero_mf, params=[]): self.domain = domain self.mf = mf self.params = params def repr(self): return "Type 1 fuzzy set with " + self.mf.__name__ + " as membership function " + \ "and " + str(self.params) + " as its parameters!" def copy(self): """ Copies the T1FS. Returns ------- T1FS Returns a copy of the T1FS. """ return T1FS(self.domain, self.mf, self.params) def __call__(self, x): return self.mf(x, self.params) def __neg__(self): mf = lambda x, params: subtract(1, self.mf(x, params)) return T1FS(self.domain, mf, params=self.params) def _CoG(self): int1 = trapz(self.domain * self(self.domain), self.domain) int2 = trapz(self(self.domain), self.domain) return int1 / int2 def defuzzify(self, method="CoG"): """ Defuzzifies the type 1 fuzzy set. Parameters ---------- method: str Must be one of the methods listed below: 1. CoG: Center of gravity Returns ------- float Defuzzified crisp output. """ if method == "CoG": return self._CoG() else: raise ValueError("The method" + method + " is not implemented yet!") def plot(self, title=None, legend_text=None, filename=None, ext="pdf", grid=True, xlabel="Domain", ylabel="Membership degree"): """ Plots the T1FS. Parameters ---------- title: str If it is set, it indicates the title which would be represented in the plot. If it is not set, the plot would not have a title. legend_text: str If it is set, it indicates the legend text which would be represented in the plot. If it is not set, the plot would not contain a legend. filename: str If it is set, the plot would be saved as a filename.ext file. ext: str Extension of the output file with pdf default value. grid: bool Grid on/off. xlabel: str Label of the x axis. ylabel: str Label of the y axis. Examples -------- >>> mySet = T1FS(linspace(0., 1., 100), trapezoid_mf, [0, 0.4, 0.6, 1., 1.]) >>> mySet.plot(filename="mySet") """ plt.figure() plt.plot(self.domain, self.mf(self.domain, self.params)) if legend_text is not None: plt.legend([legend_text]) if title is not None: plt.title(title) plt.xlabel(xlabel) plt.ylabel(ylabel) plt.grid(grid) if filename is not None: plt.savefig(filename + "." + ext, format=ext, dpi=300, bbox_inches="tight") plt.show() def T1_Emphasize(t1fs, m=2.): """ Function for creating emphasized T1FSs. Parameters ---------- t1fs : T1FS Type 1 fuzzy set to be emphasized. m : float, optional Emphasis degree. The default value is 2. Returns ------- emphasized : T1FS Emphasized type 1 fuzzy set. """ mf = lambda x, params : t1fs.mf(x, params) ** m emphasized = T1FS(t1fs.domain, mf, t1fs.params) return emphasized def T1FS_plot(*sets, title=None, legends=None, filename=None, ext="pdf", grid=True, xlabel="Domain", ylabel="Membership degree"): """ Plots multiple T1FSs together in the same figure. Parameters ---------- *sets: Multiple number of T1FSs which would be plotted. title: str If it is set, it indicates the title which would be represented in the plot. If it is not set, the plot would not have a title. legends: List of strs List of legend texts to be presented in plot. If it is not set, no legend would be in plot. filename: str If it is set, the plot would be saved as a filename.ext file. ext: str Extension of the output file with pdf default value. grid: bool Grid on/off. xlabel: str Label of the x axis. ylabel: str Label of the y axis. Examples -------- >>> domain = linspace(0., 1., 100) >>> t1fs1 = T1FS(domain, gaussian_mf, [0.33, 0.2, 1.]) >>> t1fs2 = T1FS(domain, gaussian_mf, [0.66, 0.2, 1.]) >>> T1FS_plot(t1fs1, t1fs2, title="Plotting T1FSs", legends=["First set", "Second set"]) """ plt.figure() for t1fs in sets: plt.plot(t1fs.domain, t1fs.mf(t1fs.domain, t1fs.params)) if legends is not None: plt.legend(legends) if title is not None: plt.title(title) plt.xlabel(xlabel) plt.ylabel(ylabel) plt.grid(grid) if filename is not None: plt.savefig(filename + "." + ext, format=ext, dpi=300, bbox_inches="tight") plt.show() def T1FS_AND(domain, t1fs1, t1fs2, t_norm): """ And operator for T1FSs. Parameters ---------- domain: numpy (n,) shaped array Indicates the universe of discourse dedicated to the output T1FS. t1fs1: T1FS First input of the and operator. t1fs2: T1FS Second input of the and operator. t_norm: function The t-norm function to be used. Returns ------- T1FS Returns the AND of the two input T1FSs. Examples -------- >>> domain = linspace(0., 1., 100) >>> t1fs1 = T1FS(domain, gaussian_mf, [0.33, 0.2, 1.]) >>> t1fs2 = T1FS(domain, gaussian_mf, [0.66, 0.2, 1.]) >>> t1fs3 = T1FS_AND(domain, t1fs1, t1fs2, min_t_norm) >>> t1fs3.plot() """ mf = lambda x, params: t_norm(t1fs1.mf(x, t1fs1.params), t1fs2.mf(x, t1fs2.params)) return T1FS(domain, mf) def T1FS_OR(domain, t1fs1, t1fs2, s_norm): """ Or operator for T1FSs. Parameters ---------- domain: numpy (n,) shaped array Indicates the universe of discourse dedicated to the output T1FS. t1fs1: T1FS First input of the or operator. t1fs2: T1FS Second input of the or operator. s_norm: function The s-norm function to be used. Returns ------- T1FS Returns the OR of the two input T1FSs. Examples -------- >>> domain = linspace(0., 1., 100) >>> t1fs1 = T1FS(domain, gaussian_mf, [0.33, 0.2, 1.]) >>> t1fs2 = T1FS(domain, gaussian_mf, [0.66, 0.2, 1.]) >>> t1fs3 = T1FS_OR(domain, t1fs1, t1fs2, max_s_norm) >>> t1fs3.plot() """ mf = lambda x, params: s_norm(t1fs1.mf(x, t1fs1.params), t1fs2.mf(x, t1fs2.params)) return T1FS(domain, mf) class T1Mamdani: """ Type 1 Mamdani Fuzzy Logic System. Parameters ---------- Parameters of the constructor function: engine="Product": str Inference engine of the type 1 Mamdani fuzzy logic system. This parameters is a string an can be one of the following items: Product, Minimum, Lukasiewicz, Zadeh, and Dienes-Rescher. defuzzification="CoG": str Defuzzification method of the system. When Lukasiewicz, Zadeh, and Dienes-Rescher inference engines are selected, the defuzzification method is center of the gravity by default. But for Product and Minimum inference engines, defuzzification can be selected among the methods CoG and CoA. Members ------- inputs: List of str List of the inputs names as str. outputs: List of str List of the outputs names as str. rules: List of tuples (antacedent, consequent) List of rules, which each rule is defined as a tuple (antecedent, consequent) Both antacedent and consequent are lists of tuples. Each tuple of this list shows assignement of a variable to a T1FS. First element of the tuple must be the variable name (input or output) as a str and the second element must be a T1FS. engine: str Indicates the engine selected by the user. defuzzification: str Indicates the defuzzification method selected by the user. Functions --------- add_input_variable: Adds an input variable to the inputs list of the T1FLS. add_output_variable: Adds an output variable to the outputs list of the T1FLS. add_rule: Adds a rule to the rules list of the T1FLS. copy: Returns a copy of the type 1 Mamdani fuzzy logic system. evaluate: Evaluates the T1 Mamdani FLS's output for the specified crisp input. The only input of the evaluate function is a dictionary in which the keys are input variable names as str and the values are the crisp value of inputs to be evaluated. The output of the evaluate function is depended on the method selected while constructing the class. For more information, please refer to the examples. """ def __init__(self, engine="Product", defuzzification="CoG"): self.inputs = [] self.outputs = [] self.rules = [] self.engine = engine if engine == "Product": self.evaluate = self._product_evaluate self.defuzzification = defuzzification elif engine == "Minimum": self.evaluate = self._minimum_evaluate self.defuzzification = defuzzification elif engine == "Lukasiewicz": self.evaluate = self._lukasiewicz_evaluate elif engine == "Zadeh": self.evaluate = self._zadeh_evaluate elif engine == "Dienes-Rescher": self.evaluate = self._dienes_rescher_evaluate else: raise ValueError("The " + engine + " fuzzy inference engine is not implemented yet!") def __repr__(self): return "Type 1 Mamadani fuzzy logic system with " + self.engine + " inference engine" + \ "and " + self.defuzzification + " defuzzification error!" def copy(self): o = T1Mamdani(self.engine, self.defuzzification) o.inputs = self.inputs.copy() o.outputs = self.outputs.copy() o.rules = self.rules.copy() return o def add_input_variable(self, name): """ Adds new input variable name. Parameters ---------- name: str Name of the new input variable as a str. """ self.inputs.append(name) def add_output_variable(self, name): """ Adds new output variable name. Parameters ---------- name: str Name of the new output variable as a str. """ self.outputs.append(name) def add_rule(self, antecedent, consequent): """ Adds a new rule to the rule base of the T1 Mamdani FLS. Parameters ---------- antecedent: List of tuples Antecedent is a list of tuples in which each tuple indicates assignement of a variable to a T1FS. First element of the tuple must be input variable name as str, and the second element of the tuple must be a T1FS. consequent: List of tuples Consequent is a list of tuples in which each tuple indicates assignement of a variable to a T1FS. First element of the tuple must be output variable name as str, and the second element of the tuple must be a T1FS. """ self.rules.append((antecedent, consequent)) def _CoG(self, B): C = {} D = {} for out in self.outputs: C[out] = T1FS(B[out][0].domain) for B_l in B[out]: C[out] = T1FS_OR(B_l.domain, C[out], B_l, max_s_norm) D[out] = C[out].defuzzify() return C, D def _CoA(self, B): D = {} for out in self.outputs: a = 0. b = 0. for B_l in B[out]: tmp = B_l.defuzzify() a += tmp * B_l(tmp) b += B_l(tmp) D[out] = a / b return D def _product_evaluate(self, inputs): B = {out: [] for out in self.outputs} for rule in self.rules: f = 1. for input_statement in rule[0]: f = f * input_statement[1].mf(inputs[input_statement[0]], input_statement[1].params) for consequent in rule[1]: B_l = T1FS_AND(consequent[1].domain, T1FS(consequent[1].domain, const_mf, [f]), consequent[1], product_t_norm) B[consequent[0]].append(B_l) if self.defuzzification == "CoG": return self._CoG(B) elif self.defuzzification == "CoA": return self._CoA(B) else: raise ValueError("The " + self.defuzzification + \ " defuzzification method is not implemented yet!") def _minimum_evaluate(self, inputs): B = {out: [] for out in self.outputs} for rule in self.rules: f = 1. for input_statement in rule[0]: f = min_t_norm(f, input_statement[1].mf(inputs[input_statement[0]], input_statement[1].params)) for consequent in rule[1]: B_l = T1FS_AND(consequent[1].domain, T1FS(consequent[1].domain, const_mf, [f]), consequent[1], min_t_norm) B[consequent[0]].append(B_l) if self.defuzzification == "CoG": return self._CoG(B) elif self.defuzzification == "CoA": return self._CoA(B) else: raise ValueError("The " + self.defuzzification + \ " defuzzification method is not implemented yet!") def _lukasiewicz_evaluate(self, inputs): B = {out: [] for out in self.outputs} for rule in self.rules: f = 1. for input_statement in rule[0]: f = min_t_norm(f, input_statement[1].mf(inputs[input_statement[0]], input_statement[1].params)) for consequent in rule[1]: mf = lambda x, params: 1. - f + consequent[1].mf(x, consequent[1].params) B_l = T1FS(consequent[1].domain, mf) B[consequent[0]].append(B_l) C = {} D = {} for out in self.outputs: C[out] = T1FS(B[out][0].domain, const_mf, [1]) for B_l in B[out]: C[out] = T1FS_AND(B_l.domain, C[out], B_l, min_t_norm) D[out] = C[out].defuzzify() return C, D def _zadeh_evaluate(self, inputs): B = {out: [] for out in self.outputs} for rule in self.rules: f = 1. for input_statement in rule[0]: f = min_t_norm(f, input_statement[1].mf(inputs[input_statement[0]], input_statement[1].params)) for consequent in rule[1]: mf = lambda x, params: min_t_norm(f, consequent[1].mf(x, consequent[1].params)) B_l = T1FS_OR(consequent[1].domain, T1FS(consequent[1].domain, const_mf, [1 - f]), T1FS(consequent[1].domain, mf), max_s_norm) B[consequent[0]].append(B_l) C = {} D = {} for out in self.outputs: C[out] = T1FS(B[out][0].domain, const_mf, [1]) for B_l in B[out]: C[out] = T1FS_AND(B_l.domain, C[out], B_l, min_t_norm) D[out] = C[out].defuzzify() return C, D def _dienes_rescher_evaluate(self, inputs): B = {out: [] for out in self.outputs} for rule in self.rules: f = 1. for input_statement in rule[0]: f = min_t_norm(f, input_statement[1].mf(inputs[input_statement[0]], input_statement[1].params)) for consequent in rule[1]: B_l = T1FS_OR(consequent[1].domain, T1FS(consequent[1].domain, const_mf, [1 - f]), consequent[1], max_s_norm) B[consequent[0]].append(B_l) C = {} D = {} for out in self.outputs: C[out] = T1FS(B[out][0].domain, const_mf, [1]) for B_l in B[out]: C[out] = T1FS_AND(B_l.domain, C[out], B_l, min_t_norm) D[out] = C[out].defuzzify() return C, D class T1TSK: """ Type 1 TSK Fuzzy Logic System. Parameters ---------- Parameters of the constructor function: The constructor function of the T1TSK class has no parameters. Members ------- inputs: List of str List of the inputs names as str. outputs: List of str List of the outputs names as str. rules: List of tuples (antacedent, consequent) List of rules, which each rule is defined as a tuple (antecedent, consequent) Functions --------- add_input_variable: Adds an input variable to the inputs list of the T1 TSK FLS. add_output_variable: Adds an output variable to the outputs list of the T1 TSK FLS. add_rule: Adds a rule to the rules list of the T1 TSK FLS. copy: Returns a copy of the T1 TSK FLS. evaluate: Evaluates the T1 TSK FLS based on the crisp inputs given by the user. """ def __init__(self): self.inputs = [] self.outputs = [] self.rules = [] def __repr__(self): return "Type 1 TSK fuzzy logic system!" def copy(self): """ Returns a copy of the IT2FLS. """ o = T1TSK() o.inputs = self.inputs.copy() o.outputs = self.outputs.copy() o.rules = self.rules.copy() return o def add_input_variable(self, name): """ Adds new input variable name. Parameters ---------- name: str Name of the new input variable as a str. """ self.inputs.append(name) def add_output_variable(self, name): """ Adds new output variable name. Parameters ---------- name: str Name of the new output variable as a str. """ self.outputs.append(name) def add_rule(self, antecedent, consequent): """ Adds new rule to the rule base of the T1 TSK FLS. Parameters ---------- antecedent: List of tuples Antecedent is a list of tuples in which each tuple indicates assignement of a variable to a T1FS. First element of the tuple must be input variable name as str, and the second element of the tuple must be a T1FS. consequent: List of tuples Consequent is a list of tuples in which each tuple indicates assignement of a variable to an output state. First element of the tuple must be output vriable name as str, and the second element of the tuple must be a callable object. """ self.rules.append((antecedent, consequent)) def evaluate(self, inputs, params): """ Evaluates the T1 TSK FLS based on the crisp inputs given by the user. Parameters ---------- inputs: dictionary Inputs is a dictionary, which the keys are input variable names as str and the values are the crisp value of the inputs to be evaluated. params: tuple This tuple is the parameters of the functions assigned to the consequents of the system rules. Returns ------- O: dictionary The output is a dictionary, which the keys are output variable names as str and the values are the crisp output of the system. """ F = [] B = {out: 0. for out in self.outputs} for rule in self.rules: f = 1. for input_statement in rule[0]: f *= input_statement[1].mf(inputs[input_statement[0]], input_statement[1].params) F.append(f) for consequent in rule[1]: B[consequent[0]] += f * consequent[1](*params) f = npsum(F) for out in self.outputs: B[out] /= f return B class IT2FS: """Interval Type 2 Fuzzy Set (IT2FS). Parameters ---------- Parameters of the constructor function: domain: numpy (n,) shaped array Indicates the universe of discourse dedicated to the IT2FS. umf: Upper membership function umf_params: List of parameters of upper membership function lmf: Lower membership function lmf_params: List of parameters of lower membership function check_set: If it is True, then a function named check_set in IT2FS will verify the LMF(x) < UMF(x) condition for any x in the domain. If the user is sure that has selected the parameters of the membership functions correct, then calling this time-consuming function is not needed. By default the parameter check_set is False. Functions ---------- Functions defined in IT2FS class: copy: Returns a copy of the IT2FS. plot: Plots the IT2FS. negation operator -: Returns the negated IT2FS. Examples -------- >>> mySet = IT2FS(linspace(0., 1., 100), trapezoid_mf, [0, 0.4, 0.6, 1., 1.], tri_mf, [0.25, 0.5, 0.75, 0.6]) >>> mySet.plot(filename="mySet") """ def __init__(self, domain, umf=zero_mf, umf_params=[], lmf=zero_mf, lmf_params=[], check_set=False): self.umf = umf self.lmf = lmf self.umf_params = umf_params self.lmf_params = lmf_params self.domain = domain # self.upper = maximum(minimum(umf(domain, umf_params), 1), 0) # self.lower = maximum(minimum(lmf(domain, lmf_params), 1), 0) if check_set: self.check_set() def __repr__(self): return "Interval type 2 fuzzy set with " + self.umf.__name__ + " UMF function with " + \ str(self.umf_params) + " parameters, and " + self.lmf.__name__ + \ " LMF function with " + str(self.lmf_params) + " parameters." @property def upper(self): return maximum(minimum(self.umf(self.domain, self.umf_params), 1), 0) @property def lower(self): return maximum(minimum(self.lmf(self.domain, self.lmf_params), 1), 0) def check_set(self): """ Verifies the LMF(x) < UMF(x) for any x in the domain. """ for l, u in zip(self.lower, self.upper): if l > u: raise ValueError("LMF in some points in domain is larger than UMF.") def copy(self): """ Copies the IT2FS. Returns ------- IT2FS Returns a copy of the IT2FS. """ return IT2FS(self.domain, umf=self.umf, umf_params=self.umf_params, lmf=self.lmf, lmf_params=self.lmf_params) def plot(self, title=None, legend_text=None, filename=None, ext="pdf", grid=True, xlabel="Domain", ylabel="Membership degree"): """ Plots the IT2FS. Parameters ---------- title: str If it is set, it indicates the title which would be represented in the plot. If it is not set, the plot would not have a title. legend_text: str If it is set, it indicates the legend text which would be represented in the plot. If it is not set, the plot would not contain a legend. filename: str If it is set, the plot would be saved as a filename.ext file. ext: str Extension of the output file with pdf default value. grid: bool Grid on/off. xlabel: str Label of the x axis. ylabel: str Label of the y axis. Examples -------- >>> mySet = IT2FS(linspace(0., 1., 100), trapezoid_mf, [0, 0.4, 0.6, 1., 1.], tri_mf, [0.25, 0.5, 0.75, 0.6]) >>> mySet.plot(filename="mySet") """ plt.figure() plt.fill_between(self.domain, self.upper, self.lower) if legend_text is not None: plt.legend([legend_text]) if title is not None: plt.title(title) plt.plot(self.domain, self.upper, color="black") plt.plot(self.domain, self.lower, color="black") plt.grid(grid) plt.xlabel(xlabel) plt.ylabel(ylabel) if filename is not None: plt.savefig(filename + "." + ext, format=ext, dpi=300, bbox_inches="tight") plt.show() def __neg__(self): """ Negates the IT2FS. Returns ------- IT2FS Returns a negated copy of the IT2FS. """ umf = lambda x, params: subtract(1, self.umf(x, params)) lmf = lambda x, params: subtract(1, self.lmf(x, params)) neg_it2fs = IT2FS(self.domain, lmf, self.lmf_params, umf, self.umf_params) return neg_it2fs def IT2_Emphasize(it2fs, m=2.): """ Function for creating emphasized IT2FSs. Parameters ---------- it2fs : IT2FS Interval type 2 fuzzy set to be emphasized. m : float, optional Emphasis degree. The default is 2. Returns ------- emphasized : IT2FS Emphasized interval type 2 fuzzy set. """ lmf = lambda x, params : it2fs.lmf(x, it2fs.lmf_params) ** m umf = lambda x, params : it2fs.umf(x, it2fs.umf_params) ** m emphasized = IT2FS(it2fs.domain, umf, it2fs.umf_params, lmf, it2fs.lmf_params) return emphasized def IT2FS_Elliptic(domain, params, check_set=False): """ Creates an elliptic IT2FS. Parameters ---------- domain: numpy (n,) shaped array Indicates the universe of discourse dedicated to the IT2FS. params: List The parameters of the elliptic IT2FS, the center, width, UMF's exponent, LMF's exponent, and height are indicated by params[0], params[1], params[2], params[3], and params[4], respectively. Returns ------- IT2FS Returns an elliptic IT2FS with specified parameters. Examples -------- >>> domain = linspace(0., 1., 100) >>> mySet = IT2FS_Elliptic(domain, [0.5, 0.25, 1.3, 0.7, 0.8]) >>> mySet.plot() """ return IT2FS(domain, elliptic_mf, [params[0], params[1], params[2], params[4]], elliptic_mf, [params[0], params[1], params[3], params[4]], check_set=check_set) def IT2FS_Semi_Elliptic(domain, params, check_set=False): """ Creates a semi-elliptic IT2FS. Parameters ---------- domain: numpy (n,) shaped array Indicates the universe of discourse dedicated to the IT2FS. params: List The parameters of the semi-elliptic IT2FS, the center, UMF's width, LMF's width, and height are indicated by params[0], params[1], params[2], and params[3], respectively. Returns ------- IT2FS Returns a semi-elliptic IT2FS with specified parameters. Examples -------- >>> domain = linspace(0., 1., 100) >>> mySet = IT2FS_Semi_Elliptic(domain, [0.5, 0.15, 0.05, 0.6]) >>> mySet.plot() """ return IT2FS(domain, semi_elliptic_mf, [params[0], params[1], params[3]], semi_elliptic_mf, [params[0], params[2], params[3]], check_set=check_set) def IT2FS_Gaussian_UncertMean(domain, params, check_set=False): """ Creates an Gaussian IT2FS with uncertain mean value. Parameters ---------- domain: numpy (n,) shaped array Indicates the universe of discourse dedicated to the IT2FS. params: List The parameters of the Gaussian IT2FS with uncertain mean value, the mean center, mean spread, standard deviation, and height are indicated by params[0], params[1], params[2], and params[3], respectively. Returns ------- IT2FS Returns a Gaussian IT2FS with uncertain mean value with specified parameters. Examples -------- >>> domain = linspace(0., 1., 100) >>> mySet = IT2FS_Gaussian_UncertMean(domain, [0., 0.25, 0.2]) >>> mySet.plot() """ ml = params[0] - params[1] / 2. mr = params[0] + params[1] / 2. return IT2FS(domain, gauss_uncert_mean_umf, [ml, mr, params[2], params[3]], gauss_uncert_mean_lmf, [ml, mr, params[2], params[3]], check_set=check_set) def IT2FS_Gaussian_UncertStd(domain, params, check_set=False): """ Creates a Gaussian IT2FS with uncertain standard deviation value. Parameters ---------- domain: numpy (n,) shaped array Indicates the universe of discourse dedicated to the IT2FS. params: List The parameters of the Gaussian IT2FS with uncertain standard deviation value, the mean, standard deviation center, standard deviation spread, and height are indicated by params[0], params[1], params[2], and params[3], respectively. Returns ------- IT2FS Returns a Gaussian IT2FS with uncertain standard deviation value with specified parameters. Examples -------- >>> domain = linspace(0., 1., 100) >>> mySet = IT2FS_Gaussian_UncertStd(domain, [0.5, 0.2, 0.05, 1.]) >>> mySet.plot() """ stdl = params[1] - params[2] / 2 stdr = params[1] + params[2] / 2 return IT2FS(domain, gauss_uncert_std_umf, [params[0], stdl, stdr, params[3]], gauss_uncert_std_lmf, [params[0], stdl, stdr, params[3]], check_set=check_set) def IT2FS_RGaussian_UncertStd(domain, params, check_set=False): """ Creates a Right Gaussian IT2FS with uncertain standard deviation value. Parameters ---------- domain: numpy (n,) shaped array Indicates the universe of discourse dedicated to the IT2FS. params: List The parameters of the Gaussian IT2FS with uncertain standard deviation value, the mean, standard deviation center, standard deviation spread, and height are indicated by params[0], params[1], params[2], and params[3], respectively. Returns ------- IT2FS Returns a Gaussian IT2FS with uncertain standard deviation value with specified parameters. Examples -------- >>> domain = linspace(0., 1., 100) >>> mySet = R_IT2FS_Gaussian_UncertStd(domain, [0.5, 0.2, 0.05, 1.]) >>> mySet.plot() """ stdl = params[1] - params[2] / 2 stdr = params[1] + params[2] / 2 return IT2FS(domain, rgauss_uncert_std_umf, [params[0], stdl, stdr, params[3]], rgauss_uncert_std_lmf, [params[0], stdl, stdr, params[3]], check_set=check_set) R_IT2FS_Gaussian_UncertStd = IT2FS_RGaussian_UncertStd def IT2FS_LGaussian_UncertStd(domain, params, check_set=False): """ Creates a Left Gaussian IT2FS with uncertain standard deviation value. Parameters ---------- domain: numpy (n,) shaped array Indicates the universe of discourse dedicated to the IT2FS. params: List The parameters of the Gaussian IT2FS with uncertain standard deviation value, the mean, standard deviation center, standard deviation spread, and height are indicated by params[0], params[1], params[2], and params[3], respectively. Returns ------- IT2FS Returns a Gaussian IT2FS with uncertain standard deviation value with specified parameters. Examples -------- >>> domain = linspace(0., 1., 100) >>> mySet = L_IT2FS_Gaussian_UncertStd(domain, [0.5, 0.2, 0.05, 1.]) >>> mySet.plot() """ stdl = params[1] - params[2] / 2 stdr = params[1] + params[2] / 2 return IT2FS(domain, lgauss_uncert_std_umf, [params[0], stdl, stdr, params[3]], lgauss_uncert_std_lmf, [params[0], stdl, stdr, params[3]], check_set=check_set) L_IT2FS_Gaussian_UncertStd = IT2FS_LGaussian_UncertStd def IT2FS_plot(*sets, title=None, legends=None, filename=None, ext="pdf", grid=True, xlabel="Domain", ylabel="Membership degree"): """ Plots multiple IT2FSs together in the same figure. Parameters ---------- *sets: Multiple number of IT2FSs which would be plotted. title: str If it is set, it indicates the title which would be represented in the plot. If it is not set, the plot would not have a title. legends: List of strs List of legend texts to be presented in plot. If it is not set, no legend would be in plot. filename: str If it is set, the plot would be saved as a filename.ext file. ext: str Extension of the output file with pdf default value. grid: bool Grid on/off. xlabel: str Label of the x axis. ylabel: str Label of the y axis. Examples -------- >>> domain = linspace(0., 1., 100) >>> it2fs1 = IT2FS_Gaussian_UncertStd(domain, [0.33, 0.2, 0.05]) >>> it2fs2 = IT2FS_Gaussian_UncertStd(domain, [0.66, 0.2, 0.05]) >>> IT2FS_plot(it2fs1, it2fs2, title="Plotting IT2FSs", legends=["First set", "Second set"]) """ plt.figure() for it2fs in sets: plt.fill_between(it2fs.domain, it2fs.upper, it2fs.lower, alpha=0.5) if legends is not None: plt.legend(legends) for it2fs in sets: plt.plot(it2fs.domain, it2fs.lower, color="black") plt.plot(it2fs.domain, it2fs.upper, color="black") if title is not None: plt.title(title) plt.xlabel(xlabel) plt.ylabel(ylabel) plt.grid(grid) if filename is not None: plt.savefig(filename + "." + ext, format=ext, dpi=300, bbox_inches="tight") plt.show() def TR_plot(domain, tr, title=None, legend=None, filename=None, ext="pdf", grid=True, xlabel="Domain", ylabel="Membership degree"): """ Plots a type reduced IT2FS. Parameters ---------- domain: numpy (n,) shaped array Indicates the universe of discourse dedicated to the IT2FS. tr: Tuple (l, r) Indicates the type reduced set to be plotted. title: str If it is set, it indicates the title which would be represented in the plot. If it is not set, the plot would not have a title. legend: str If it is set, it indicates the legend text which would be represented in the plot. If it is not set, the plot would not contain a legend. filename: str If it is set, the plot would be saved as a filename.ext file. ext: str Extension of the output file with pdf default value. grid: bool Grid on/off. xlabel: str Label of the x axis. ylabel: str Label of the y axis. Examples -------- >>> tr1 = (0.2, 0.3) >>> TR_plot(linspace(0., 1., 100), tr1) """ plt.figure() plt.plot([min(domain), tr[0], tr[0], tr[1], tr[1], max(domain)], [0, 0, 1, 1, 0, 0], linewidth=2) plt.xlim((min(domain), max(domain))) plt.xlabel(xlabel) plt.ylabel(ylabel) if title is not None: plt.title(title) if legend is not None: plt.legend([legend]) plt.grid(grid) if filename is not None: plt.savefig(filename + "." + ext, format=ext, dpi=300, bbox_inches="tight") plt.show() def crisp(tr): """ Calculates the crisp number achieved from type reduced IT2FS. Parameters ---------- tr: Tuple (l, r) Type reduced IT2FS Returns ------- float Returns the crisp number achieved from type reduced IT2FS. Examples -------- >>> tr1 = (0.1, 0.3) >>> print(crisp(tr1)) """ return (tr[0] + tr[1]) / 2 def crisp_list(trs, o=None): """ Calculates the crisp outputs achieved by calling the evaluate_list function from IT2FLS class. Parameters ---------- trs: List of Tuple (l, r) Type reduced IT2FSs o: str The name of the output variable to be processed. If it is not given, then the crisp outputs are calculated for all output variables. Returns ------- List of float (or Dictionary of Lists of float) """ if o is None: output = {} for key in trs[0].keys(): output[key] = [] for tr in trs: for key in trs[0].keys(): output[key].append(crisp(tr[key])) return output else: output = [] for tr in trs: output.append(crisp(tr[o])) return output def min_t_norm(a, b): """ Minimum t-norm function. Parameters ---------- a: numpy (n,) shaped array b: numpy (n,) shaped array Returns ------- Returns minimum t-norm of a and b Examples -------- >>> a = random.random(10,) >>> b = random.random(10,) >>> c = min_t_norm(a, b) """ return minimum(a, b) def product_t_norm(a, b): """ Product t-norm function. Parameters ---------- a: numpy (n,) shaped array b: numpy (n,) shaped array Returns ------- Returns product t-norm of a and b Examples -------- >>> a = random.random(10,) >>> b = random.random(10,) >>> c = product_t_norm(a, b) """ return multiply(a, b) def lukasiewicz_t_norm(a, b): """ Lukasiewicz t-norm function. Parameters ---------- a: numpy (n,) shaped array b: numpy (n,) shaped array Returns ------- Returns Lukasiewicz t-norm of a and b Examples -------- >>> a = random.random(10,) >>> b = random.random(10,) >>> c = lukasiewicz_t_norm(a, b) """ return maximum(0, a + b - 1) def drastic_t_norm(a, b): """ Drastic t-norm function. Parameters ---------- a: numpy (n,) shaped array b: numpy (n,) shaped array Returns ------- Returns drastic t-norm of a and b Examples -------- >>> a = random.random(10,) >>> b = random.random(10,) >>> c = drastic_t_norm(a, b) """ return b * (a == 1) + a * (b == 1) def nilpotent_minimum_t_norm(a, b): """ Nilpotent minimum t-norm function. Parameters ---------- a: numpy (n,) shaped array b: numpy (n,) shaped array Returns ------- Returns nilpotent minimum t-norm of a and b Examples -------- >>> a = random.random(10,) >>> b = random.random(10,) >>> c = nilpotent_minimum_t_norm(a, b) """ return minimum(a, b) * (a + b > 1) def hamacher_product_t_norm(a, b): """ Hamacher product t-norm function. Parameters ---------- a: numpy (n,) shaped array b: numpy (n,) shaped array Returns ------- Returns hamacher product t-norm of a and b Examples -------- >>> a = random.random(10,) >>> b = random.random(10,) >>> c = hamacher_product_t_norm(a, b) """ return ((a * b) / (a + b - a * b)) * logical_not((a == 0) * (b == 0)) def max_s_norm(a, b): """ Maximum s-norm function. Parameters ---------- a: numpy (n,) shaped array b: numpy (n,) shaped array Returns ------- Returns maximum s-norm of a and b Examples -------- >>> a = random.random(10,) >>> b = random.random(10,) >>> c = max_s_norm(a, b) """ return maximum(a, b) def probabilistic_sum_s_norm(a, b): """ Probabilistic sum s-norm function. Parameters ---------- a: numpy (n,) shaped array b: numpy (n,) shaped array Returns ------- Returns probabilistic sum s-norm of a and b Examples -------- >>> a = random.random(10,) >>> b = random.random(10,) >>> c = probabilistic_sum_s_norm(a, b) """ return a + b - a * b def bounded_sum_s_norm(a, b): """ Bounded sum s-norm function. Parameters ---------- a: numpy (n,) shaped array b: numpy (n,) shaped array Returns ------- Returns bounded sum s-norm of a and b Examples -------- >>> a = random.random(10,) >>> b = random.random(10,) >>> c = bounded_sum_s_norm(a, b) """ return minimum(a + b, 1) def drastic_s_norm(a, b): """ Drastic s-norm function. Parameters ---------- a: numpy (n,) shaped array b: numpy (n,) shaped array Returns ------- Returns drastic s-norm of a and b Examples -------- >>> a = random.random(10,) >>> b = random.random(10,) >>> c = drastic_s_norm(a, b) """ return b * (a == 0) + a * (b == 0) + 1. * (a != 0.) * (b != 0.) def nilpotent_maximum_s_norm(a, b): """ Nilpotent maximum s-norm function. Parameters ---------- a: numpy (n,) shaped array b: numpy (n,) shaped array Returns ------- Returns nilpotent maximum s-norm of a and b Examples -------- >>> a = random.random(10,) >>> b = random.random(10,) >>> c = nilpotent_maximum_s_norm(a, b) """ return maximum(a, b) * (a + b < 1) + 1. * (a + b >= 1) def einstein_sum_s_norm(a, b): """ Einstein sum s-norm function. Parameters ---------- a: numpy (n,) shaped array b: numpy (n,) shaped array Returns ------- Returns einstein sum s-norm of a and b Examples -------- >>> a = random.random(10,) >>> b = random.random(10,) >>> c = einstein_sum_s_norm(a, b) """ return (a + b) / (1 + a * b) def meet(domain, it2fs1, it2fs2, t_norm): """ Meet operator for IT2FSs. Parameters ---------- domain: numpy (n,) shaped array Indicates the universe of discourse dedicated to the IT2FS. it2fs1: IT2FS First input of the meet operator. it2fs2: IT2FS Second input of the meet operator. t_norm: function The t-norm function to be used. Returns ------- IT2FS Returns the meet of the two input IT2FSs. Examples -------- >>> domain = linspace(0., 1., 100) >>> it2fs1 = IT2FS_Gaussian_UncertStd(domain, [0.33, 0.2, 0.05, 1.]) >>> it2fs2 = IT2FS_Gaussian_UncertStd(domain, [0.66, 0.2, 0.05, 1.]) >>> it2fs3 = meet(domain, it2fs1, it2fs2, min_t_norm) >>> it2fs3.plot() """ umf = lambda x, params: t_norm(it2fs1.umf(x, it2fs1.umf_params), it2fs2.umf(x, it2fs2.umf_params)) lmf = lambda x, params: t_norm(it2fs1.lmf(x, it2fs1.lmf_params), it2fs2.lmf(x, it2fs2.lmf_params)) it2fs = IT2FS(domain, umf, [], lmf, []) return it2fs def join(domain, it2fs1, it2fs2, s_norm): """ Join operator for IT2FSs. Parameters ---------- domain: numpy (n,) shaped array Indicates the universe of discourse dedicated to the IT2FS. it2fs1: IT2FS First input of the join operator. it2fs2: IT2FS Second input of the join operator. s_norm: function The s-norm function to be used. Returns ------- IT2FS Returns the join of the two input IT2FSs. Examples -------- >>> domain = linspace(0., 1., 100) >>> it2fs1 = IT2FS_Gaussian_UncertStd(domain, [0.33, 0.2, 0.05, 1.]) >>> it2fs2 = IT2FS_Gaussian_UncertStd(domain, [0.66, 0.2, 0.05, 1.]) >>> it2fs3 = join(domain, it2fs1, it2fs2, max_s_norm) >>> it2fs3.plot() """ umf = lambda x, params: s_norm(it2fs1.umf(x, it2fs1.umf_params), it2fs2.umf(x, it2fs2.umf_params)) lmf = lambda x, params: s_norm(it2fs1.lmf(x, it2fs1.lmf_params), it2fs2.lmf(x, it2fs2.lmf_params)) it2fs = IT2FS(domain, umf, [], lmf, []) return it2fs def trim(intervals): v = intervals[:, 3] i, = where(v > 0) if i.size == 0: return False else: min1 = i[0] max1 = i[-1] + 1 v = intervals[:, 2] i, = where(v > 0) if i.size == 0: min2 = min1 max2 = max1 else: min2 = i[0] max2 = i[-1] + 1 return intervals[min(min1, min2):max(max1, max2), :] def KM_algorithm(intervals, params=[]): # intervals = [[a1, b1, c1, d1], [a2, b2, c2, d2], ...] """ KM algorithm Parameters ---------- intervals: numpy (n, 4) array Y = intervals[:, 0:2] F = intervals[:, 2:4] params: List List of parameters of algorithm, if it is needed. Returns ------- Tuple (l, r) """ # left calculations intervals = trim(intervals) if intervals is False: return 0., 0. w = (intervals[:, 2] + intervals[:, 3]) / 2. w_l = w[:] N = len(intervals) intervals = intervals[intervals[:,0].argsort()] y_l_prime_num = npsum(intervals[:, 0] * w_l) y_prime_den = npsum(w_l) y_l_prime = y_l_prime_num / y_prime_den while True: k_l = 0 for i in range(0, N-1): if (intervals[i, 0] <= y_l_prime <= intervals[i+1, 0]) or \ isclose(intervals[i, 0], y_l_prime) or \ isclose(y_l_prime, intervals[i+1, 0]): k_l = i break ii = arange(N) w_l = (ii <= k_l) * intervals[:, 3] + (ii > k_l) * intervals[:, 2] y_l_num = npsum(intervals[:, 0] * w_l) y_l_den = npsum(w_l) y_l = y_l_num / y_l_den if isclose(y_l, y_l_prime, abs_tol=1.0e-6): break else: y_l_prime = y_l # right calculations w_r = w[:] intervals = intervals[intervals[:, 1].argsort()] y_r_prime_num = npsum(intervals[:, 1] * w_r) y_r_prime = y_r_prime_num / y_prime_den while True: k_r = 0 for i in range(0, N-1): if (intervals[i, 1] <= y_r_prime <= intervals[i+1, 1]) or \ isclose(intervals[i, 1], y_r_prime) or \ isclose(y_r_prime, intervals[i+1, 1]): k_r = i break ii = arange(N) w_r = (ii <= k_r) * intervals[:, 2] + (ii > k_r) * intervals[:, 3] y_r_num = npsum(intervals[:, 1] * w_r) y_r_den = npsum(w_r) y_r = y_r_num / y_r_den if isclose(y_r, y_r_prime, abs_tol=1.0e-6): break else: y_r_prime = y_r return y_l, y_r def EKM_algorithm(intervals, params=[]): """ EKM algorithm Parameters ---------- intervals: numpy (n, 4) array Y = intervals[:, 0:2] F = intervals[:, 2:4] params: List List of parameters of algorithm, if it is needed. Returns ------- Tuple (l, r) """ # Left calculations intervals = trim(intervals) if intervals is False: return 0, 0 N = len(intervals) k_l = round(N / 2.4) intervals = intervals[intervals[:, 0].argsort()] a_l = npsum(intervals[:k_l, 0] * intervals[:k_l, 3]) + \ npsum(intervals[k_l:, 0] * intervals[k_l:, 2]) b_l = npsum(intervals[:k_l, 3]) + npsum(intervals[k_l:, 2]) y_l_prime = a_l / b_l while True: k_l_prime = 0 for i in range(0, N-1): if (intervals[i, 0] <= y_l_prime <= intervals[i+1, 0]) or \ isclose(intervals[i, 0], y_l_prime, abs_tol=1.0e-6) or \ isclose(y_l_prime, intervals[i+1, 0], abs_tol=1.0e-6): k_l_prime = i break if k_l_prime == k_l: y_l = y_l_prime break s_l = sign(k_l_prime - k_l) imin = min(k_l, k_l_prime) + 1 imax = max(k_l, k_l_prime) a_l_prime = a_l + s_l * npsum(intervals[imin:imax, 0] * \ (intervals[imin:imax, 3] - intervals[imin:imax, 2])) b_l_prime = b_l + s_l * \ npsum(intervals[imin:imax, 3] - intervals[imin:imax, 2]) y_l_second = a_l_prime / b_l_prime k_l = k_l_prime y_l_prime = y_l_second a_l = a_l_prime b_l = b_l_prime # Right calculations intervals = intervals[intervals[:, 1].argsort()] k_r = round(N / 1.7) a_r = npsum(intervals[:k_r, 1] * intervals[:k_r, 2]) + \ npsum(intervals[k_r:, 1] * intervals[k_r:, 3]) b_r = npsum(intervals[:k_r, 2]) + npsum(intervals[k_r:, 3]) y_r_prime = a_r / b_r while True: k_r_prime = 0 for i in range(0, N-1): if (intervals[i, 1] <= y_r_prime <= intervals[i+1, 1]) or \ isclose(intervals[i, 1], y_r_prime, abs_tol=1.0e-6) or \ isclose(y_r_prime, intervals[i+1, 1], abs_tol=1.0e-6): k_r_prime = i break if k_r_prime == k_r: y_r = y_r_prime break s_r = sign(k_r_prime - k_r) imin = min(k_r, k_r_prime) + 1 imax = max(k_r, k_r_prime) a_r_prime = npsum(intervals[imin:imax, 1] * (intervals[imin:imax, 3] - intervals[imin:imax, 2])) b_r_prime = npsum(intervals[imin:imax, 3] - intervals[imin:imax, 2]) a_r_prime = a_r - s_r * a_r_prime b_r_prime = b_r - s_r * b_r_prime y_r_second = a_r_prime / b_r_prime k_r = k_r_prime y_r_prime = y_r_second a_r = a_r_prime b_r = b_r_prime return y_l, y_r def WEKM_algorithm(intervals, params=[]): """ WEKM algorithm Parameters ---------- intervals: numpy (n, 4) array Y = intervals[:, 0:2] F = intervals[:, 2:4] params: List List of parameters of algorithm, if it is needed. Returns ------- Tuple (l, r) """ # Left calculations intervals = intervals[intervals[:,0].argsort()] intervals = trim(intervals) if intervals is False: return 0, 0 N = len(intervals) k_l = round(N / 2.4) a_l = 0 b_l = 0 for i in range(k_l): a_l += params[i] * intervals[i, 0] * intervals[i, 3] b_l += params[i] * intervals[i, 3] for i in range(k_l, N): a_l += params[i] * intervals[i, 0] * intervals[i, 2] b_l += params[i] * intervals[i, 2] y_l_prime = a_l / b_l while True: k_l_prime = 0 for i in range(1, N): if (intervals[i - 1, 0] <= y_l_prime <= intervals[i, 0]) or \ isclose(intervals[i - 1, 0], y_l_prime) or \ isclose(y_l_prime, intervals[i, 0]): k_l_prime = i - 1 break if k_l_prime == k_l: y_l = y_l_prime break s_l = sign(k_l_prime - k_l) a_l_prime = 0 b_l_prime = 0 for i in range(min(k_l, k_l_prime) + 1, max(k_l, k_l_prime)): a_l_prime += params[i] * intervals[i, 0] * (intervals[i, 3] - intervals[i, 2]) b_l_prime += params[i] * (intervals[i, 3] - intervals[i, 2]) a_l_prime = a_l + s_l * a_l_prime b_l_prime = b_l + s_l * b_l_prime y_l_second = a_l_prime / b_l_prime k_l = k_l_prime y_l_prime = y_l_second a_l = a_l_prime b_l = b_l_prime # Right calculations intervals = intervals[intervals[:,1].argsort()] k_r = round(N / 1.7) a_r = 0 b_r = 0 for i in range(k_r): a_r += params[i] * intervals[i, 1] * intervals[i, 2] b_r += params[i] * intervals[i, 2] for i in range(k_r, N): a_r += params[i] * intervals[i, 1] * intervals[i, 3] b_r += params[i] * intervals[i, 3] y_r_prime = a_r / b_r while True: k_r_prime = 0 for i in range(1, N): if (intervals[i - 1, 1] <= y_r_prime <= intervals[i, 1]) or \ isclose(intervals[i - 1, 1], y_r_prime) or \ isclose(y_r_prime, intervals[i, 1]): k_r_prime = i - 1 break if k_r_prime == k_r: y_r = y_r_prime break s_r = sign(k_r_prime - k_r) a_r_prime = 0 b_r_prime = 0 for i in range(min(k_r, k_r_prime) + 1, max(k_r, k_r_prime)): a_r_prime += params[i] * intervals[i, 1] * (intervals[i, 3] - intervals[i, 2]) b_r_prime += params[i] * (intervals[i, 3] - intervals[i, 2]) a_r_prime = a_r - s_r * a_r_prime b_r_prime = b_r - s_r * b_r_prime y_r_second = a_r_prime / b_r_prime k_r = k_r_prime y_r_prime = y_r_second a_r = a_r_prime b_r = b_r_prime return y_l, y_r def TWEKM_algorithm(intervals, params): """ TWEKM algorithm Parameters ---------- intervals: numpy (n, 4) array Y = intervals[:, 0:2] F = intervals[:, 2:4] params: List List of parameters of algorithm, if it is needed. Returns ------- Tuple (l, r) """ params = [] N = len(intervals) for i in range(N): if i == 0 or i == N-1: params.append(0.5) else: params.append(1) return WEKM_algorithm(intervals, params) def EIASC_algorithm(intervals, params=[]): """ EIASC algorithm Parameters ---------- intervals: numpy (n, 4) array Y = intervals[:, 0:2] F = intervals[:, 2:4] params: List List of parameters of algorithm, if it is needed. Returns ------- Tuple (l, r) """ # Left calculations intervals = trim(intervals) if intervals is False: return 0, 0 N = len(intervals) intervals = intervals[intervals[:, 0].argsort()] a_l = npsum(intervals[:, 0] * intervals[:, 2]) b_l = npsum(intervals[:, 2]) L = 0 while True: d = intervals[L, 3] - intervals[L, 2] a_l += intervals[L, 0] * d b_l += d y_l = a_l / b_l L += 1 if (y_l <= intervals[L, 0]) or isclose(y_l, intervals[L, 0]): break # Right calculations intervals = intervals[intervals[:, 1].argsort()] a_r = npsum(intervals[:, 1] * intervals[:, 2]) b_r = npsum(intervals[:, 2]) R = N - 1 while True: d = intervals[R, 3] - intervals[R, 2] a_r += intervals[R, 1] * d b_r += d y_r = a_r / b_r R -= 1 if (y_r >= intervals[R, 1]) or isclose(y_r, intervals[R, 1]): break return y_l, y_r def WM_algorithm(intervals, params=[]): """ WM algorithm Parameters ---------- intervals: numpy (n, 4) array Y = intervals[:, 0:2] F = intervals[:, 2:4] params: List List of parameters of algorithm, if it is needed. Returns ------- Tuple (l, r) """ intervals = intervals[intervals[:,0].argsort()] intervals = trim(intervals) if intervals is False: return 0, 0 F = intervals[:, 2:4] Y = intervals[:, 0:2] y_l_sup = min(npsum(F[:, 0] * Y[:, 0]) / npsum(F[:, 0]), npsum(F[:, 1] * Y[:, 0]) / npsum(F[:, 1])) y_r_inf = min(npsum(F[:, 1] * Y[:, 1]) / npsum(F[:, 1]), npsum(F[:, 0] * Y[:, 1]) / npsum(F[:, 0])) c = npsum(F[:, 1] - F[:, 0]) / (npsum(F[:, 0]) * npsum(F[:, 1])) y_l_inf = y_l_sup - c * (npsum(F[:, 0] * (Y[:, 0] - Y[0, 0])) * npsum(F[:, 1] * (Y[-1, 0] - Y[:, 0]))) / (npsum(F[:, 0] * (Y[:, 0] - Y[0, 0])) + npsum(F[:, 1] * (Y[-1, 0] - Y[:, 0]))) y_r_sup = y_r_inf + c * (npsum(F[:, 1] * (Y[:, 1] - Y[0, 1])) * npsum(F[:, 0] * (Y[-1, 1] - Y[:, 1]))) / (npsum(F[:, 1] * (Y[:, 1] - Y[0, 1])) + npsum(F[:, 0] * (Y[-1, 1] - Y[:, 1]))) y_l = (y_l_sup + y_l_inf) / 2 y_r = (y_r_sup + y_r_inf) / 2 return y_l, y_r def BMM_algorithm(intervals, params): """ BMM algorithm Parameters ---------- intervals: numpy (n, 4) array Y = intervals[:, 0:2] F = intervals[:, 2:4] params: List List of parameters of algorithm, if it is needed. Returns ------- float Crisp output """ intervals = intervals[intervals[:,0].argsort()] intervals = trim(intervals) if intervals is False: return 0 F = intervals[:, 2:4] Y = (intervals[:, 0] + intervals[:, 1]) / 2. m = params[0] n = params[1] #Y = Y.reshape((Y.size,)) return m * npsum(F[:, 0] * Y) / npsum(F[:, 0]) + n * npsum(F[:, 1] * Y) / npsum(F[:, 1]) def LBMM_algorithm(intervals, params): """ LBMM algorithm (BMM extended by Li et al.) Ref. An Overview of Alternative Type-ReductionApproaches for Reducing the Computational Costof Interval Type-2 Fuzzy Logic Controllers Parameters ---------- intervals: numpy (n, 4) array Y = intervals[:, 0:2] F = intervals[:, 2:4] params: List List of parameters of algorithm, if it is needed. Returns ------- float Crisp output """ intervals = intervals[intervals[:,0].argsort()] intervals = trim(intervals) if intervals is False: return 0 F = intervals[:, 2:4] Y = intervals[:, 0:2] m = params[0] n = params[1] return m * npsum(F[:, 0] * Y[:, 0]) / npsum(F[:, 0]) + n * npsum(F[:, 1] * Y[:, 1]) / npsum(F[:, 1]) def NT_algorithm(intervals, params=[]): """ NT algorithm Parameters ---------- intervals: numpy (n, 4) array Y = intervals[:, 0:2] F = intervals[:, 2:4] params: List List of parameters of algorithm, if it is needed. Returns ------- float Crisp output """ intervals = intervals[intervals[:,0].argsort()] intervals = trim(intervals) if intervals is False: return 0 F = intervals[:, 2:4] Y = (intervals[:, 0] + intervals[:, 1]) / 2. return (npsum(Y * F[:, 1]) + npsum(Y * F[:, 0])) / (npsum(F[:, 0]) + npsum(F[:, 1])) def Centroid(it2fs, alg_func, domain, alg_params=[]): """ Centroid type reduction for an interval type 2 fuzzy set. Parameters ---------- it2fs: IT2FS IT2FS which would be type reduced. alg_func: Function Type reduction algorithm to be used, which is one of these: KM_algorithm, EKM_algorithm, WEKM_algorithm, TWEKM_algorithm, EIASC_algorithm, WM_algorithm, BMM_algorithm, LBMM_algorithm, and NT_algorithm domain: numpy (n,) shaped array Indicates the universe of discourse dedicated to the IT2FS. alg_params: List List of parameters of type reduction algorithm if it is needed. Returns ------- Based on selected type reduction algorithm tuple (l, r) or float Returns Centroid type reduction of the input IT2FS. """ intervals = c_[domain, domain, it2fs.lower, it2fs.upper] return alg_func(intervals, alg_params) def CoSet(firing_array, consequent_array, alg_func, domain, alg_params=[]): """ Center of sets type reduction. Parameters ---------- firing_array: numpy (m, 2) shaped array Firing strength of consequents. consequent_array: List of IT2FS List of consequents corresponding with the rules of IT2FLS alg_func: Function Type reduction algorithm to be used, which is one of these: KM_algorithm, EKM_algorithm, WEKM_algorithm, TWEKM_algorithm, EIASC_algorithm, WM_algorithm, BMM_algorithm, LBMM_algorithm, and NT_algorithm domain: numpy (n,) shaped array Indicates the universe of discourse dedicated to the IT2FS. alg_params: List List of parameters of type reduction algorithm if it is needed. Returns ------- Based on selected type reduction algorithm tuple (l, r) or float Returns Center of sets type reduction of the input IT2FS. """ intervals = [] for l in range(len(consequent_array)): tmp = Centroid(consequent_array[l], alg_func, domain) intervals.append([tmp[0], tmp[1], firing_array[l, 0], firing_array[l, 1]]) return alg_func(array(intervals), alg_params) def CoSum(it2fs_array, alg_func, domain, alg_params=[]): """ Center of sum type reduction for an interval type 2 fuzzy set. Parameters ---------- it2fs_array: List of IT2FSs List of final IT2FSs achieved by evaluating rule base. alg_func: Function Type reduction algorithm to be used, which is one of these: KM_algorithm, EKM_algorithm, WEKM_algorithm, TWEKM_algorithm, EIASC_algorithm, WM_algorithm, BMM_algorithm, LBMM_algorithm, and NT_algorithm domain: numpy (n,) shaped array Indicates the universe of discourse dedicated to the IT2FS. alg_params: List List of parameters of type reduction algorithm if it is needed. Returns ------- Based on selected type reduction algorithm tuple (l, r) or float Returns Center of sum type reduction of the input IT2FS. """ lower_sum = zeros_like(domain) upper_sum = zeros_like(domain) for it2fs in it2fs_array: add(lower_sum, it2fs.lower, out=lower_sum) add(upper_sum, it2fs.lower, out=upper_sum) intervals = c_[domain, domain, lower_sum, upper_sum] return alg_func(intervals, alg_params) def Height(it2fs_array, alg_func, domain, alg_params=[]): """ Height type reduction for an interval type 2 fuzzy set. Parameters ---------- it2fs_array: List of IT2FSs List of final IT2FSs achieved by evaluating rule base. alg_func: Function Type reduction algorithm to be used, which is one of these: KM_algorithm, EKM_algorithm, WEKM_algorithm, TWEKM_algorithm, EIASC_algorithm, WM_algorithm, BMM_algorithm, LBMM_algorithm, and NT_algorithm domain: numpy (n,) shaped array Indicates the universe of discourse dedicated to the IT2FS. alg_params: List List of parameters of type reduction algorithm if it is needed. Returns ------- Based on selected type reduction algorithm tuple (l, r) or float Returns Height type reduction of the input IT2FS. """ intervals = [] for it2fs in it2fs_array: index = argmax(it2fs.upper) intervals.append([domain[index], domain[index], it2fs.lower[index], it2fs.upper[index]]) return alg_func(array(intervals), alg_params) def ModiHe(it2fs_array, spread_array, alg_func, domain, alg_params=[]): """ Modified height type reduction for an interval type 2 fuzzy set. Parameters ---------- it2fs_array: List of IT2FSs List of final IT2FSs achieved by evaluating rule base. spread_array: List of spread values corresponding with IT2FSs in it2fs_array. alg_func: Function Type reduction algorithm to be used, which is one of these: KM_algorithm, EKM_algorithm, WEKM_algorithm, TWEKM_algorithm, EIASC_algorithm, WM_algorithm, BMM_algorithm, LBMM_algorithm, and NT_algorithm domain: numpy (n,) shaped array Indicates the universe of discourse dedicated to the IT2FS. alg_params: List List of parameters of type reduction algorithm if it is needed. Returns ------- Based on selected type reduction algorithm tuple (l, r) or float Returns Modified height type reduction of the input IT2FS. """ intervals = [] j = 0 for it2fs in it2fs_array: index = argmax(it2fs.upper) intervals.append([domain[index], domain[index], it2fs.lower[index]/(spread_array[j] ** 2), it2fs.upper[index]/(spread_array[j] ** 2)]) j += 1 return alg_func(array(intervals), alg_params) class IT2FLS: """Interval type 2 fuzzy logic system. No construction parameter is needed. Members ------- inputs: List of str List of names of inputs as str output: List of str List of names ot outputs as str rules: List of tuples (antecedent, consequent) List of rules which each rule is defined as a tuple (antecedent, consequent) Both antacedent and consequent are lists of tuples. Each tuple of this list shows assignement of a variable to an IT2FS. First element of the tuple must be variable name (input or output) as a str and the second element must be an IT2FS. Functions --------- add_input_variable: Adds an input variable to the inputs list of the IT2FLS. add_output_variable: Adds an output variable to the outputs list of the IT2FLS. add_rule: Adds a rule to the rules list of the IT2FLS. copy: Returns a copy of the IT2FLS. evaluate: Evaluates the IT2FLS's output for a specified crisp input. Examples -------- Assume that we are going to simulate an IT2FLS with two inputs and two outputs. Each input is defined by three IT2FSs, Small, Medium, and Large. These IT2FSs are from Gaussian type with uncertain standard deviation value. The universe of discourse of the fuzzy system is defined as the interval [0, 1]. Also, the rule base of the system is defined as below: * IF x1 is Small and x2 is Small THEN y1 is Small and y2 is Large * IF x1 is Medium and x2 is Medium THEN y1 is Medium and y2 is Small * IF x1 is Large and x2 is Large THEN y1 is Large and y2 is Small The codes to simulate the aforementioned system using the PyIT2FLS would be as below: >>> domain = linspace(0., 1., 100) >>> >>> Small = IT2FS_Gaussian_UncertStd(domain, [0, 0.15, 0.1, 1.]) >>> Medium = IT2FS_Gaussian_UncertStd(domain, [0.5, 0.15, 0.1, 1.]) >>> Large = IT2FS_Gaussian_UncertStd(domain, [1., 0.15, 0.1, 1.]) >>> IT2FS_plot(Small, Medium, Large, legends=["Small", "Medium", "large"]) >>> >>> myIT2FLS = IT2FLS() >>> myIT2FLS.add_input_variable("x1") >>> myIT2FLS.add_input_variable("x2") >>> myIT2FLS.add_output_variable("y1") >>> myIT2FLS.add_output_variable("y2") >>> >>> myIT2FLS.add_rule([("x1", Small), ("x2", Small)], [("y1", Small), ("y2", Large)]) >>> myIT2FLS.add_rule([("x1", Medium), ("x2", Medium)], [("y1", Medium), ("y2", Small)]) >>> myIT2FLS.add_rule([("x1", Large), ("x2", Large)], [("y1", Large), ("y2", Small)]) >>> >>> it2out, tr = myIT2FLS.evaluate({"x1":0.9, "x2":0.9}, min_t_norm, max_s_norm, domain) >>> it2out["y1"].plot() >>> TR_plot(domain, tr["y1"]) >>> print(crisp(tr["y1"])) >>> >>> it2out["y2"].plot() >>> TR_plot(domain, tr["y2"]) >>> print(crisp(tr["y2"])) >>> Notes ----- While using the PyIT2FLS the user must take care of the items listed below: * The UMF defined for an IT2FS must be greater than or equal with the LMF at all points of the discrete universe of discourse. * The inputs and outputs defined must be compatible while adding the rules and evluating the IT2FLS. """ def __init__(self): self.inputs = [] self.outputs = [] self.rules = [] def __repr__(self): return "Interval type 2 Mamdani fuzzy logic system!" def add_input_variable(self, name): """ Adds new input variable name. Parameters ---------- name: str Name of the new input variable as a str. """ self.inputs.append(name) def add_output_variable(self, name): """ Adds new output variable name. Parameters ---------- name: str Name of the new output variable as a str. """ self.outputs.append(name) def add_rule(self, antecedent, consequent): """ Adds new rule to the rule base of the IT2FLS. Parameters ---------- antecedent: List of tuples Antecedent is a list of tuples in which each tuple indicates assignement of a variable to an IT2FS. First element of the tuple must be input variable name as str, and the second element of the tuple must be an IT2FS. consequent: List of tuples Consequent is a list of tuples in which each tuple indicates assignement of a variable to an IT2FS. First element of the tuple must be output variable name as str, and the second element of the tuple must be an IT2FS. """ self.rules.append((antecedent, consequent)) def copy(self): """ Returns a copy of the IT2FLS. """ o = IT2FLS() o.inputs = self.inputs.copy() o.outputs = self.outputs.copy() o.rules = self.rules.copy() return o def evaluate_list(self, inputs, t_norm, s_norm, domain, method="Centroid", method_params=[], algorithm="EIASC", algorithm_params=[]): """ Evaluates the IT2FLS based on list of crisp inputs given by user. Parameters ---------- inputs: dictionary Inputs is a dictionary in which the keys are input variable names as str and the values are the list of crisp values corresponded with the inputs to be evaluated. t_norm: function Indicates the t-norm operator to be used, and should be chosen between min_t_norm, product_t_norm, or other user defined t-norms. s_norm: function Indicates the s-norm operator to be used, and should be chosen between max_s_norm or other user defined s-norms. domain: numpy (n,) shaped array Indicates the universe of discourse dedicated to the IT2FS. method="Centroid": str Indicates the type reduction method name and should be one of the methods listed below: Centroid, CoSet, CoSum, Height, and ModiHe. method_params=[]: List Parameters of the type reduction method, if needed. algorithm="EIASC": Indicates the type reduction algorithm name and should be one of the algorithms listed below: KM, EKM, WEKM, TWEKM, EIASC, WM, BMM, LBMM, and NT. algorithm_params=[]: List Parameters of the type reduction algorithm, if needed. Returns ------- It depends on which method and algorithm for type reduction is chosen. If Centroid type reduction method is chosen the output is a tuple with two elements. First element is the overall IT2FS outputs of the system as a list of dictionaries with output names as keys and sets as values. The second output is outputs of the selected type reduction algorithm as a list of dictionaries with output names as keys and type reduction algorithm function output as value. For other type reduction methods the only output is a list of dictionaries of the type reduction algorithm function outputs for each output variable name as a key. Notes ----- While using the evaluate function some cares must be taken by the user himself which are listed as below: * The inputs must be lay in the defined universe of discourse. * The type reduction method and the type reduction algorithm must be selected from the lists provided in docstrings. """ inputs_list = [] l = len(inputs[self.inputs[0]]) for i in inputs.values(): if len(i) != l: raise ValueError("All input lists must contain same number of values.") for i in range(l): inputs_list.append({}) for j in self.inputs: inputs_list[-1][j] = inputs[j][i] if algorithm == "KM": alg_func = KM_algorithm elif algorithm == "EKM": alg_func = EKM_algorithm elif algorithm == "WEKM": alg_func = WEKM_algorithm elif algorithm == "TWEKM": alg_func = TWEKM_algorithm elif algorithm == "WM": alg_func = WM_algorithm elif algorithm == "LBMM": alg_func = LBMM_algorithm elif algorithm == "BMM": alg_func = BMM_algorithm elif algorithm == "NT": alg_func = NT_algorithm elif algorithm == "EIASC": alg_func = EIASC_algorithm else: raise ValueError("The " + algorithm + " algorithm is not implemented, yet!") outputs = [] if method == "Centroid": Cs = [] TRs = [] for inputs in inputs_list: B = {out: [] for out in self.outputs} for rule in self.rules: u = 1 l = 1 for input_statement in rule[0]: u = t_norm(u, input_statement[1].umf(inputs[input_statement[0]], input_statement[1].umf_params)) l = t_norm(l, input_statement[1].lmf(inputs[input_statement[0]], input_statement[1].lmf_params)) for consequent in rule[1]: B_l = meet(consequent[1].domain, IT2FS(consequent[1].domain, const_mf, [u], const_mf, [l]), consequent[1], t_norm) B[consequent[0]].append(B_l) C = {out: IT2FS(B[out][0].domain) for out in self.outputs} TR = {} for out in self.outputs: for B_l in B[out]: C[out] = join(B_l.domain, C[out], B_l, s_norm) TR[out] = Centroid(C[out], alg_func, B_l.domain, alg_params=algorithm_params) Cs.append(C) TRs.append(TR) return Cs, TRs elif method == "CoSet": for inputs in inputs_list: F = [] G = {out: [] for out in self.outputs} for rule in self.rules: u = 1 l = 1 for input_statement in rule[0]: u = t_norm(u, input_statement[1].umf(inputs[input_statement[0]], input_statement[1].umf_params)) l = t_norm(l, input_statement[1].lmf(inputs[input_statement[0]], input_statement[1].lmf_params)) F.append([l, u]) for consequent in rule[1]: G[consequent[0]].append(consequent[1]) TR = {} for out in self.outputs: TR[out] = CoSet(array(F), G[out], alg_func, G[out][0].domain, alg_params=algorithm_params) outputs.append(TR) return outputs elif method == "CoSum": for inputs in inputs_list: B = {out: [] for out in self.outputs} for rule in self.rules: u = 1 l = 1 for input_statement in rule[0]: u = t_norm(u, input_statement[1].umf(inputs[input_statement[0]], input_statement[1].umf_params)) l = t_norm(l, input_statement[1].lmf(inputs[input_statement[0]], input_statement[1].lmf_params)) for consequent in rule[1]: B_l = meet(consequent[1].domain, IT2FS(consequent[1].domain, const_mf, [u], const_mf, [l]), consequent[1], t_norm) B[consequent[0]].append(B_l) TR = {} for out in self.outputs: TR[out] = CoSum(B[out], alg_func, B[out][0].domain, alg_params=algorithm_params) outputs.append(TR) return outputs elif method == "Height": for inputs in inputs_list: B = {out: [] for out in self.outputs} for rule in self.rules: u = 1 l = 1 for input_statement in rule[0]: u = t_norm(u, input_statement[1].umf(inputs[input_statement[0]], input_statement[1].umf_params)) l = t_norm(l, input_statement[1].lmf(inputs[input_statement[0]], input_statement[1].lmf_params)) for consequent in rule[1]: B_l = meet(consequent[1].domain, IT2FS(consequent[1].domain, const_mf, [u], const_mf, [l]), consequent[1], t_norm) B[consequent[0]].append(B_l) TR = {} for out in self.outputs: TR[out] = Height(B[out], alg_func, B[out][0].domain, alg_params=algorithm_params) outputs.append(TR) return outputs elif method == "ModiHe": for inputs in inputs_list: B = {out: [] for out in self.outputs} for rule in self.rules: u = 1 l = 1 for input_statement in rule[0]: u = t_norm(u, input_statement[1].umf(inputs[input_statement[0]], input_statement[1].umf_params)) l = t_norm(l, input_statement[1].lmf(inputs[input_statement[0]], input_statement[1].lmf_params)) for consequent in rule[1]: B_l = meet(consequent[1].domain, IT2FS(consequent[1].domain, const_mf, [u], const_mf, [l]), consequent[1], t_norm) B[consequent[0]].append(B_l) TR = {} for out in self.outputs: TR[out] = ModiHe(B[out], method_params, alg_func, B[out][0].domain, alg_params=algorithm_params) outputs.append(TR) return outputs else: raise ValueError("The method " + method + " is not implemented yet!") def evaluate(self, inputs, t_norm, s_norm, domain, method="Centroid", method_params=[], algorithm="EIASC", algorithm_params=[]): """ Evaluates the IT2FLS based on crisp inputs given by user. Parameters ---------- inputs: dictionary Inputs is a dictionary in which the keys are input variable names as str and the values are the crisp value of inputs to be evaluated. t_norm: function Indicates the t-norm operator to be used, and should be chosen between min_t_norm, product_t_norm, or other user defined t-norms. s_norm: function Indicates the s-norm operator to be used, and should be chosen between max_s_norm or other user defined s-norms. domain: numpy (n,) shaped array Indicates the universe of discourse dedicated to the IT2FS. method="Centroid": str Indicates the type reduction method name and should be one of the methods listed below: Centroid, CoSet, CoSum, Height, and ModiHe. method_params=[]: List Parameters of the type reduction method, if needed. algorithm="EIASC": Indicates the type reduction algorithm name and should be one of the algorithms listed below: KM, EKM, WEKM, TWEKM, EIASC, WM, BMM, LBMM, and NT. algorithm_params=[]: List Parameters of the type reduction algorithm, if needed. Returns ------- It depends on which method and algorithm for type reduction is chosen. If Centroid type reduction method is chosen the output is a tuple with two elements. First element is the overall IT2FS outputs of the system as a dictionary with output names as keys and sets as values. The second output is outputs of the selected type reduction algorithm as a dictionary with output names as keys and type reduction algorithm function output as value. For other type reduction methods the only output is the dictionary of the type reduction algorithm function outputs for each output variable name as a key. Notes ----- While using the evaluate function some cares must be taken by the user himself which are listed as below: * The inputs must be lay in the defined universe of discourse. * The type reduction method and the type reduction algorithm must be selected from the lists provided in docstrings. """ if algorithm == "KM": alg_func = KM_algorithm elif algorithm == "EKM": alg_func = EKM_algorithm elif algorithm == "WEKM": alg_func = WEKM_algorithm elif algorithm == "TWEKM": alg_func = TWEKM_algorithm elif algorithm == "WM": alg_func = WM_algorithm elif algorithm == "LBMM": alg_func = LBMM_algorithm elif algorithm == "BMM": alg_func = BMM_algorithm elif algorithm == "NT": alg_func = NT_algorithm elif algorithm == "EIASC": alg_func = EIASC_algorithm else: raise ValueError("The " + algorithm + " algorithm is not implemented, yet!") if method == "Centroid": B = {out: [] for out in self.outputs} for rule in self.rules: u = 1 l = 1 for input_statement in rule[0]: u = t_norm(u, input_statement[1].umf(inputs[input_statement[0]], input_statement[1].umf_params)) l = t_norm(l, input_statement[1].lmf(inputs[input_statement[0]], input_statement[1].lmf_params)) for consequent in rule[1]: B_l = meet(consequent[1].domain, IT2FS(consequent[1].domain, const_mf, [u], const_mf, [l]), consequent[1], t_norm) B[consequent[0]].append(B_l) C = {out: IT2FS(B[out][0].domain) for out in self.outputs} TR = {} for out in self.outputs: for B_l in B[out]: C[out] = join(B_l.domain, C[out], B_l, s_norm) TR[out] = Centroid(C[out], alg_func, B_l.domain, alg_params=algorithm_params) return C, TR elif method == "CoSet": F = [] G = {out: [] for out in self.outputs} for rule in self.rules: u = 1 l = 1 for input_statement in rule[0]: u = t_norm(u, input_statement[1].umf(inputs[input_statement[0]], input_statement[1].umf_params)) l = t_norm(l, input_statement[1].lmf(inputs[input_statement[0]], input_statement[1].lmf_params)) F.append([l, u]) for consequent in rule[1]: G[consequent[0]].append(consequent[1]) TR = {} for out in self.outputs: TR[out] = CoSet(array(F), G[out], alg_func, G[out][0].domain, alg_params=algorithm_params) return TR elif method == "CoSum": B = {out: [] for out in self.outputs} for rule in self.rules: u = 1 l = 1 for input_statement in rule[0]: u = t_norm(u, input_statement[1].umf(inputs[input_statement[0]], input_statement[1].umf_params)) l = t_norm(l, input_statement[1].lmf(inputs[input_statement[0]], input_statement[1].lmf_params)) for consequent in rule[1]: B_l = meet(consequent[1].domain, IT2FS(consequent[1].domain, const_mf, [u], const_mf, [l]), consequent[1], t_norm) B[consequent[0]].append(B_l) TR = {} for out in self.outputs: TR[out] = CoSum(B[out], alg_func, B[out][0].domain, alg_params=algorithm_params) return TR elif method == "Height": B = {out: [] for out in self.outputs} for rule in self.rules: u = 1 l = 1 for input_statement in rule[0]: u = t_norm(u, input_statement[1].umf(inputs[input_statement[0]], input_statement[1].umf_params)) l = t_norm(l, input_statement[1].lmf(inputs[input_statement[0]], input_statement[1].lmf_params)) for consequent in rule[1]: B_l = meet(consequent[1].domain, IT2FS(consequent[1].domain, const_mf, [u], const_mf, [l]), consequent[1], t_norm) B[consequent[0]].append(B_l) TR = {} for out in self.outputs: TR[out] = Height(B[out], alg_func, B[out][0].domain, alg_params=algorithm_params) return TR elif method == "ModiHe": B = {out: [] for out in self.outputs} for rule in self.rules: u = 1 l = 1 for input_statement in rule[0]: u = t_norm(u, input_statement[1].umf(inputs[input_statement[0]], input_statement[1].umf_params)) l = t_norm(l, input_statement[1].lmf(inputs[input_statement[0]], input_statement[1].lmf_params)) for consequent in rule[1]: B_l = meet(consequent[1].domain, IT2FS(consequent[1].domain, const_mf, [u], const_mf, [l]), consequent[1], t_norm) B[consequent[0]].append(B_l) TR = {} for out in self.outputs: TR[out] = ModiHe(B[out], method_params, alg_func, B[out][0].domain, alg_params=algorithm_params) return TR else: raise ValueError("The method " + method + " is not implemented yet!") class IT2TSK: """ Interval type 2 TSK fuzzy logic system. Parameters ---------- Parameters of the constructor function: t_norm: function T-norm operator which would be used by FLS. s_norm: function S-norm operator which would be used bu FLS. Members ------- inputs: List of str List of the inputs name as str. output: List of str List of the outputs name as str. rules: List of tuples (antecedent, consequent) List of rules which each rule is defined as a tuple (antecedent, consequent) Both antacedent and consequent are lists of tuples. Each tuple of the antacedent list shows assignement of a variable to an IT2FS. First element of the tuple must be the input variable name as a str, and the second element must be an IT2FS. Each tuple of the consequent indicates assignement of a variable to an output state. First element of the tuple must be output vriable name as str, and the second element of the tuple must be a dictionary. This dictionary shows the output polynomial in the case of the rule. For example let an output polynomial be as 2 x1 + 4 x2 + 5. Then the dictionary for this case would be {"const":5., "x1":2., "x2":4.}. Note that this is written for an IT2 TSK FLS with two inputs, named x1 and x2. Functions --------- add_input_variable: Adds an input variable to the inputs list of the IT2 TSK FLS. add_output_variable: Adds an output variable to the outputs list of the IT2 TSK FLS. add_rule: Adds a rule to the rules list of the IT2 TSK FLS. copy: Returns a copy of the interval type 2 tsk fuzzy logic system. evaluate: Evaluates the IT2 TSK FLS based on the crisp inputs given by the user. Notes ----- While using the IT2TSK class the user must take care of the items listed below: * The UMF defined for an IT2FS must be greater than or equal with the LMF at all points of the discrete universe of discourse. * The inputs and outputs defined must be compatible while adding the rules and evluating the IT2FLS. """ def __init__(self, t_norm, s_norm): self.inputs = [] self.outputs = [] self.rules = [] self.__t_norm = t_norm self.__s_norm = s_norm if isThereTypereduction: self.algorithm = typereduction.EIASC_algorithm else: self.algorithm = EIASC_algorithm def __repr__(self): return "Interval type 2 TSK fuzzy logic system!" def add_input_variable(self, name): """ Adds new input variable name. Parameters ---------- name: str Name of the new input variable as a str. """ self.inputs.append(name) def add_output_variable(self, name): """ Adds new output variable name. Parameters ---------- name: str Name of the new output variable as a str. """ self.outputs.append(name) def add_rule(self, antecedent, consequent): """ Adds new rule to the rule base of the IT2FLS. Parameters ---------- antecedent: List of tuples Antecedent is a list of tuples in which each tuple indicates assignement of a variable to an IT2FS. First element of the tuple must be the input variable name as str, and the second element of the tuple must be an IT2FS. consequent: List of tuples Consequent is a list of tuples in which each tuple indicates assignement of a variable to an output state. First element of the tuple must be output vriable name as str, and the second element of the tuple must be a dictionary. This dictionary shows the output polynomial in the case of the rule. For example let an output polynomial be as 2 x1 + 4 x2 + 5. Then the dictionary for this case would be {"const":5., "x1":2., "x2":4.}. Note that this is written for an IT2 TSK FLS with two inputs, named x1 and x2. Example ------- Assume that we are going to simulate an IT2 TSK FLS with two inputs named x1 and x2. Our rule base is defined as below: * IF x1 is Small and x2 is Small THEN y1 = x1 + x2 + 1 and y2 = 2 x1 - x2 + 1 * IF x1 is Small and x2 is Big THEN y1 = 1.5 x1 + 0.5 x2 + 0.5 and y2 = 1.5 x1 - 0.5 x2 + 0.5 * IF x1 is Big and x2 is Small THEN y1 = 2. x1 + 0.1 x2 - 0.2 and y2 = 0.5 x1 + 0.1 x2 * IF x1 is Big and x2 is Big THEN y1 = 4. x1 -0.5 x2 - 1 and y2 = -0.5 x1 + x2 - 0.5 Then these rules can be added to the system using the codes below: >>> myIT2FLS.add_rule([("x1", Small), ("x2", Small)], [("y1", {"const":1., "x1":1., "x2":1.}), ("y2", {"const":1., "x1":2., "x2":-1.})]) >>> myIT2FLS.add_rule([("x1", Small), ("x2", Big)], [("y1", {"const":0.5, "x1":1.5, "x2":0.5}), ("y2", {"const":0.5, "x1":1.5, "x2":-0.5})]) >>> myIT2FLS.add_rule([("x1", Big), ("x2", Small)], [("y1", {"const":-0.2, "x1":2., "x2":0.1}), ("y2", {"const":0., "x1":0.5, "x2":0.1})]) >>> myIT2FLS.add_rule([("x1", Big), ("x2", Big)], [("y1", {"const":-1., "x1":4., "x2":-0.5}), ("y2", {"const":-0.5, "x1":-0.5, "x2":1.})]) """ self.rules.append((antecedent, consequent)) def copy(self): """ Returns a copy of the IT2FLS. """ o = IT2TSK(self.__t_norm, self.__s_norm) o.inputs = self.inputs.copy() o.outputs = self.outputs.copy() o.rules = self.rules.copy() return o def evaluate(self, inputs): """ Evaluates the IT2 TSK FLS based on the crisp inputs given by the user. Parameters ---------- inputs: dictionary Inputs is a dictionary, which the keys are input variable names as str and the values are the crisp value of the inputs to be evaluated. Returns ------- O: dictionary The output is a dictionary, which the keys are output variable names as str and the values are the crisp output of the system. """ F = [] B = {out: [] for out in self.outputs} for rule in self.rules: u = 1 l = 1 for input_statement in rule[0]: u = self.__t_norm(u, input_statement[1].umf(inputs[input_statement[0]], input_statement[1].umf_params)) l = self.__t_norm(l, input_statement[1].lmf(inputs[input_statement[0]], input_statement[1].lmf_params)) F.append([l, u]) for consequent in rule[1]: B[consequent[0]].append(consequent[1]["const"]) for input in self.inputs: # self.inputs -> Name of the input variables ... # inputs -> Dict of input and value pairs ... # consequent[1] -> dict of input and coefficient pairs ... B[consequent[0]][-1] += consequent[1][input] * inputs[input] O = {} for output in self.outputs: y = array(B[output]).reshape((len(B[output]), 1)) intervals = hstack([y, y, array(F)]) o = self.algorithm(intervals) O[output] = crisp(o) return O class IT2Mamdani: """ Interval Type 2 Mamadani Fuzzy Logic System. Parameters ---------- Parameters of the constructor function: t_norm: function T-norm operator which would be used by FLS. s_norm: function S-norm operator which would be used by FLS. method="Centroid": str Indicates the type reduction method name and should be one of the methods listed below: Centroid, CoSet, CoSum, Height, and ModiHe. method_params=[]: List Parameters of the type reduction method, if needed. algorithm="EIASC": str Indicates the type reduction algorithm name and should be one of the algorithms listed below: KM, EKM, WEKM, TWEKM, EIASC, WM, BMM, LBMM, and NT. algorithm_params=[]: List Parameters of the type reduction algorithm, if needed. Members ------- inputs: List of str List of the inputs name as str. output: List of str List of the outputs name as str. rules: List of tuples (antecedent, consequent) List of rules which each rule is defined as a tuple (antecedent, consequent) Both antacedent and consequent are lists of tuples. Each tuple of these lists shows assignement of a variable to an IT2FS. First element of the tuple must be variable name (input or output) as a str, and the second element must be an IT2FS. Functions --------- add_input_variable: Adds an input variable to the inputs list of the IT2 Mamdani FLS. add_output_variable: Adds an output variable to the outputs list of the IT2 Mamdani FLS. add_rule: Adds a rule to the rules list of the IT2 Mamdani FLS. copy: Returns a copy of the interval type 2 mamdani fuzzy logic system. evaluate: Evaluates the IT2FLS's output for a specified crisp input. This function is selected based on the constructor function parameter, method, among 5 private functions below: __Mamdani_Centroid, __Mamdani_CoSet, __Mamdani_CoSum, __Mamdani_Height, and __Mamdani_ModiHe. The only input of the evaluate function is a dictionary named inputs in which the keys are input variable names as str and the values are the crisp value of inputs to be evaluated. The output of the evaluate function is depended on the method selected while constructing the class. For more information, please refer to the examples. Notes ----- While using the IT2Mamdani class the user must take care of the items listed below: * The UMF defined for an IT2FS must be greater than or equal with the LMF at all points of the discrete universe of discourse. * The inputs and outputs defined must be compatible while adding the rules and evluating the IT2FLS. """ def __init__(self, t_norm, s_norm, method="Centroid", method_params=[], algorithm="EIASC", algorithm_params=[]): self.inputs = [] self.outputs = [] self.rules = [] self.__t_norm = t_norm self.__s_norm = s_norm self.__method = method self.__method_params = method_params if algorithm == "KM": if isThereTypereduction: self.__algorithm = typereduction.KM_algorithm else: self.__algorithm = KM_algorithm elif algorithm == "EKM": if isThereTypereduction: self.__algorithm = typereduction.EKM_algorithm else: self.__algorithm = EKM_algorithm elif algorithm == "WEKM": self.__algorithm = WEKM_algorithm elif algorithm == "TWEKM": self.__algorithm = TWEKM_algorithm elif algorithm == "EIASC": if isThereTypereduction: self.__algorithm = typereduction.EIASC_algorithm else: self.__algorithm = EIASC_algorithm elif algorithm == "WM": if isThereTypereduction: self.__algorithm = typereduction.WM_algorithm else: self.__algorithm = WM_algorithm elif algorithm == "BMM": self.__algorithm = BMM_algorithm elif algorithm == "LBMM": self.__algorithm = LBMM_algorithm elif algorithm == "NT": self.__algorithm = NT_algorithm elif callable(algorithm): self.__algorithm = algorithm else: raise ValueError("The algorithm, " + algorithm + ", is not implemented yet!") self.__algorithm_params = algorithm_params if method == "Centroid": self.evaluate = self.__Mamdani_Centroid elif method == "CoSet": self.evaluate = self.__Mamdani_CoSet elif method == "CoSum": self.evaluate = self.__Mamdani_CoSum elif method == "Height": self.evaluate = self.__Mamdani_Height elif method == "ModiHe": self.evaluate = self.__Mamdani_ModiHe else: raise ValueError("The method, " + method + ", is not implemented yet!") def __repr__(self): # TODO! pass def add_input_variable(self, name): """ Adds new input variable name. Parameters ---------- name: str Name of the new input variable as a str. """ self.inputs.append(name) def add_output_variable(self, name): """ Adds new output variable name. Parameters ---------- name: str Name of the new output variable as a str. """ self.outputs.append(name) def add_rule(self, antecedent, consequent): """ Adds new rule to the rule base of the IT2FLS. Parameters ---------- antecedent: List of tuples Antecedent is a list of tuples in which each tuple indicates assignement of a variable to an IT2FS. First element of the tuple must be input variable name as str, and the second element of the tuple must be an IT2FS. consequent: List of tuples Consequent is a list of tuples in which each tuple indicates assignement of a variable to an IT2FS. First element of the tuple must be output variable name as str, and the second element of the tuple must be an IT2FS. """ self.rules.append((antecedent, consequent)) def copy(self): """ Returns a copy of the IT2FLS. """ o = IT2Mamdani(self.__t_norm, self.__s_norm, self.__method, self.__method_params, self.__algorithm, self.__algorithm_params) o.inputs = self.inputs.copy() o.outputs = self.outputs.copy() o.rules = self.rules.copy() return o def __meet(self, domain, it2fs1, l, u, t_norm): umf = lambda x, params: t_norm(it2fs1.umf(x, it2fs1.umf_params), u) lmf = lambda x, params: t_norm(it2fs1.lmf(x, it2fs1.lmf_params), l) it2fs = IT2FS(domain, umf, [], lmf, []) return it2fs def __join(self, domain, it2fs1, l, u, s_norm): umf = lambda x, params: s_norm(it2fs1.umf(x, it2fs1.umf_params), u) lmf = lambda x, params: s_norm(it2fs1.lmf(x, it2fs1.lmf_params), l) it2fs = IT2FS(domain, umf, [], lmf, []) return it2fs def __Mamdani_Centroid(self, inputs): B = {out: [] for out in self.outputs} for rule in self.rules: u = 1 l = 1 for input_statement in rule[0]: u = self.__t_norm(u, input_statement[1].umf(inputs[input_statement[0]], input_statement[1].umf_params)) l = self.__t_norm(l, input_statement[1].lmf(inputs[input_statement[0]], input_statement[1].lmf_params)) for consequent in rule[1]: B_l = self.__meet(consequent[1].domain, consequent[1], l, u, self.__t_norm) B[consequent[0]].append(B_l) C = {out: IT2FS(B[out][0].domain) for out in self.outputs} TR = {} for out in self.outputs: for B_l in B[out]: C[out] = join(B_l.domain, C[out], B_l, self.__s_norm) TR[out] = Centroid(C[out], self.__algorithm, B_l.domain, alg_params=self.__algorithm_params) return C, TR def __Mamdani_CoSet(self, inputs): F = [] G = {out: [] for out in self.outputs} for rule in self.rules: u = 1 l = 1 for input_statement in rule[0]: u = self.__t_norm(u, input_statement[1].umf(inputs[input_statement[0]], input_statement[1].umf_params)) l = self.__t_norm(l, input_statement[1].lmf(inputs[input_statement[0]], input_statement[1].lmf_params)) F.append([l, u]) for consequent in rule[1]: G[consequent[0]].append(consequent[1]) TR = {} for out in self.outputs: TR[out] = CoSet(array(F), G[out], self.__algorithm, G[out][0].domain, alg_params=self.__algorithm_params) return TR def __Mamdani_CoSum(self, inputs): B = {out: [] for out in self.outputs} for rule in self.rules: u = 1 l = 1 for input_statement in rule[0]: u = self.__t_norm(u, input_statement[1].umf(inputs[input_statement[0]], input_statement[1].umf_params)) l = self.__t_norm(l, input_statement[1].lmf(inputs[input_statement[0]], input_statement[1].lmf_params)) for consequent in rule[1]: B_l = meet(consequent[1].domain, consequent[1], l, u, self.__t_norm) B[consequent[0]].append(B_l) TR = {} for out in self.outputs: TR[out] = CoSum(B[out], self.__algorithm, B[out][0].domain, alg_params=self.__algorithm_params) return TR def __Mamdani_Height(self, inputs): B = {out: [] for out in self.outputs} for rule in self.rules: u = 1 l = 1 for input_statement in rule[0]: u = self.__t_norm(u, input_statement[1].umf(inputs[input_statement[0]], input_statement[1].umf_params)) l = self.__t_norm(l, input_statement[1].lmf(inputs[input_statement[0]], input_statement[1].lmf_params)) for consequent in rule[1]: B_l = self.__meet(consequent[1].domain, consequent[1], l, u, self.__t_norm) B[consequent[0]].append(B_l) TR = {} for out in self.outputs: TR[out] = Height(B[out], self.__algorithm, B[out][0].domain, alg_params=self.__algorithm_params) return TR def __Mamdani_ModiHe(self, inputs): B = {out: [] for out in self.outputs} for rule in self.rules: u = 1 l = 1 for input_statement in rule[0]: u = self.__t_norm(u, input_statement[1].umf(inputs[input_statement[0]], input_statement[1].umf_params)) l = self.__t_norm(l, input_statement[1].lmf(inputs[input_statement[0]], input_statement[1].lmf_params)) for consequent in rule[1]: B_l = self.__meet(consequent[1].domain, consequent[1], l, u, self.__t_norm) B[consequent[0]].append(B_l) TR = {} for out in self.outputs: TR[out] = ModiHe(B[out], self.__method_params, self.__algorithm, B[out][0].domain, alg_params=self.__algorithm_params) return TR TSK = IT2TSK Mamdani = IT2Mamdani
[ "matplotlib.pyplot.title", "numpy.maximum", "numpy.sum", "numpy.abs", "numpy.argmax", "matplotlib.pyplot.figure", "numpy.arange", "numpy.exp", "matplotlib.pyplot.fill_between", "numpy.zeros_like", "numpy.multiply", "numpy.logical_not", "numpy.add", "numpy.minimum", "matplotlib.pyplot.sho...
[((1161, 1174), 'numpy.zeros_like', 'zeros_like', (['x'], {}), '(x)\n', (1171, 1174), False, 'from numpy import exp, ones_like, zeros_like, arange, multiply, subtract, add, minimum, maximum, sign, c_, argmax, array, where, hstack, logical_not, sqrt\n'), ((2024, 2059), 'numpy.multiply', 'multiply', (['params[1]', '(x == params[0])'], {}), '(params[1], x == params[0])\n', (2032, 2059), False, 'from numpy import exp, ones_like, zeros_like, arange, multiply, subtract, add, minimum, maximum, sign, c_, argmax, array, where, hstack, logical_not, sqrt\n'), ((24786, 24798), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (24796, 24798), True, 'import matplotlib.pyplot as plt\n'), ((24997, 25015), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['xlabel'], {}), '(xlabel)\n', (25007, 25015), True, 'import matplotlib.pyplot as plt\n'), ((25020, 25038), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['ylabel'], {}), '(ylabel)\n', (25030, 25038), True, 'import matplotlib.pyplot as plt\n'), ((25043, 25057), 'matplotlib.pyplot.grid', 'plt.grid', (['grid'], {}), '(grid)\n', (25051, 25057), True, 'import matplotlib.pyplot as plt\n'), ((25175, 25185), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (25183, 25185), True, 'import matplotlib.pyplot as plt\n'), ((55932, 55944), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (55942, 55944), True, 'import matplotlib.pyplot as plt\n'), ((56296, 56314), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['xlabel'], {}), '(xlabel)\n', (56306, 56314), True, 'import matplotlib.pyplot as plt\n'), ((56319, 56337), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['ylabel'], {}), '(ylabel)\n', (56329, 56337), True, 'import matplotlib.pyplot as plt\n'), ((56342, 56356), 'matplotlib.pyplot.grid', 'plt.grid', (['grid'], {}), '(grid)\n', (56350, 56356), True, 'import matplotlib.pyplot as plt\n'), ((56474, 56484), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (56482, 56484), True, 'import matplotlib.pyplot as plt\n'), ((57816, 57828), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (57826, 57828), True, 'import matplotlib.pyplot as plt\n'), ((57991, 58009), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['xlabel'], {}), '(xlabel)\n', (58001, 58009), True, 'import matplotlib.pyplot as plt\n'), ((58014, 58032), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['ylabel'], {}), '(ylabel)\n', (58024, 58032), True, 'import matplotlib.pyplot as plt\n'), ((58144, 58158), 'matplotlib.pyplot.grid', 'plt.grid', (['grid'], {}), '(grid)\n', (58152, 58158), True, 'import matplotlib.pyplot as plt\n'), ((58276, 58286), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (58284, 58286), True, 'import matplotlib.pyplot as plt\n'), ((60003, 60016), 'numpy.minimum', 'minimum', (['a', 'b'], {}), '(a, b)\n', (60010, 60016), False, 'from numpy import exp, ones_like, zeros_like, arange, multiply, subtract, add, minimum, maximum, sign, c_, argmax, array, where, hstack, logical_not, sqrt\n'), ((60422, 60436), 'numpy.multiply', 'multiply', (['a', 'b'], {}), '(a, b)\n', (60430, 60436), False, 'from numpy import exp, ones_like, zeros_like, arange, multiply, subtract, add, minimum, maximum, sign, c_, argmax, array, where, hstack, logical_not, sqrt\n'), ((60857, 60878), 'numpy.maximum', 'maximum', (['(0)', '(a + b - 1)'], {}), '(0, a + b - 1)\n', (60864, 60878), False, 'from numpy import exp, ones_like, zeros_like, arange, multiply, subtract, add, minimum, maximum, sign, c_, argmax, array, where, hstack, logical_not, sqrt\n'), ((62682, 62695), 'numpy.maximum', 'maximum', (['a', 'b'], {}), '(a, b)\n', (62689, 62695), False, 'from numpy import exp, ones_like, zeros_like, arange, multiply, subtract, add, minimum, maximum, sign, c_, argmax, array, where, hstack, logical_not, sqrt\n'), ((63526, 63543), 'numpy.minimum', 'minimum', (['(a + b)', '(1)'], {}), '(a + b, 1)\n', (63533, 63543), False, 'from numpy import exp, ones_like, zeros_like, arange, multiply, subtract, add, minimum, maximum, sign, c_, argmax, array, where, hstack, logical_not, sqrt\n'), ((67391, 67403), 'numpy.where', 'where', (['(v > 0)'], {}), '(v > 0)\n', (67396, 67403), False, 'from numpy import exp, ones_like, zeros_like, arange, multiply, subtract, add, minimum, maximum, sign, c_, argmax, array, where, hstack, logical_not, sqrt\n'), ((68468, 68496), 'numpy.sum', 'npsum', (['(intervals[:, 0] * w_l)'], {}), '(intervals[:, 0] * w_l)\n', (68473, 68496), True, 'from numpy import sum as npsum\n'), ((68515, 68525), 'numpy.sum', 'npsum', (['w_l'], {}), '(w_l)\n', (68520, 68525), True, 'from numpy import sum as npsum\n'), ((69314, 69342), 'numpy.sum', 'npsum', (['(intervals[:, 1] * w_r)'], {}), '(intervals[:, 1] * w_r)\n', (69319, 69342), True, 'from numpy import sum as npsum\n'), ((77507, 77547), 'numpy.sum', 'npsum', (['(intervals[:, 0] * intervals[:, 2])'], {}), '(intervals[:, 0] * intervals[:, 2])\n', (77512, 77547), True, 'from numpy import sum as npsum\n'), ((77558, 77580), 'numpy.sum', 'npsum', (['intervals[:, 2]'], {}), '(intervals[:, 2])\n', (77563, 77580), True, 'from numpy import sum as npsum\n'), ((77921, 77961), 'numpy.sum', 'npsum', (['(intervals[:, 1] * intervals[:, 2])'], {}), '(intervals[:, 1] * intervals[:, 2])\n', (77926, 77961), True, 'from numpy import sum as npsum\n'), ((77972, 77994), 'numpy.sum', 'npsum', (['intervals[:, 2]'], {}), '(intervals[:, 2])\n', (77977, 77994), True, 'from numpy import sum as npsum\n'), ((85491, 85509), 'numpy.zeros_like', 'zeros_like', (['domain'], {}), '(domain)\n', (85501, 85509), False, 'from numpy import exp, ones_like, zeros_like, arange, multiply, subtract, add, minimum, maximum, sign, c_, argmax, array, where, hstack, logical_not, sqrt\n'), ((85526, 85544), 'numpy.zeros_like', 'zeros_like', (['domain'], {}), '(domain)\n', (85536, 85544), False, 'from numpy import exp, ones_like, zeros_like, arange, multiply, subtract, add, minimum, maximum, sign, c_, argmax, array, where, hstack, logical_not, sqrt\n'), ((2776, 2788), 'numpy.ones_like', 'ones_like', (['x'], {}), '(x)\n', (2785, 2788), False, 'from numpy import exp, ones_like, zeros_like, arange, multiply, subtract, add, minimum, maximum, sign, c_, argmax, array, where, hstack, logical_not, sqrt\n'), ((3625, 3793), 'numpy.maximum', 'maximum', (['(0)', '(params[3] * (x - params[0]) / (params[1] - params[0]) * (x <= params[1]) +\n params[3] * ((params[2] - x) / (params[2] - params[1])) * (x > params[1]))'], {}), '(0, params[3] * (x - params[0]) / (params[1] - params[0]) * (x <=\n params[1]) + params[3] * ((params[2] - x) / (params[2] - params[1])) *\n (x > params[1]))\n', (3632, 3793), False, 'from numpy import exp, ones_like, zeros_like, arange, multiply, subtract, add, minimum, maximum, sign, c_, argmax, array, where, hstack, logical_not, sqrt\n'), ((4631, 4752), 'numpy.maximum', 'maximum', (['(0)', '(params[2] * (x <= params[1]) + params[2] * ((params[0] - x) / (params[0] -\n params[1])) * (x > params[1]))'], {}), '(0, params[2] * (x <= params[1]) + params[2] * ((params[0] - x) / (\n params[0] - params[1])) * (x > params[1]))\n', (4638, 4752), False, 'from numpy import exp, ones_like, zeros_like, arange, multiply, subtract, add, minimum, maximum, sign, c_, argmax, array, where, hstack, logical_not, sqrt\n'), ((5586, 5704), 'numpy.maximum', 'maximum', (['(0)', '(params[2] * (x - params[0]) / (params[1] - params[0]) * (x <= params[1]) +\n params[2] * (x > params[1]))'], {}), '(0, params[2] * (x - params[0]) / (params[1] - params[0]) * (x <=\n params[1]) + params[2] * (x > params[1]))\n', (5593, 5704), False, 'from numpy import exp, ones_like, zeros_like, arange, multiply, subtract, add, minimum, maximum, sign, c_, argmax, array, where, hstack, logical_not, sqrt\n'), ((6613, 6834), 'numpy.maximum', 'maximum', (['(0)', '(params[4] * ((x - params[0]) / (params[1] - params[0])) * (x <= params[1]) +\n params[4] * ((params[3] - x) / (params[3] - params[2])) * (x >= params[\n 2]) + params[4] * ((x > params[1]) * (x < params[2])))'], {}), '(0, params[4] * ((x - params[0]) / (params[1] - params[0])) * (x <=\n params[1]) + params[4] * ((params[3] - x) / (params[3] - params[2])) *\n (x >= params[2]) + params[4] * ((x > params[1]) * (x < params[2])))\n', (6620, 6834), False, 'from numpy import exp, ones_like, zeros_like, arange, multiply, subtract, add, minimum, maximum, sign, c_, argmax, array, where, hstack, logical_not, sqrt\n'), ((7706, 7757), 'numpy.exp', 'exp', (['(-((params[0] - x) ** 2 / (2 * params[1] ** 2)))'], {}), '(-((params[0] - x) ** 2 / (2 * params[1] ** 2)))\n', (7709, 7757), False, 'from numpy import exp, ones_like, zeros_like, arange, multiply, subtract, add, minimum, maximum, sign, c_, argmax, array, where, hstack, logical_not, sqrt\n'), ((22474, 22486), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (22484, 22486), True, 'import matplotlib.pyplot as plt\n'), ((22693, 22711), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['xlabel'], {}), '(xlabel)\n', (22703, 22711), True, 'import matplotlib.pyplot as plt\n'), ((22720, 22738), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['ylabel'], {}), '(ylabel)\n', (22730, 22738), True, 'import matplotlib.pyplot as plt\n'), ((22747, 22761), 'matplotlib.pyplot.grid', 'plt.grid', (['grid'], {}), '(grid)\n', (22755, 22761), True, 'import matplotlib.pyplot as plt\n'), ((22891, 22901), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (22899, 22901), True, 'import matplotlib.pyplot as plt\n'), ((24922, 24941), 'matplotlib.pyplot.legend', 'plt.legend', (['legends'], {}), '(legends)\n', (24932, 24941), True, 'import matplotlib.pyplot as plt\n'), ((24976, 24992), 'matplotlib.pyplot.title', 'plt.title', (['title'], {}), '(title)\n', (24985, 24992), True, 'import matplotlib.pyplot as plt\n'), ((25095, 25170), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(filename + '.' + ext)"], {'format': 'ext', 'dpi': '(300)', 'bbox_inches': '"""tight"""'}), "(filename + '.' + ext, format=ext, dpi=300, bbox_inches='tight')\n", (25106, 25170), True, 'import matplotlib.pyplot as plt\n'), ((41357, 41365), 'numpy.sum', 'npsum', (['F'], {}), '(F)\n', (41362, 41365), True, 'from numpy import sum as npsum\n'), ((45946, 45958), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (45956, 45958), True, 'import matplotlib.pyplot as plt\n'), ((45967, 46020), 'matplotlib.pyplot.fill_between', 'plt.fill_between', (['self.domain', 'self.upper', 'self.lower'], {}), '(self.domain, self.upper, self.lower)\n', (45983, 46020), True, 'import matplotlib.pyplot as plt\n'), ((46162, 46210), 'matplotlib.pyplot.plot', 'plt.plot', (['self.domain', 'self.upper'], {'color': '"""black"""'}), "(self.domain, self.upper, color='black')\n", (46170, 46210), True, 'import matplotlib.pyplot as plt\n'), ((46219, 46267), 'matplotlib.pyplot.plot', 'plt.plot', (['self.domain', 'self.lower'], {'color': '"""black"""'}), "(self.domain, self.lower, color='black')\n", (46227, 46267), True, 'import matplotlib.pyplot as plt\n'), ((46276, 46290), 'matplotlib.pyplot.grid', 'plt.grid', (['grid'], {}), '(grid)\n', (46284, 46290), True, 'import matplotlib.pyplot as plt\n'), ((46299, 46317), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['xlabel'], {}), '(xlabel)\n', (46309, 46317), True, 'import matplotlib.pyplot as plt\n'), ((46326, 46344), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['ylabel'], {}), '(ylabel)\n', (46336, 46344), True, 'import matplotlib.pyplot as plt\n'), ((46474, 46484), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (46482, 46484), True, 'import matplotlib.pyplot as plt\n'), ((55976, 56043), 'matplotlib.pyplot.fill_between', 'plt.fill_between', (['it2fs.domain', 'it2fs.upper', 'it2fs.lower'], {'alpha': '(0.5)'}), '(it2fs.domain, it2fs.upper, it2fs.lower, alpha=0.5)\n', (55992, 56043), True, 'import matplotlib.pyplot as plt\n'), ((56080, 56099), 'matplotlib.pyplot.legend', 'plt.legend', (['legends'], {}), '(legends)\n', (56090, 56099), True, 'import matplotlib.pyplot as plt\n'), ((56131, 56181), 'matplotlib.pyplot.plot', 'plt.plot', (['it2fs.domain', 'it2fs.lower'], {'color': '"""black"""'}), "(it2fs.domain, it2fs.lower, color='black')\n", (56139, 56181), True, 'import matplotlib.pyplot as plt\n'), ((56190, 56240), 'matplotlib.pyplot.plot', 'plt.plot', (['it2fs.domain', 'it2fs.upper'], {'color': '"""black"""'}), "(it2fs.domain, it2fs.upper, color='black')\n", (56198, 56240), True, 'import matplotlib.pyplot as plt\n'), ((56275, 56291), 'matplotlib.pyplot.title', 'plt.title', (['title'], {}), '(title)\n', (56284, 56291), True, 'import matplotlib.pyplot as plt\n'), ((56394, 56469), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(filename + '.' + ext)"], {'format': 'ext', 'dpi': '(300)', 'bbox_inches': '"""tight"""'}), "(filename + '.' + ext, format=ext, dpi=300, bbox_inches='tight')\n", (56405, 56469), True, 'import matplotlib.pyplot as plt\n'), ((58067, 58083), 'matplotlib.pyplot.title', 'plt.title', (['title'], {}), '(title)\n', (58076, 58083), True, 'import matplotlib.pyplot as plt\n'), ((58119, 58139), 'matplotlib.pyplot.legend', 'plt.legend', (['[legend]'], {}), '([legend])\n', (58129, 58139), True, 'import matplotlib.pyplot as plt\n'), ((58196, 58271), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(filename + '.' + ext)"], {'format': 'ext', 'dpi': '(300)', 'bbox_inches': '"""tight"""'}), "(filename + '.' + ext, format=ext, dpi=300, bbox_inches='tight')\n", (58207, 58271), True, 'import matplotlib.pyplot as plt\n'), ((61755, 61768), 'numpy.minimum', 'minimum', (['a', 'b'], {}), '(a, b)\n', (61762, 61768), False, 'from numpy import exp, ones_like, zeros_like, arange, multiply, subtract, add, minimum, maximum, sign, c_, argmax, array, where, hstack, logical_not, sqrt\n'), ((62253, 62285), 'numpy.logical_not', 'logical_not', (['((a == 0) * (b == 0))'], {}), '((a == 0) * (b == 0))\n', (62264, 62285), False, 'from numpy import exp, ones_like, zeros_like, arange, multiply, subtract, add, minimum, maximum, sign, c_, argmax, array, where, hstack, logical_not, sqrt\n'), ((67546, 67558), 'numpy.where', 'where', (['(v > 0)'], {}), '(v > 0)\n', (67551, 67558), False, 'from numpy import exp, ones_like, zeros_like, arange, multiply, subtract, add, minimum, maximum, sign, c_, argmax, array, where, hstack, logical_not, sqrt\n'), ((68891, 68900), 'numpy.arange', 'arange', (['N'], {}), '(N)\n', (68897, 68900), False, 'from numpy import exp, ones_like, zeros_like, arange, multiply, subtract, add, minimum, maximum, sign, c_, argmax, array, where, hstack, logical_not, sqrt\n'), ((68994, 69022), 'numpy.sum', 'npsum', (['(intervals[:, 0] * w_l)'], {}), '(intervals[:, 0] * w_l)\n', (68999, 69022), True, 'from numpy import sum as npsum\n'), ((69041, 69051), 'numpy.sum', 'npsum', (['w_l'], {}), '(w_l)\n', (69046, 69051), True, 'from numpy import sum as npsum\n'), ((69095, 69133), 'math.isclose', 'isclose', (['y_l', 'y_l_prime'], {'abs_tol': '(1e-06)'}), '(y_l, y_l_prime, abs_tol=1e-06)\n', (69102, 69133), False, 'from math import isclose\n'), ((69703, 69712), 'numpy.arange', 'arange', (['N'], {}), '(N)\n', (69709, 69712), False, 'from numpy import exp, ones_like, zeros_like, arange, multiply, subtract, add, minimum, maximum, sign, c_, argmax, array, where, hstack, logical_not, sqrt\n'), ((69806, 69834), 'numpy.sum', 'npsum', (['(intervals[:, 1] * w_r)'], {}), '(intervals[:, 1] * w_r)\n', (69811, 69834), True, 'from numpy import sum as npsum\n'), ((69853, 69863), 'numpy.sum', 'npsum', (['w_r'], {}), '(w_r)\n', (69858, 69863), True, 'from numpy import sum as npsum\n'), ((69907, 69945), 'math.isclose', 'isclose', (['y_r', 'y_r_prime'], {'abs_tol': '(1e-06)'}), '(y_r, y_r_prime, abs_tol=1e-06)\n', (69914, 69945), False, 'from math import isclose\n'), ((70648, 70694), 'numpy.sum', 'npsum', (['(intervals[:k_l, 0] * intervals[:k_l, 3])'], {}), '(intervals[:k_l, 0] * intervals[:k_l, 3])\n', (70653, 70694), True, 'from numpy import sum as npsum\n'), ((70709, 70755), 'numpy.sum', 'npsum', (['(intervals[k_l:, 0] * intervals[k_l:, 2])'], {}), '(intervals[k_l:, 0] * intervals[k_l:, 2])\n', (70714, 70755), True, 'from numpy import sum as npsum\n'), ((70766, 70791), 'numpy.sum', 'npsum', (['intervals[:k_l, 3]'], {}), '(intervals[:k_l, 3])\n', (70771, 70791), True, 'from numpy import sum as npsum\n'), ((70794, 70819), 'numpy.sum', 'npsum', (['intervals[k_l:, 2]'], {}), '(intervals[k_l:, 2])\n', (70799, 70819), True, 'from numpy import sum as npsum\n'), ((71273, 71294), 'numpy.sign', 'sign', (['(k_l_prime - k_l)'], {}), '(k_l_prime - k_l)\n', (71277, 71294), False, 'from numpy import exp, ones_like, zeros_like, arange, multiply, subtract, add, minimum, maximum, sign, c_, argmax, array, where, hstack, logical_not, sqrt\n'), ((71896, 71942), 'numpy.sum', 'npsum', (['(intervals[:k_r, 1] * intervals[:k_r, 2])'], {}), '(intervals[:k_r, 1] * intervals[:k_r, 2])\n', (71901, 71942), True, 'from numpy import sum as npsum\n'), ((71957, 72003), 'numpy.sum', 'npsum', (['(intervals[k_r:, 1] * intervals[k_r:, 3])'], {}), '(intervals[k_r:, 1] * intervals[k_r:, 3])\n', (71962, 72003), True, 'from numpy import sum as npsum\n'), ((72014, 72039), 'numpy.sum', 'npsum', (['intervals[:k_r, 2]'], {}), '(intervals[:k_r, 2])\n', (72019, 72039), True, 'from numpy import sum as npsum\n'), ((72042, 72067), 'numpy.sum', 'npsum', (['intervals[k_r:, 3]'], {}), '(intervals[k_r:, 3])\n', (72047, 72067), True, 'from numpy import sum as npsum\n'), ((72532, 72553), 'numpy.sign', 'sign', (['(k_r_prime - k_r)'], {}), '(k_r_prime - k_r)\n', (72536, 72553), False, 'from numpy import exp, ones_like, zeros_like, arange, multiply, subtract, add, minimum, maximum, sign, c_, argmax, array, where, hstack, logical_not, sqrt\n'), ((72657, 72746), 'numpy.sum', 'npsum', (['(intervals[imin:imax, 1] * (intervals[imin:imax, 3] - intervals[imin:imax, 2]))'], {}), '(intervals[imin:imax, 1] * (intervals[imin:imax, 3] - intervals[imin:\n imax, 2]))\n', (72662, 72746), True, 'from numpy import sum as npsum\n'), ((72789, 72845), 'numpy.sum', 'npsum', (['(intervals[imin:imax, 3] - intervals[imin:imax, 2])'], {}), '(intervals[imin:imax, 3] - intervals[imin:imax, 2])\n', (72794, 72845), True, 'from numpy import sum as npsum\n'), ((74422, 74443), 'numpy.sign', 'sign', (['(k_l_prime - k_l)'], {}), '(k_l_prime - k_l)\n', (74426, 74443), False, 'from numpy import exp, ones_like, zeros_like, arange, multiply, subtract, add, minimum, maximum, sign, c_, argmax, array, where, hstack, logical_not, sqrt\n'), ((75766, 75787), 'numpy.sign', 'sign', (['(k_r_prime - k_r)'], {}), '(k_r_prime - k_r)\n', (75770, 75787), False, 'from numpy import exp, ones_like, zeros_like, arange, multiply, subtract, add, minimum, maximum, sign, c_, argmax, array, where, hstack, logical_not, sqrt\n'), ((79097, 79121), 'numpy.sum', 'npsum', (['(F[:, 1] - F[:, 0])'], {}), '(F[:, 1] - F[:, 0])\n', (79102, 79121), True, 'from numpy import sum as npsum\n'), ((84441, 84457), 'numpy.array', 'array', (['intervals'], {}), '(intervals)\n', (84446, 84457), False, 'from numpy import exp, ones_like, zeros_like, arange, multiply, subtract, add, minimum, maximum, sign, c_, argmax, array, where, hstack, logical_not, sqrt\n'), ((85583, 85625), 'numpy.add', 'add', (['lower_sum', 'it2fs.lower'], {'out': 'lower_sum'}), '(lower_sum, it2fs.lower, out=lower_sum)\n', (85586, 85625), False, 'from numpy import exp, ones_like, zeros_like, arange, multiply, subtract, add, minimum, maximum, sign, c_, argmax, array, where, hstack, logical_not, sqrt\n'), ((85634, 85676), 'numpy.add', 'add', (['upper_sum', 'it2fs.lower'], {'out': 'upper_sum'}), '(upper_sum, it2fs.lower, out=upper_sum)\n', (85637, 85676), False, 'from numpy import exp, ones_like, zeros_like, arange, multiply, subtract, add, minimum, maximum, sign, c_, argmax, array, where, hstack, logical_not, sqrt\n'), ((86833, 86852), 'numpy.argmax', 'argmax', (['it2fs.upper'], {}), '(it2fs.upper)\n', (86839, 86852), False, 'from numpy import exp, ones_like, zeros_like, arange, multiply, subtract, add, minimum, maximum, sign, c_, argmax, array, where, hstack, logical_not, sqrt\n'), ((86970, 86986), 'numpy.array', 'array', (['intervals'], {}), '(intervals)\n', (86975, 86986), False, 'from numpy import exp, ones_like, zeros_like, arange, multiply, subtract, add, minimum, maximum, sign, c_, argmax, array, where, hstack, logical_not, sqrt\n'), ((88194, 88213), 'numpy.argmax', 'argmax', (['it2fs.upper'], {}), '(it2fs.upper)\n', (88200, 88213), False, 'from numpy import exp, ones_like, zeros_like, arange, multiply, subtract, add, minimum, maximum, sign, c_, argmax, array, where, hstack, logical_not, sqrt\n'), ((88444, 88460), 'numpy.array', 'array', (['intervals'], {}), '(intervals)\n', (88449, 88460), False, 'from numpy import exp, ones_like, zeros_like, arange, multiply, subtract, add, minimum, maximum, sign, c_, argmax, array, where, hstack, logical_not, sqrt\n'), ((16683, 16707), 'numpy.logical_not', 'logical_not', (['to_evaluate'], {}), '(to_evaluate)\n', (16694, 16707), False, 'from numpy import exp, ones_like, zeros_like, arange, multiply, subtract, add, minimum, maximum, sign, c_, argmax, array, where, hstack, logical_not, sqrt\n'), ((17731, 17755), 'numpy.logical_not', 'logical_not', (['to_evaluate'], {}), '(to_evaluate)\n', (17742, 17755), False, 'from numpy import exp, ones_like, zeros_like, arange, multiply, subtract, add, minimum, maximum, sign, c_, argmax, array, where, hstack, logical_not, sqrt\n'), ((22600, 22625), 'matplotlib.pyplot.legend', 'plt.legend', (['[legend_text]'], {}), '([legend_text])\n', (22610, 22625), True, 'import matplotlib.pyplot as plt\n'), ((22668, 22684), 'matplotlib.pyplot.title', 'plt.title', (['title'], {}), '(title)\n', (22677, 22684), True, 'import matplotlib.pyplot as plt\n'), ((22807, 22882), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(filename + '.' + ext)"], {'format': 'ext', 'dpi': '(300)', 'bbox_inches': '"""tight"""'}), "(filename + '.' + ext, format=ext, dpi=300, bbox_inches='tight')\n", (22818, 22882), True, 'import matplotlib.pyplot as plt\n'), ((46069, 46094), 'matplotlib.pyplot.legend', 'plt.legend', (['[legend_text]'], {}), '([legend_text])\n', (46079, 46094), True, 'import matplotlib.pyplot as plt\n'), ((46137, 46153), 'matplotlib.pyplot.title', 'plt.title', (['title'], {}), '(title)\n', (46146, 46153), True, 'import matplotlib.pyplot as plt\n'), ((46390, 46465), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(filename + '.' + ext)"], {'format': 'ext', 'dpi': '(300)', 'bbox_inches': '"""tight"""'}), "(filename + '.' + ext, format=ext, dpi=300, bbox_inches='tight')\n", (46401, 46465), True, 'import matplotlib.pyplot as plt\n'), ((64401, 64414), 'numpy.maximum', 'maximum', (['a', 'b'], {}), '(a, b)\n', (64408, 64414), False, 'from numpy import exp, ones_like, zeros_like, arange, multiply, subtract, add, minimum, maximum, sign, c_, argmax, array, where, hstack, logical_not, sqrt\n'), ((77783, 77812), 'math.isclose', 'isclose', (['y_l', 'intervals[L, 0]'], {}), '(y_l, intervals[L, 0])\n', (77790, 77812), False, 'from math import isclose\n'), ((78201, 78230), 'math.isclose', 'isclose', (['y_r', 'intervals[R, 1]'], {}), '(y_r, intervals[R, 1])\n', (78208, 78230), False, 'from math import isclose\n'), ((78861, 78885), 'numpy.sum', 'npsum', (['(F[:, 0] * Y[:, 0])'], {}), '(F[:, 0] * Y[:, 0])\n', (78866, 78885), True, 'from numpy import sum as npsum\n'), ((78888, 78902), 'numpy.sum', 'npsum', (['F[:, 0]'], {}), '(F[:, 0])\n', (78893, 78902), True, 'from numpy import sum as npsum\n'), ((78923, 78947), 'numpy.sum', 'npsum', (['(F[:, 1] * Y[:, 0])'], {}), '(F[:, 1] * Y[:, 0])\n', (78928, 78947), True, 'from numpy import sum as npsum\n'), ((78950, 78964), 'numpy.sum', 'npsum', (['F[:, 1]'], {}), '(F[:, 1])\n', (78955, 78964), True, 'from numpy import sum as npsum\n'), ((78984, 79008), 'numpy.sum', 'npsum', (['(F[:, 1] * Y[:, 1])'], {}), '(F[:, 1] * Y[:, 1])\n', (78989, 79008), True, 'from numpy import sum as npsum\n'), ((79011, 79025), 'numpy.sum', 'npsum', (['F[:, 1]'], {}), '(F[:, 1])\n', (79016, 79025), True, 'from numpy import sum as npsum\n'), ((79046, 79070), 'numpy.sum', 'npsum', (['(F[:, 0] * Y[:, 1])'], {}), '(F[:, 0] * Y[:, 1])\n', (79051, 79070), True, 'from numpy import sum as npsum\n'), ((79073, 79087), 'numpy.sum', 'npsum', (['F[:, 0]'], {}), '(F[:, 0])\n', (79078, 79087), True, 'from numpy import sum as npsum\n'), ((79125, 79139), 'numpy.sum', 'npsum', (['F[:, 0]'], {}), '(F[:, 0])\n', (79130, 79139), True, 'from numpy import sum as npsum\n'), ((79142, 79156), 'numpy.sum', 'npsum', (['F[:, 1]'], {}), '(F[:, 1])\n', (79147, 79156), True, 'from numpy import sum as npsum\n'), ((80389, 80403), 'numpy.sum', 'npsum', (['F[:, 0]'], {}), '(F[:, 0])\n', (80394, 80403), True, 'from numpy import sum as npsum\n'), ((80431, 80445), 'numpy.sum', 'npsum', (['F[:, 1]'], {}), '(F[:, 1])\n', (80436, 80445), True, 'from numpy import sum as npsum\n'), ((81290, 81304), 'numpy.sum', 'npsum', (['F[:, 0]'], {}), '(F[:, 0])\n', (81295, 81304), True, 'from numpy import sum as npsum\n'), ((81338, 81352), 'numpy.sum', 'npsum', (['F[:, 1]'], {}), '(F[:, 1])\n', (81343, 81352), True, 'from numpy import sum as npsum\n'), ((81971, 81989), 'numpy.sum', 'npsum', (['(Y * F[:, 1])'], {}), '(Y * F[:, 1])\n', (81976, 81989), True, 'from numpy import sum as npsum\n'), ((81992, 82010), 'numpy.sum', 'npsum', (['(Y * F[:, 0])'], {}), '(Y * F[:, 0])\n', (81997, 82010), True, 'from numpy import sum as npsum\n'), ((82015, 82029), 'numpy.sum', 'npsum', (['F[:, 0]'], {}), '(F[:, 0])\n', (82020, 82029), True, 'from numpy import sum as npsum\n'), ((82032, 82046), 'numpy.sum', 'npsum', (['F[:, 1]'], {}), '(F[:, 1])\n', (82037, 82046), True, 'from numpy import sum as npsum\n'), ((18713, 18747), 'numpy.abs', 'npabs', (['((x - params[2]) / params[0])'], {}), '((x - params[2]) / params[0])\n', (18718, 18747), True, 'from numpy import abs as npabs\n'), ((68727, 68762), 'math.isclose', 'isclose', (['intervals[i, 0]', 'y_l_prime'], {}), '(intervals[i, 0], y_l_prime)\n', (68734, 68762), False, 'from math import isclose\n'), ((68784, 68823), 'math.isclose', 'isclose', (['y_l_prime', 'intervals[i + 1, 0]'], {}), '(y_l_prime, intervals[i + 1, 0])\n', (68791, 68823), False, 'from math import isclose\n'), ((69539, 69574), 'math.isclose', 'isclose', (['intervals[i, 1]', 'y_r_prime'], {}), '(intervals[i, 1], y_r_prime)\n', (69546, 69574), False, 'from math import isclose\n'), ((69596, 69635), 'math.isclose', 'isclose', (['y_r_prime', 'intervals[i + 1, 1]'], {}), '(y_r_prime, intervals[i + 1, 1])\n', (69603, 69635), False, 'from math import isclose\n'), ((71004, 71054), 'math.isclose', 'isclose', (['intervals[i, 0]', 'y_l_prime'], {'abs_tol': '(1e-06)'}), '(intervals[i, 0], y_l_prime, abs_tol=1e-06)\n', (71011, 71054), False, 'from math import isclose\n'), ((71077, 71131), 'math.isclose', 'isclose', (['y_l_prime', 'intervals[i + 1, 0]'], {'abs_tol': '(1e-06)'}), '(y_l_prime, intervals[i + 1, 0], abs_tol=1e-06)\n', (71084, 71131), False, 'from math import isclose\n'), ((71410, 71499), 'numpy.sum', 'npsum', (['(intervals[imin:imax, 0] * (intervals[imin:imax, 3] - intervals[imin:imax, 2]))'], {}), '(intervals[imin:imax, 0] * (intervals[imin:imax, 3] - intervals[imin:\n imax, 2]))\n', (71415, 71499), True, 'from numpy import sum as npsum\n'), ((71571, 71627), 'numpy.sum', 'npsum', (['(intervals[imin:imax, 3] - intervals[imin:imax, 2])'], {}), '(intervals[imin:imax, 3] - intervals[imin:imax, 2])\n', (71576, 71627), True, 'from numpy import sum as npsum\n'), ((72254, 72304), 'math.isclose', 'isclose', (['intervals[i, 1]', 'y_r_prime'], {'abs_tol': '(1e-06)'}), '(intervals[i, 1], y_r_prime, abs_tol=1e-06)\n', (72261, 72304), False, 'from math import isclose\n'), ((72327, 72381), 'math.isclose', 'isclose', (['y_r_prime', 'intervals[i + 1, 1]'], {'abs_tol': '(1e-06)'}), '(y_r_prime, intervals[i + 1, 1], abs_tol=1e-06)\n', (72334, 72381), False, 'from math import isclose\n'), ((74179, 74218), 'math.isclose', 'isclose', (['intervals[i - 1, 0]', 'y_l_prime'], {}), '(intervals[i - 1, 0], y_l_prime)\n', (74186, 74218), False, 'from math import isclose\n'), ((74240, 74275), 'math.isclose', 'isclose', (['y_l_prime', 'intervals[i, 0]'], {}), '(y_l_prime, intervals[i, 0])\n', (74247, 74275), False, 'from math import isclose\n'), ((75523, 75562), 'math.isclose', 'isclose', (['intervals[i - 1, 1]', 'y_r_prime'], {}), '(intervals[i - 1, 1], y_r_prime)\n', (75530, 75562), False, 'from math import isclose\n'), ((75584, 75619), 'math.isclose', 'isclose', (['y_r_prime', 'intervals[i, 1]'], {}), '(y_r_prime, intervals[i, 1])\n', (75591, 75619), False, 'from math import isclose\n'), ((79298, 79334), 'numpy.sum', 'npsum', (['(F[:, 0] * (Y[:, 0] - Y[0, 0]))'], {}), '(F[:, 0] * (Y[:, 0] - Y[0, 0]))\n', (79303, 79334), True, 'from numpy import sum as npsum\n'), ((79337, 79374), 'numpy.sum', 'npsum', (['(F[:, 1] * (Y[-1, 0] - Y[:, 0]))'], {}), '(F[:, 1] * (Y[-1, 0] - Y[:, 0]))\n', (79342, 79374), True, 'from numpy import sum as npsum\n'), ((79516, 79552), 'numpy.sum', 'npsum', (['(F[:, 1] * (Y[:, 1] - Y[0, 1]))'], {}), '(F[:, 1] * (Y[:, 1] - Y[0, 1]))\n', (79521, 79552), True, 'from numpy import sum as npsum\n'), ((79555, 79592), 'numpy.sum', 'npsum', (['(F[:, 0] * (Y[-1, 1] - Y[:, 1]))'], {}), '(F[:, 0] * (Y[-1, 1] - Y[:, 1]))\n', (79560, 79592), True, 'from numpy import sum as npsum\n'), ((80368, 80386), 'numpy.sum', 'npsum', (['(F[:, 0] * Y)'], {}), '(F[:, 0] * Y)\n', (80373, 80386), True, 'from numpy import sum as npsum\n'), ((80410, 80428), 'numpy.sum', 'npsum', (['(F[:, 1] * Y)'], {}), '(F[:, 1] * Y)\n', (80415, 80428), True, 'from numpy import sum as npsum\n'), ((81263, 81287), 'numpy.sum', 'npsum', (['(F[:, 0] * Y[:, 0])'], {}), '(F[:, 0] * Y[:, 0])\n', (81268, 81287), True, 'from numpy import sum as npsum\n'), ((81311, 81335), 'numpy.sum', 'npsum', (['(F[:, 1] * Y[:, 1])'], {}), '(F[:, 1] * Y[:, 1])\n', (81316, 81335), True, 'from numpy import sum as npsum\n'), ((130143, 130151), 'numpy.array', 'array', (['F'], {}), '(F)\n', (130148, 130151), False, 'from numpy import exp, ones_like, zeros_like, arange, multiply, subtract, add, minimum, maximum, sign, c_, argmax, array, where, hstack, logical_not, sqrt\n'), ((79187, 79223), 'numpy.sum', 'npsum', (['(F[:, 0] * (Y[:, 0] - Y[0, 0]))'], {}), '(F[:, 0] * (Y[:, 0] - Y[0, 0]))\n', (79192, 79223), True, 'from numpy import sum as npsum\n'), ((79256, 79293), 'numpy.sum', 'npsum', (['(F[:, 1] * (Y[-1, 0] - Y[:, 0]))'], {}), '(F[:, 1] * (Y[-1, 0] - Y[:, 0]))\n', (79261, 79293), True, 'from numpy import sum as npsum\n'), ((79405, 79441), 'numpy.sum', 'npsum', (['(F[:, 1] * (Y[:, 1] - Y[0, 1]))'], {}), '(F[:, 1] * (Y[:, 1] - Y[0, 1]))\n', (79410, 79441), True, 'from numpy import sum as npsum\n'), ((79474, 79511), 'numpy.sum', 'npsum', (['(F[:, 0] * (Y[-1, 1] - Y[:, 1]))'], {}), '(F[:, 0] * (Y[-1, 1] - Y[:, 1]))\n', (79479, 79511), True, 'from numpy import sum as npsum\n'), ((120283, 120299), 'numpy.array', 'array', (['B[output]'], {}), '(B[output])\n', (120288, 120299), False, 'from numpy import exp, ones_like, zeros_like, arange, multiply, subtract, add, minimum, maximum, sign, c_, argmax, array, where, hstack, logical_not, sqrt\n'), ((120367, 120375), 'numpy.array', 'array', (['F'], {}), '(F)\n', (120372, 120375), False, 'from numpy import exp, ones_like, zeros_like, arange, multiply, subtract, add, minimum, maximum, sign, c_, argmax, array, where, hstack, logical_not, sqrt\n'), ((109150, 109158), 'numpy.array', 'array', (['F'], {}), '(F)\n', (109155, 109158), False, 'from numpy import exp, ones_like, zeros_like, arange, multiply, subtract, add, minimum, maximum, sign, c_, argmax, array, where, hstack, logical_not, sqrt\n'), ((100178, 100186), 'numpy.array', 'array', (['F'], {}), '(F)\n', (100183, 100186), False, 'from numpy import exp, ones_like, zeros_like, arange, multiply, subtract, add, minimum, maximum, sign, c_, argmax, array, where, hstack, logical_not, sqrt\n')]
from __future__ import absolute_import from __future__ import unicode_literals from __future__ import division from __future__ import print_function import argparse import os from os.path import join from collections import defaultdict as dd import numpy as np import sklearn import torch from torch.utils.data import Dataset from sklearn.metrics.pairwise import cosine_similarity from keras.preprocessing.sequence import pad_sequences from utils import feature_utils from utils import data_utils from utils import settings import logging logger = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO, format='%(asctime)s %(message)s') # include timestamp class AuthorCNNMatchDataset(Dataset): def __init__(self, file_dir, matrix_size1, matrix_size2, seed, shuffle, args, use_emb=True, all_train=False): self.file_dir = file_dir self.matrix_title_size = matrix_size1 self.matrix_author_size = matrix_size2 # load training pairs pos_pairs = data_utils.load_json(file_dir, 'pos_person_pairs.json') neg_pairs = data_utils.load_json(file_dir, 'neg_person_pairs.json') pairs = pos_pairs + neg_pairs labels = [1] * len(pos_pairs) + [0] * len(neg_pairs) self.person_dict = data_utils.load_json(file_dir, "ego_person_dict.json") self.use_emb = use_emb if self.use_emb: self.pretrain_emb = torch.load(os.path.join(settings.OUT_DIR, "rnn_init_word_emb.emb")) self.tokenizer = data_utils.load_large_obj(settings.OUT_DIR, "tokenizer_all_domain.pkl") X_long = [] X_short = [] nn_pos = 0 nn_neg = 0 for i, pair in enumerate(pairs): if i % 100 == 0: logger.info('pairs to matrices %d %d %d', i, nn_pos, nn_neg) aid, mid = pair['aid'], pair['mid'] aperson = self.person_dict.get(aid, {}) mperson = self.person_dict.get(mid, {}) # matrix1, nn1 = self.org_to_matrix(aperson.get('org', ''), mperson.get('org', ''), matrix_size1) matrix1, nn1 = self.paper_to_matrix(aperson.get('pubs', []), mperson.get('pubs', []), matrix_size1) matrix1 = feature_utils.scale_matrix(matrix1) X_long.append(matrix1) matrix2, nn2 = self.venue_to_matrix(aperson.get('venue', ''), mperson.get('venue', ''), matrix_size2) # print("matrix2", matrix2) matrix2 = feature_utils.scale_matrix(matrix2) X_short.append(matrix2) self.X_long = X_long self.X_short = X_short self.Y = labels print("shuffle", shuffle) if shuffle: self.X_long, self.X_short, self.Y = sklearn.utils.shuffle( self.X_long, self.X_short, self.Y, random_state=seed ) self.N = len(self.Y) # valid_start = int(self.N * args.train_ratio / 100) # test_start = int(self.N * (args.train_ratio + args.valid_ratio) / 100) if all_train: valid_start = 10000 test_start = 5000 + valid_start end_point = 5000 + test_start else: valid_start = 800 test_start = 200 + valid_start end_point = 200 + test_start train_data = {} train_data["x1"] = self.X_long[:valid_start] train_data["x2"] = self.X_short[:valid_start] train_data["y"] = self.Y[:valid_start] print("train labels", len(train_data["y"])) test_data = {} test_data["x1"] = self.X_long[test_start: end_point] test_data["x2"] = self.X_short[test_start: end_point] test_data["y"] = self.Y[test_start: end_point] print("test labels", len(test_data["y"])) valid_data = {} valid_data["x1"] = self.X_long[valid_start:test_start] valid_data["x2"] = self.X_short[valid_start:test_start] valid_data["y"] = self.Y[valid_start:test_start] print("valid labels", len(valid_data["y"])) print("train positive samples", sum(train_data["y"])) print("test positive samples", sum(test_data["y"])) out_dir = join(settings.DATA_DIR, "dom-adpt") os.makedirs(out_dir, exist_ok=True) data_utils.dump_large_obj(train_data, out_dir, "author_train.pkl") data_utils.dump_large_obj(test_data, out_dir, "author_test.pkl") data_utils.dump_large_obj(valid_data, out_dir, "author_valid.pkl") def paper_to_matrix(self, ap, mp, max_size): if self.use_emb: #TODO apubs = self.tokenizer.texts_to_sequences([" ".join(ap)])[0][:max_size] mpubs = self.tokenizer.texts_to_sequences([" ".join(mp)])[0][:max_size] else: apubs = ap[:max_size] mpubs = mp[:max_size] matrix = -np.ones((max_size, max_size)) for i, apid in enumerate(apubs): for j, mpid in enumerate(mpubs): v = -1 if apid == mpid: v = 1 elif self.use_emb: v = cosine_similarity(self.pretrain_emb[apid].reshape(1, -1), self.pretrain_emb[mpid].reshape(1, -1))[0][0] matrix[i, j] = v return matrix, None def venue_to_matrix(self, o1, o2, max_size): avenue = [v['id'] for v in o1] mvenue = [v['id'] for v in o2] if self.use_emb: avenue = self.tokenizer.texts_to_sequences([" ".join(avenue)])[0][:max_size] mvenue = self.tokenizer.texts_to_sequences([" ".join(mvenue)])[0][:max_size] avenue = avenue[: max_size] mvenue = mvenue[: max_size] matrix = -np.ones((max_size, max_size)) nn1 = 0 for i, avid in enumerate(avenue): for j, mvid in enumerate(mvenue): v = -1 if avid == mvid: v = 1 nn1 += 1 elif self.use_emb: v = cosine_similarity(self.pretrain_emb[avid].reshape(1, -1), self.pretrain_emb[mvid].reshape(1, -1))[0][0] matrix[i, j] = v print(nn1, avenue, mvenue) return matrix, None class AuthorRNNMatchDataset(Dataset): def __init__(self, file_dir, max_seq1_len, max_seq2_len, shuffle, seed, args, all_train=False): self.max_seq1_len = max_seq1_len self.max_seq2_len = max_seq2_len # load training pairs pos_pairs = data_utils.load_json(file_dir, 'pos_person_pairs.json') neg_pairs = data_utils.load_json(file_dir, 'neg_person_pairs.json') pairs = pos_pairs + neg_pairs self.labels = [1] * len(pos_pairs) + [0] * len(neg_pairs) self.person_dict = data_utils.load_json(file_dir, "ego_person_dict.json") nn_pos = 0 nn_neg = 0 t = data_utils.load_large_obj(settings.OUT_DIR, "tokenizer_all_domain.pkl") self.vocab_size = len(t.word_counts) print("vocab size", self.vocab_size) self.mag = [self.person_dict.get(pair["mid"], {}).get("pubs", []) for pair in pairs] self.aminer = [self.person_dict.get(pair["aid"], {}).get("pubs", []) for pair in pairs] self.mag = t.texts_to_sequences(self.mag) self.aminer = t.texts_to_sequences(self.aminer) self.mag = pad_sequences(self.mag, maxlen=self.max_seq1_len) self.aminer = pad_sequences(self.aminer, maxlen=self.max_seq1_len) self.mag_keywords = [] self.aminer_keywords = [] for i, pair in enumerate(pairs): if i % 100 == 0: logger.info('pairs to matrices %d %d %d', i, nn_pos, nn_neg) aid, mid = pair['aid'], pair['mid'] avenue = [item["id"] for item in self.person_dict.get(aid, {}).get("venue", [])] mvenue = [item["id"] for item in self.person_dict.get(mid, {}).get("venue", [])] self.mag_keywords.append(mvenue) self.aminer_keywords.append(avenue) self.mag_keywords = t.texts_to_sequences(self.mag_keywords) self.aminer_keywords = t.texts_to_sequences(self.aminer_keywords) self.mag_keywords = pad_sequences(self.mag_keywords, maxlen=max_seq2_len) self.aminer_keywords = pad_sequences(self.aminer_keywords, maxlen=max_seq2_len) if shuffle: self.mag, self.aminer, self.mag_keywords, self.aminer_keywords, self.labels = sklearn.utils.shuffle( self.mag, self.aminer, self.mag_keywords, self.aminer_keywords, self.labels, random_state=seed ) self.N = len(self.labels) # valid_start = int(self.N * args.train_ratio / 100) # test_start = int(self.N * (args.train_ratio + args.valid_ratio) / 100) if all_train: valid_start = 10000 test_start = 5000 + valid_start end_point = 5000 + test_start else: valid_start = 800 test_start = 200 + valid_start end_point = 200 + test_start train_data = {} train_data["x1_seq1"] = self.mag[:valid_start] train_data["x1_seq2"] = self.mag_keywords[:valid_start] train_data["x2_seq1"] = self.aminer[:valid_start] train_data["x2_seq2"] = self.aminer_keywords[:valid_start] train_data["y"] = self.labels[:valid_start] train_data["vocab_size"] = self.vocab_size print("train labels", len(train_data["y"])) test_data = {} test_data["x1_seq1"] = self.mag[test_start: end_point] test_data["x1_seq2"] = self.mag_keywords[test_start: end_point] test_data["x2_seq1"] = self.aminer[test_start: end_point] test_data["x2_seq2"] = self.aminer_keywords[test_start: end_point] test_data["y"] = self.labels[test_start: end_point] print("test labels", len(test_data["y"])) valid_data = {} valid_data["x1_seq1"] = self.mag[valid_start:test_start] valid_data["x1_seq2"] = self.mag_keywords[valid_start:test_start] valid_data["x2_seq1"] = self.aminer[valid_start:test_start] valid_data["x2_seq2"] = self.aminer_keywords[valid_start:test_start] valid_data["y"] = self.labels[valid_start:test_start] print("valid labels", len(valid_data["y"])) out_dir = join(settings.DATA_DIR, "dom-adpt") os.makedirs(out_dir, exist_ok=True) data_utils.dump_large_obj(train_data, out_dir, "author_rnn_train.pkl") data_utils.dump_large_obj(test_data, out_dir, "author_rnn_test.pkl") data_utils.dump_large_obj(valid_data, out_dir, "author_rnn_valid.pkl") if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--file-dir', type=str, default=settings.AUTHOR_DATA_DIR, help="Input file directory") parser.add_argument('--matrix-size1', type=int, default=7, help='Matrix size 1.') parser.add_argument('--matrix-size2', type=int, default=4, help='Matrix size 2.') parser.add_argument('--train-ratio', type=int, default=50, help='Training size.') parser.add_argument('--valid-ratio', type=int, default=25, help='Testing size.') parser.add_argument('--seed', type=int, default=42, help='Random seed.') parser.add_argument('--shuffle', action='store_true', default=True, help="Shuffle dataset") parser.add_argument('--max-sequence-length', type=int, default=17, help="Max sequence length for raw sequences") parser.add_argument('--max-key-sequence-length', type=int, default=8, help="Max key sequence length for key sequences") args = parser.parse_args() dataset = AuthorCNNMatchDataset(file_dir=args.file_dir, matrix_size1=args.matrix_size1, matrix_size2=args.matrix_size2, seed=args.seed, shuffle=True, args=args, use_emb=False, all_train=True) dataset = AuthorRNNMatchDataset(args.file_dir, args.max_sequence_length, args.max_key_sequence_length, shuffle=True, seed=args.seed, args=args, all_train=True)
[ "utils.data_utils.load_json", "argparse.ArgumentParser", "logging.basicConfig", "os.makedirs", "keras.preprocessing.sequence.pad_sequences", "utils.data_utils.dump_large_obj", "utils.feature_utils.scale_matrix", "utils.data_utils.load_large_obj", "numpy.ones", "sklearn.utils.shuffle", "os.path.j...
[((551, 578), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (568, 578), False, 'import logging\n'), ((579, 652), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO', 'format': '"""%(asctime)s %(message)s"""'}), "(level=logging.INFO, format='%(asctime)s %(message)s')\n", (598, 652), False, 'import logging\n'), ((10687, 10712), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (10710, 10712), False, 'import argparse\n'), ((1006, 1061), 'utils.data_utils.load_json', 'data_utils.load_json', (['file_dir', '"""pos_person_pairs.json"""'], {}), "(file_dir, 'pos_person_pairs.json')\n", (1026, 1061), False, 'from utils import data_utils\n'), ((1082, 1137), 'utils.data_utils.load_json', 'data_utils.load_json', (['file_dir', '"""neg_person_pairs.json"""'], {}), "(file_dir, 'neg_person_pairs.json')\n", (1102, 1137), False, 'from utils import data_utils\n'), ((1265, 1319), 'utils.data_utils.load_json', 'data_utils.load_json', (['file_dir', '"""ego_person_dict.json"""'], {}), "(file_dir, 'ego_person_dict.json')\n", (1285, 1319), False, 'from utils import data_utils\n'), ((1502, 1573), 'utils.data_utils.load_large_obj', 'data_utils.load_large_obj', (['settings.OUT_DIR', '"""tokenizer_all_domain.pkl"""'], {}), "(settings.OUT_DIR, 'tokenizer_all_domain.pkl')\n", (1527, 1573), False, 'from utils import data_utils\n'), ((4153, 4188), 'os.path.join', 'join', (['settings.DATA_DIR', '"""dom-adpt"""'], {}), "(settings.DATA_DIR, 'dom-adpt')\n", (4157, 4188), False, 'from os.path import join\n'), ((4197, 4232), 'os.makedirs', 'os.makedirs', (['out_dir'], {'exist_ok': '(True)'}), '(out_dir, exist_ok=True)\n', (4208, 4232), False, 'import os\n'), ((4241, 4307), 'utils.data_utils.dump_large_obj', 'data_utils.dump_large_obj', (['train_data', 'out_dir', '"""author_train.pkl"""'], {}), "(train_data, out_dir, 'author_train.pkl')\n", (4266, 4307), False, 'from utils import data_utils\n'), ((4316, 4380), 'utils.data_utils.dump_large_obj', 'data_utils.dump_large_obj', (['test_data', 'out_dir', '"""author_test.pkl"""'], {}), "(test_data, out_dir, 'author_test.pkl')\n", (4341, 4380), False, 'from utils import data_utils\n'), ((4389, 4455), 'utils.data_utils.dump_large_obj', 'data_utils.dump_large_obj', (['valid_data', 'out_dir', '"""author_valid.pkl"""'], {}), "(valid_data, out_dir, 'author_valid.pkl')\n", (4414, 4455), False, 'from utils import data_utils\n'), ((6506, 6561), 'utils.data_utils.load_json', 'data_utils.load_json', (['file_dir', '"""pos_person_pairs.json"""'], {}), "(file_dir, 'pos_person_pairs.json')\n", (6526, 6561), False, 'from utils import data_utils\n'), ((6582, 6637), 'utils.data_utils.load_json', 'data_utils.load_json', (['file_dir', '"""neg_person_pairs.json"""'], {}), "(file_dir, 'neg_person_pairs.json')\n", (6602, 6637), False, 'from utils import data_utils\n'), ((6770, 6824), 'utils.data_utils.load_json', 'data_utils.load_json', (['file_dir', '"""ego_person_dict.json"""'], {}), "(file_dir, 'ego_person_dict.json')\n", (6790, 6824), False, 'from utils import data_utils\n'), ((6875, 6946), 'utils.data_utils.load_large_obj', 'data_utils.load_large_obj', (['settings.OUT_DIR', '"""tokenizer_all_domain.pkl"""'], {}), "(settings.OUT_DIR, 'tokenizer_all_domain.pkl')\n", (6900, 6946), False, 'from utils import data_utils\n'), ((7354, 7403), 'keras.preprocessing.sequence.pad_sequences', 'pad_sequences', (['self.mag'], {'maxlen': 'self.max_seq1_len'}), '(self.mag, maxlen=self.max_seq1_len)\n', (7367, 7403), False, 'from keras.preprocessing.sequence import pad_sequences\n'), ((7426, 7478), 'keras.preprocessing.sequence.pad_sequences', 'pad_sequences', (['self.aminer'], {'maxlen': 'self.max_seq1_len'}), '(self.aminer, maxlen=self.max_seq1_len)\n', (7439, 7478), False, 'from keras.preprocessing.sequence import pad_sequences\n'), ((8191, 8244), 'keras.preprocessing.sequence.pad_sequences', 'pad_sequences', (['self.mag_keywords'], {'maxlen': 'max_seq2_len'}), '(self.mag_keywords, maxlen=max_seq2_len)\n', (8204, 8244), False, 'from keras.preprocessing.sequence import pad_sequences\n'), ((8276, 8332), 'keras.preprocessing.sequence.pad_sequences', 'pad_sequences', (['self.aminer_keywords'], {'maxlen': 'max_seq2_len'}), '(self.aminer_keywords, maxlen=max_seq2_len)\n', (8289, 8332), False, 'from keras.preprocessing.sequence import pad_sequences\n'), ((10330, 10365), 'os.path.join', 'join', (['settings.DATA_DIR', '"""dom-adpt"""'], {}), "(settings.DATA_DIR, 'dom-adpt')\n", (10334, 10365), False, 'from os.path import join\n'), ((10374, 10409), 'os.makedirs', 'os.makedirs', (['out_dir'], {'exist_ok': '(True)'}), '(out_dir, exist_ok=True)\n', (10385, 10409), False, 'import os\n'), ((10418, 10488), 'utils.data_utils.dump_large_obj', 'data_utils.dump_large_obj', (['train_data', 'out_dir', '"""author_rnn_train.pkl"""'], {}), "(train_data, out_dir, 'author_rnn_train.pkl')\n", (10443, 10488), False, 'from utils import data_utils\n'), ((10497, 10565), 'utils.data_utils.dump_large_obj', 'data_utils.dump_large_obj', (['test_data', 'out_dir', '"""author_rnn_test.pkl"""'], {}), "(test_data, out_dir, 'author_rnn_test.pkl')\n", (10522, 10565), False, 'from utils import data_utils\n'), ((10574, 10644), 'utils.data_utils.dump_large_obj', 'data_utils.dump_large_obj', (['valid_data', 'out_dir', '"""author_rnn_valid.pkl"""'], {}), "(valid_data, out_dir, 'author_rnn_valid.pkl')\n", (10599, 10644), False, 'from utils import data_utils\n'), ((2197, 2232), 'utils.feature_utils.scale_matrix', 'feature_utils.scale_matrix', (['matrix1'], {}), '(matrix1)\n', (2223, 2232), False, 'from utils import feature_utils\n'), ((2444, 2479), 'utils.feature_utils.scale_matrix', 'feature_utils.scale_matrix', (['matrix2'], {}), '(matrix2)\n', (2470, 2479), False, 'from utils import feature_utils\n'), ((2704, 2779), 'sklearn.utils.shuffle', 'sklearn.utils.shuffle', (['self.X_long', 'self.X_short', 'self.Y'], {'random_state': 'seed'}), '(self.X_long, self.X_short, self.Y, random_state=seed)\n', (2725, 2779), False, 'import sklearn\n'), ((4807, 4836), 'numpy.ones', 'np.ones', (['(max_size, max_size)'], {}), '((max_size, max_size))\n', (4814, 4836), True, 'import numpy as np\n'), ((5689, 5718), 'numpy.ones', 'np.ones', (['(max_size, max_size)'], {}), '((max_size, max_size))\n', (5696, 5718), True, 'import numpy as np\n'), ((8444, 8566), 'sklearn.utils.shuffle', 'sklearn.utils.shuffle', (['self.mag', 'self.aminer', 'self.mag_keywords', 'self.aminer_keywords', 'self.labels'], {'random_state': 'seed'}), '(self.mag, self.aminer, self.mag_keywords, self.\n aminer_keywords, self.labels, random_state=seed)\n', (8465, 8566), False, 'import sklearn\n'), ((1420, 1475), 'os.path.join', 'os.path.join', (['settings.OUT_DIR', '"""rnn_init_word_emb.emb"""'], {}), "(settings.OUT_DIR, 'rnn_init_word_emb.emb')\n", (1432, 1475), False, 'import os\n')]
class Callback(): def __init__(self, learner): self.learner = learner def fit_start(self): return True def fit_end(self): return True def epoch_start(self, epoch): return True def batch_start(self, batch): return True def after_loss(self, loss): return True def batch_end(self): return True def epoch_end(self): return True from collections import defaultdict import numpy as np def take_mean(data, bpe, afrac): if afrac== 0.: return np.mean(data) else: mean_but_last = np.mean(data[:-1]) #return (1./bpe)*np.mean(data[-1]) + (1. - 1./bpe)*mean_but_last return (afrac*data[-1] + (bpe -1)*mean_but_last)/(bpe - 1 + afrac) class AccCallback(Callback): def __init__(self, learner, bs): super().__init__(learner) self.bs = bs self.losses = [] self.batch_losses = [] self.paramhist = defaultdict(list) self.gradhist = defaultdict(list) self.bpe = 0 self.afrac=0. def get_weights(self, layer, index): return np.array([wmat[index][0] for wmat in self.paramhist[layer+'_w']]) def get_weightgrads(self, layer, index): return np.array([wmat[index][0] for wmat in self.gradhist[layer+'_w']]) def get_biases(self, layer): return np.array([e[0] for e in self.paramhist[layer+'_b']]) def get_biasgrads(self, layer): return np.array([e[0] for e in self.gradhist[layer+'_b']]) def fit_start(self): self.bpe = self.learner.bpe self.afrac = self.learner.afrac return True def fit_end(self): return True def epoch_start(self, epoch): self.epoch = epoch #print("EPOCH {}".format(self.epoch)) return True def batch_start(self, batch): self.batch = batch def after_loss(self, loss): self.loss = loss #print("loss", self.epoch, self.loss) return True def batch_end(self): self.batch_losses.append(self.loss) def epoch_end(self): for layer, name, fnval, grval in self.learner.model.params_and_grads(): self.paramhist[layer.name+'_'+name].append(fnval) self.gradhist[layer.name+'_'+name].append(grval) eloss = take_mean(self.batch_losses[-self.bpe:], self.bpe, self.afrac) self.losses.append(eloss) if self.epoch % 10 ==0: print(f"Epoch {self.epoch} Loss {eloss}") return True class ClfCallback(Callback): def __init__(self, learner, bs, xtrain, xtest,ytrain,ytest): super().__init__(learner) self.accuracies = [] self.test_accuracies = [] self.bs = bs self.losses = [] self.batch_losses = [] self.paramhist = defaultdict(list) self.gradhist = defaultdict(list) self.bpe = 0 self.afrac=0. self.xtrain = xtrain self.xtest = xtest self.ytrain = ytrain self.ytest = ytest def get_weights(self, layer, index): return np.array([wmat[index][0] for wmat in self.paramhist[layer+'_w']]) def get_weightgrads(self, layer, index): return np.array([wmat[index][0] for wmat in self.gradhist[layer+'_w']]) def get_biases(self, layer): return np.array([e[0] for e in self.paramhist[layer+'_b']]) def get_biasgrads(self, layer): return np.array([e[0] for e in self.gradhist[layer+'_b']]) def fit_start(self): self.bpe = self.learner.bpe self.afrac = self.learner.afrac return True def fit_end(self): return True def epoch_start(self, epoch): self.epoch = epoch #print("EPOCH {}".format(self.epoch)) return True def batch_start(self, batch): self.batch = batch def after_loss(self, loss): self.loss = loss #print("loss", self.epoch, self.loss) return True def batch_end(self): self.batch_losses.append(self.loss) def epoch_end(self): for layer, name, fnval, grval in self.learner.model.params_and_grads(): self.paramhist[layer.name+'_'+name].append(fnval) self.gradhist[layer.name+'_'+name].append(grval) eloss = take_mean(self.batch_losses[-self.bpe:], self.bpe, self.afrac) self.losses.append(eloss) self.prob_ytrain = self.learner.model(self.xtrain) self.pred_ytrain = 1*(self.prob_ytrain > 0.5) train_accuracy = np.mean(self.pred_ytrain == self.ytrain) self.accuracies.append(train_accuracy) self.prob_ytest = self.learner.model(self.xtest) self.pred_ytest = 1*(self.prob_ytest > 0.5) test_accuracy = np.mean(self.pred_ytest == self.ytest) self.test_accuracies.append(test_accuracy) if self.epoch % 10 ==0: print(f"Epoch {self.epoch} Loss {eloss}") print(f"train accuracy {train_accuracy}, test accuracy {test_accuracy}") return True
[ "collections.defaultdict", "numpy.mean", "numpy.array" ]
[((548, 561), 'numpy.mean', 'np.mean', (['data'], {}), '(data)\n', (555, 561), True, 'import numpy as np\n'), ((596, 614), 'numpy.mean', 'np.mean', (['data[:-1]'], {}), '(data[:-1])\n', (603, 614), True, 'import numpy as np\n'), ((979, 996), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (990, 996), False, 'from collections import defaultdict\n'), ((1021, 1038), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (1032, 1038), False, 'from collections import defaultdict\n'), ((1147, 1214), 'numpy.array', 'np.array', (["[wmat[index][0] for wmat in self.paramhist[layer + '_w']]"], {}), "([wmat[index][0] for wmat in self.paramhist[layer + '_w']])\n", (1155, 1214), True, 'import numpy as np\n'), ((1273, 1339), 'numpy.array', 'np.array', (["[wmat[index][0] for wmat in self.gradhist[layer + '_w']]"], {}), "([wmat[index][0] for wmat in self.gradhist[layer + '_w']])\n", (1281, 1339), True, 'import numpy as np\n'), ((1386, 1440), 'numpy.array', 'np.array', (["[e[0] for e in self.paramhist[layer + '_b']]"], {}), "([e[0] for e in self.paramhist[layer + '_b']])\n", (1394, 1440), True, 'import numpy as np\n'), ((1490, 1543), 'numpy.array', 'np.array', (["[e[0] for e in self.gradhist[layer + '_b']]"], {}), "([e[0] for e in self.gradhist[layer + '_b']])\n", (1498, 1543), True, 'import numpy as np\n'), ((2832, 2849), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (2843, 2849), False, 'from collections import defaultdict\n'), ((2874, 2891), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (2885, 2891), False, 'from collections import defaultdict\n'), ((3121, 3188), 'numpy.array', 'np.array', (["[wmat[index][0] for wmat in self.paramhist[layer + '_w']]"], {}), "([wmat[index][0] for wmat in self.paramhist[layer + '_w']])\n", (3129, 3188), True, 'import numpy as np\n'), ((3247, 3313), 'numpy.array', 'np.array', (["[wmat[index][0] for wmat in self.gradhist[layer + '_w']]"], {}), "([wmat[index][0] for wmat in self.gradhist[layer + '_w']])\n", (3255, 3313), True, 'import numpy as np\n'), ((3360, 3414), 'numpy.array', 'np.array', (["[e[0] for e in self.paramhist[layer + '_b']]"], {}), "([e[0] for e in self.paramhist[layer + '_b']])\n", (3368, 3414), True, 'import numpy as np\n'), ((3464, 3517), 'numpy.array', 'np.array', (["[e[0] for e in self.gradhist[layer + '_b']]"], {}), "([e[0] for e in self.gradhist[layer + '_b']])\n", (3472, 3517), True, 'import numpy as np\n'), ((4557, 4597), 'numpy.mean', 'np.mean', (['(self.pred_ytrain == self.ytrain)'], {}), '(self.pred_ytrain == self.ytrain)\n', (4564, 4597), True, 'import numpy as np\n'), ((4796, 4834), 'numpy.mean', 'np.mean', (['(self.pred_ytest == self.ytest)'], {}), '(self.pred_ytest == self.ytest)\n', (4803, 4834), True, 'import numpy as np\n')]
import numpy as np """ A2-Part-2: Generate a complex sinusoid Write a function to generate the complex sinusoid that is used in DFT computation of length N (samples), corresponding to the frequency index k. Note that the complex sinusoid used in DFT computation has a negative sign in the exponential function. The amplitude of such a complex sinusoid is 1, the length is N, and the frequency in radians is 2*pi*k/N. The input arguments to the function are two positive integers, k and N, such that k < N-1. The function should return cSine, a numpy array of the complex sinusoid. EXAMPLE: If you run your function using N=5 and k=1, the function should return the following numpy array cSine: array([ 1.0 + 0.j, 0.30901699 - 0.95105652j, -0.80901699 - 0.58778525j, -0.80901699 + 0.58778525j, 0.30901699 + 0.95105652j]) """ def genComplexSine(k, N): """ Inputs: k (integer) = frequency index of the complex sinusoid of the DFT N (integer) = length of complex sinusoid in samples Output: The function should return a numpy array cSine (numpy array) = The generated complex sinusoid (length N) """ ## Your code here time_domain = np.arange(0, N) x = np.exp(-1j * 2 * np.pi * k * time_domain / N) return(x)
[ "numpy.arange", "numpy.exp" ]
[((1195, 1210), 'numpy.arange', 'np.arange', (['(0)', 'N'], {}), '(0, N)\n', (1204, 1210), True, 'import numpy as np\n'), ((1219, 1266), 'numpy.exp', 'np.exp', (['(-1.0j * 2 * np.pi * k * time_domain / N)'], {}), '(-1.0j * 2 * np.pi * k * time_domain / N)\n', (1225, 1266), True, 'import numpy as np\n')]
# Copyright 2016-present CERN – European Organization for Nuclear Research # # 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 numpy import sign from math import isclose from qf_lib.backtesting.portfolio.backtest_position import BacktestPosition from qf_lib.backtesting.portfolio.transaction import Transaction from qf_lib.common.utils.miscellaneous.constants import ISCLOSE_REL_TOL, ISCLOSE_ABS_TOL class BacktestCryptoPosition(BacktestPosition): def market_value(self) -> float: return self.quantity() * self.current_price def total_exposure(self) -> float: return self._quantity * self.current_price def _cash_to_buy_or_proceeds_from_sale(self, transaction: Transaction) -> float: result = transaction.price * transaction.quantity + transaction.commission return -result def _compute_profit_and_loss_fraction(self, price: float, quantity: float): if sign(quantity) * self.direction() == -1: price_pnl = price - self._avg_price_per_unit # We multiply by the direction, so that the in case of finding a pair of transaction going in opposite # directions, the realized pnl of this operation would consider the direction of the position quantity = self.direction() * abs(quantity) return price_pnl * quantity else: return 0.0 def transact_transaction(self, transaction: Transaction) -> float: self._check_if_open() assert transaction.ticker == self._ticker, "Ticker of the Transaction has to match the Ticker of the Position" assert isclose(transaction.quantity, 0, rel_tol=ISCLOSE_REL_TOL, abs_tol=ISCLOSE_ABS_TOL) is not True, "`Transaction.quantity` shouldn't be 0" assert transaction.price > 0.0, "Transaction.price must be positive. For short sales use a negative quantity" if self.start_time is None: self.start_time = transaction.time if self._direction == 0: self._direction = sign(transaction.quantity) sign_change = sign(self._quantity) * sign(self._quantity + transaction.quantity) assert sign_change != -1, "Position cannot change direction (for ex: from Long to Short). Close it first" # has to be called before we append the transaction to list of all transactions cash_move = self._cash_to_buy_or_proceeds_from_sale(transaction) self._realised_pnl_without_commissions += self._compute_profit_and_loss_fraction(price=transaction.price, quantity=transaction.quantity) if sign(transaction.quantity) == self.direction(): self._avg_price_per_unit = (self._avg_price_per_unit * self._quantity + transaction.price * transaction.quantity) / (self._quantity + transaction.quantity) if isclose(self._quantity + transaction.quantity, 0, rel_tol=ISCLOSE_REL_TOL, abs_tol=ISCLOSE_ABS_TOL): # close the position if the number of shares drops to zero self._close_position(transaction.time) self._quantity += transaction.quantity self._commission += transaction.commission return cash_move
[ "math.isclose", "numpy.sign" ]
[((3451, 3554), 'math.isclose', 'isclose', (['(self._quantity + transaction.quantity)', '(0)'], {'rel_tol': 'ISCLOSE_REL_TOL', 'abs_tol': 'ISCLOSE_ABS_TOL'}), '(self._quantity + transaction.quantity, 0, rel_tol=ISCLOSE_REL_TOL,\n abs_tol=ISCLOSE_ABS_TOL)\n', (3458, 3554), False, 'from math import isclose\n'), ((2142, 2229), 'math.isclose', 'isclose', (['transaction.quantity', '(0)'], {'rel_tol': 'ISCLOSE_REL_TOL', 'abs_tol': 'ISCLOSE_ABS_TOL'}), '(transaction.quantity, 0, rel_tol=ISCLOSE_REL_TOL, abs_tol=\n ISCLOSE_ABS_TOL)\n', (2149, 2229), False, 'from math import isclose\n'), ((2544, 2570), 'numpy.sign', 'sign', (['transaction.quantity'], {}), '(transaction.quantity)\n', (2548, 2570), False, 'from numpy import sign\n'), ((2594, 2614), 'numpy.sign', 'sign', (['self._quantity'], {}), '(self._quantity)\n', (2598, 2614), False, 'from numpy import sign\n'), ((2617, 2660), 'numpy.sign', 'sign', (['(self._quantity + transaction.quantity)'], {}), '(self._quantity + transaction.quantity)\n', (2621, 2660), False, 'from numpy import sign\n'), ((3183, 3209), 'numpy.sign', 'sign', (['transaction.quantity'], {}), '(transaction.quantity)\n', (3187, 3209), False, 'from numpy import sign\n'), ((1454, 1468), 'numpy.sign', 'sign', (['quantity'], {}), '(quantity)\n', (1458, 1468), False, 'from numpy import sign\n')]
import os import yaml from yaml.loader import SafeLoader import pandas as pd import numpy as np from typing import List, Optional import pydantic as dt from .dgl_dataset import DGLDataset from ..convert import heterograph as dgl_heterograph from .. import backend as F from .utils import save_graphs, load_graphs from ..base import dgl_warning, DGLError import abc import ast from typing import Callable class MetaNode(dt.BaseModel): """ Class of node_data in YAML. Internal use only. """ file_name: str ntype: Optional[str] = '_V' graph_id_field: Optional[str] = 'graph_id' node_id_field: Optional[str] = 'node_id' class MetaEdge(dt.BaseModel): """ Class of edge_data in YAML. Internal use only. """ file_name: str etype: Optional[List[str]] = ['_V', '_E', '_V'] graph_id_field: Optional[str] = 'graph_id' src_id_field: Optional[str] = 'src_id' dst_id_field: Optional[str] = 'dst_id' class MetaGraph(dt.BaseModel): """ Class of graph_data in YAML. Internal use only. """ file_name: str graph_id_field: Optional[str] = 'graph_id' class MetaYaml(dt.BaseModel): """ Class of YAML. Internal use only. """ version: Optional[str] = '1.0.0' dataset_name: str separator: Optional[str] = ',' node_data: List[MetaNode] edge_data: List[MetaEdge] graph_data: Optional[MetaGraph] = None def load_yaml_with_sanity_check(yaml_file): """ Load yaml and do sanity check. Internal use only. """ with open(yaml_file) as f: yaml_data = yaml.load(f, Loader=SafeLoader) try: meta_yaml = MetaYaml(**yaml_data) except dt.ValidationError as e: print( "Details of pydantic.ValidationError:\n{}".format(e.json())) raise DGLError( "Validation Error for YAML fields. Details are shown above.") if meta_yaml.version != '1.0.0': raise DGLError("Invalid CSVDataset version {}. Supported versions: '1.0.0'".format( meta_yaml.version)) ntypes = [meta.ntype for meta in meta_yaml.node_data] if len(ntypes) > len(set(ntypes)): raise DGLError( "Each node CSV file must have a unique node type name, but found duplicate node type: {}.".format(ntypes)) etypes = [tuple(meta.etype) for meta in meta_yaml.edge_data] if len(etypes) > len(set(etypes)): raise DGLError( "Each edge CSV file must have a unique edge type name, but found duplicate edge type: {}.".format(etypes)) return meta_yaml def _validate_data_length(data_dict): len_dict = {k: len(v) for k, v in data_dict.items()} lst = list(len_dict.values()) res = lst.count(lst[0]) == len(lst) if not res: raise DGLError( "All data are required to have same length while some of them does not. Length of data={}".format(str(len_dict))) class BaseData: """ Class of base data which is inherited by Node/Edge/GraphData. Internal use only. """ @staticmethod def read_csv(file_name, base_dir, separator): csv_path = file_name if base_dir is not None: csv_path = os.path.join(base_dir, csv_path) return pd.read_csv(csv_path, sep=separator) @staticmethod def pop_from_dataframe(df: pd.DataFrame, item: str): ret = None try: ret = df.pop(item).to_numpy().squeeze() except KeyError: pass return ret class NodeData(BaseData): """ Class of node data which is used for DGLGraph construction. Internal use only. """ def __init__(self, node_id, data, type=None, graph_id=None): self.id = np.array(node_id, dtype=np.int64) self.data = data self.type = type if type is not None else '_V' self.graph_id = np.array(graph_id, dtype=np.int) if graph_id is not None else np.full( len(node_id), 0) _validate_data_length({**{'id': self.id, 'graph_id': self.graph_id}, **self.data}) @staticmethod def load_from_csv(meta: MetaNode, data_parser: Callable, base_dir=None, separator=','): df = BaseData.read_csv(meta.file_name, base_dir, separator) node_ids = BaseData.pop_from_dataframe(df, meta.node_id_field) graph_ids = BaseData.pop_from_dataframe(df, meta.graph_id_field) if node_ids is None: raise DGLError("Missing node id field [{}] in file [{}].".format( meta.node_id_field, meta.file_name)) ntype = meta.ntype ndata = data_parser(df) return NodeData(node_ids, ndata, type=ntype, graph_id=graph_ids) @staticmethod def to_dict(node_data: List['NodeData']) -> dict: # node_ids could be arbitrary numeric values, namely non-sorted, duplicated, not labeled from 0 to num_nodes-1 node_dict = {} for n_data in node_data: graph_ids = np.unique(n_data.graph_id) for graph_id in graph_ids: idx = n_data.graph_id == graph_id ids = n_data.id[idx] u_ids, u_indices = np.unique(ids, return_index=True) if len(ids) > len(u_ids): dgl_warning( "There exist duplicated ids and only the first ones are kept.") if graph_id not in node_dict: node_dict[graph_id] = {} node_dict[graph_id][n_data.type] = {'mapping': {index: i for i, index in enumerate(ids[u_indices])}, 'data': {k: F.tensor(v[idx][u_indices]) for k, v in n_data.data.items()}} return node_dict class EdgeData(BaseData): """ Class of edge data which is used for DGLGraph construction. Internal use only. """ def __init__(self, src_id, dst_id, data, type=None, graph_id=None): self.src = np.array(src_id, dtype=np.int64) self.dst = np.array(dst_id, dtype=np.int64) self.data = data self.type = type if type is not None else ('_V', '_E', '_V') self.graph_id = np.array(graph_id, dtype=np.int) if graph_id is not None else np.full( len(src_id), 0) _validate_data_length({**{'src': self.src, 'dst': self.dst, 'graph_id': self.graph_id}, **self.data}) @staticmethod def load_from_csv(meta: MetaEdge, data_parser: Callable, base_dir=None, separator=','): df = BaseData.read_csv(meta.file_name, base_dir, separator) src_ids = BaseData.pop_from_dataframe(df, meta.src_id_field) if src_ids is None: raise DGLError("Missing src id field [{}] in file [{}].".format( meta.src_id_field, meta.file_name)) dst_ids = BaseData.pop_from_dataframe(df, meta.dst_id_field) if dst_ids is None: raise DGLError("Missing dst id field [{}] in file [{}].".format( meta.dst_id_field, meta.file_name)) graph_ids = BaseData.pop_from_dataframe(df, meta.graph_id_field) etype = tuple(meta.etype) edata = data_parser(df) return EdgeData(src_ids, dst_ids, edata, type=etype, graph_id=graph_ids) @staticmethod def to_dict(edge_data: List['EdgeData'], node_dict: dict) -> dict: edge_dict = {} for e_data in edge_data: (src_type, e_type, dst_type) = e_data.type graph_ids = np.unique(e_data.graph_id) for graph_id in graph_ids: if graph_id in edge_dict and e_data.type in edge_dict[graph_id]: raise DGLError(f"Duplicate edge type[{e_data.type}] for same graph[{graph_id}], please place the same edge_type for same graph into single EdgeData.") idx = e_data.graph_id == graph_id src_mapping = node_dict[graph_id][src_type]['mapping'] dst_mapping = node_dict[graph_id][dst_type]['mapping'] src_ids = [src_mapping[index] for index in e_data.src[idx]] dst_ids = [dst_mapping[index] for index in e_data.dst[idx]] if graph_id not in edge_dict: edge_dict[graph_id] = {} edge_dict[graph_id][e_data.type] = {'edges': (F.tensor(src_ids), F.tensor(dst_ids)), 'data': {k: F.tensor(v[idx]) for k, v in e_data.data.items()}} return edge_dict class GraphData(BaseData): """ Class of graph data which is used for DGLGraph construction. Internal use only. """ def __init__(self, graph_id, data): self.graph_id = np.array(graph_id, dtype=np.int64) self.data = data _validate_data_length({**{'graph_id': self.graph_id}, **self.data}) @staticmethod def load_from_csv(meta: MetaGraph, data_parser: Callable, base_dir=None, separator=','): df = BaseData.read_csv(meta.file_name, base_dir, separator) graph_ids = BaseData.pop_from_dataframe(df, meta.graph_id_field) if graph_ids is None: raise DGLError("Missing graph id field [{}] in file [{}].".format( meta.graph_id_field, meta.file_name)) gdata = data_parser(df) return GraphData(graph_ids, gdata) @staticmethod def to_dict(graph_data: 'GraphData', graphs_dict: dict) -> dict: missing_ids = np.setdiff1d( np.array(list(graphs_dict.keys())), graph_data.graph_id) if len(missing_ids) > 0: raise DGLError( "Found following graph ids in node/edge CSVs but not in graph CSV: {}.".format(missing_ids)) graph_ids = graph_data.graph_id graphs = [] for graph_id in graph_ids: if graph_id not in graphs_dict: graphs_dict[graph_id] = dgl_heterograph( {('_V', '_E', '_V'): ([], [])}) for graph_id in graph_ids: graphs.append(graphs_dict[graph_id]) data = {k: F.tensor(v) for k, v in graph_data.data.items()} return graphs, data class DGLGraphConstructor: """ Class for constructing DGLGraph from Node/Edge/Graph data. Internal use only. """ @staticmethod def construct_graphs(node_data, edge_data, graph_data=None): if not isinstance(node_data, list): node_data = [node_data] if not isinstance(edge_data, list): edge_data = [edge_data] node_dict = NodeData.to_dict(node_data) edge_dict = EdgeData.to_dict(edge_data, node_dict) graph_dict = DGLGraphConstructor._construct_graphs( node_dict, edge_dict) if graph_data is None: graph_data = GraphData(np.full(1, 0), {}) graphs, data = GraphData.to_dict( graph_data, graph_dict) return graphs, data @staticmethod def _construct_graphs(node_dict, edge_dict): graph_dict = {} for graph_id in node_dict: if graph_id not in edge_dict: edge_dict[graph_id][('_V', '_E', '_V')] = {'edges': ([], [])} graph = dgl_heterograph({etype: edata['edges'] for etype, edata in edge_dict[graph_id].items()}, num_nodes_dict={ntype: len(ndata['mapping']) for ntype, ndata in node_dict[graph_id].items()}) def assign_data(type, src_data, dst_data): for key, value in src_data.items(): dst_data[type].data[key] = value for type, data in node_dict[graph_id].items(): assign_data(type, data['data'], graph.nodes) for (type), data in edge_dict[graph_id].items(): assign_data(type, data['data'], graph.edges) graph_dict[graph_id] = graph return graph_dict class DefaultDataParser: """ Default data parser for DGLCSVDataset. It 1. ignores any columns which does not have a header. 2. tries to convert to list of numeric values(generated by np.array().tolist()) if cell data is a str separated by ','. 3. read data and infer data type directly, otherwise. """ def __call__(self, df: pd.DataFrame): data = {} for header in df: if 'Unnamed' in header: dgl_warning("Unamed column is found. Ignored...") continue dt = df[header].to_numpy().squeeze() if len(dt) > 0 and isinstance(dt[0], str): #probably consists of list of numeric values dt = np.array([ast.literal_eval(row) for row in dt]) data[header] = dt return data class DGLCSVDataset(DGLDataset): """ This class aims to parse data from CSV files, construct DGLGraph and behaves as a DGLDataset. Parameters ---------- data_path : str Directory which contains 'meta.yaml' and CSV files force_reload : bool, optional Whether to reload the dataset. Default: False verbose: bool, optional Whether to print out progress information. Default: True. node_data_parser : dict[str, callable], optional A dictionary used for node data parsing when loading from CSV files. The key is node type which specifies the header in CSV file and the value is a callable object which is used to parse corresponding column data. Default: None. If None, a default data parser is applied which load data directly and tries to convert list into array. edge_data_parser : dict[(str, str, str), callable], optional A dictionary used for edge data parsing when loading from CSV files. The key is edge type which specifies the header in CSV file and the value is a callable object which is used to parse corresponding column data. Default: None. If None, a default data parser is applied which load data directly and tries to convert list into array. graph_data_parser : callable, optional A callable object which is used to parse corresponding column graph data. Default: None. If None, a default data parser is applied which load data directly and tries to convert list into array. Attributes ---------- graphs : :class:`dgl.DGLGraph` Graphs of the dataset data : dict any available graph-level data such as graph-level feature, labels. Examples [TODO]: link to a detailed web page. """ META_YAML_NAME = 'meta.yaml' def __init__(self, data_path, force_reload=False, verbose=True, node_data_parser=None, edge_data_parser=None, graph_data_parser=None): self.graphs = None self.data = None self.node_data_parser = {} if node_data_parser is None else node_data_parser self.edge_data_parser = {} if edge_data_parser is None else edge_data_parser self.graph_data_parser = graph_data_parser self.default_data_parser = DefaultDataParser() meta_yaml_path = os.path.join(data_path, DGLCSVDataset.META_YAML_NAME) if not os.path.exists(meta_yaml_path): raise DGLError( "'{}' cannot be found under {}.".format(DGLCSVDataset.META_YAML_NAME, data_path)) self.meta_yaml = load_yaml_with_sanity_check(meta_yaml_path) ds_name = self.meta_yaml.dataset_name super().__init__(ds_name, raw_dir=os.path.dirname( meta_yaml_path), force_reload=force_reload, verbose=verbose) def process(self): """Parse node/edge data from CSV files and construct DGL.Graphs """ meta_yaml = self.meta_yaml base_dir = self.raw_dir node_data = [] for meta_node in meta_yaml.node_data: if meta_node is None: continue ntype = meta_node.ntype data_parser = self.node_data_parser.get( ntype, self.default_data_parser) ndata = NodeData.load_from_csv( meta_node, base_dir=base_dir, separator=meta_yaml.separator, data_parser=data_parser) node_data.append(ndata) edge_data = [] for meta_edge in meta_yaml.edge_data: if meta_edge is None: continue etype = tuple(meta_edge.etype) data_parser = self.edge_data_parser.get( etype, self.default_data_parser) edata = EdgeData.load_from_csv( meta_edge, base_dir=base_dir, separator=meta_yaml.separator, data_parser=data_parser) edge_data.append(edata) graph_data = None if meta_yaml.graph_data is not None: meta_graph = meta_yaml.graph_data data_parser = self.default_data_parser if self.graph_data_parser is None else self.graph_data_parser graph_data = GraphData.load_from_csv( meta_graph, base_dir=base_dir, separator=meta_yaml.separator, data_parser=data_parser) # construct graphs self.graphs, self.data = DGLGraphConstructor.construct_graphs( node_data, edge_data, graph_data) def has_cache(self): graph_path = os.path.join(self.save_path, self.name + '.bin') if os.path.exists(graph_path): return True return False def save(self): if self.graphs is None: raise DGLError("No graphs available in dataset") graph_path = os.path.join(self.save_path, self.name + '.bin') save_graphs(graph_path, self.graphs, labels=self.data) def load(self): graph_path = os.path.join(self.save_path, self.name + '.bin') self.graphs, self.data = load_graphs(graph_path) def __getitem__(self, i): if 'label' in self.data: return self.graphs[i], self.data['label'][i] else: return self.graphs[i] def __len__(self): return len(self.graphs)
[ "numpy.full", "yaml.load", "pandas.read_csv", "os.path.dirname", "os.path.exists", "numpy.array", "ast.literal_eval", "os.path.join", "numpy.unique" ]
[((1526, 1557), 'yaml.load', 'yaml.load', (['f'], {'Loader': 'SafeLoader'}), '(f, Loader=SafeLoader)\n', (1535, 1557), False, 'import yaml\n'), ((3225, 3261), 'pandas.read_csv', 'pd.read_csv', (['csv_path'], {'sep': 'separator'}), '(csv_path, sep=separator)\n', (3236, 3261), True, 'import pandas as pd\n'), ((3686, 3719), 'numpy.array', 'np.array', (['node_id'], {'dtype': 'np.int64'}), '(node_id, dtype=np.int64)\n', (3694, 3719), True, 'import numpy as np\n'), ((5982, 6014), 'numpy.array', 'np.array', (['src_id'], {'dtype': 'np.int64'}), '(src_id, dtype=np.int64)\n', (5990, 6014), True, 'import numpy as np\n'), ((6034, 6066), 'numpy.array', 'np.array', (['dst_id'], {'dtype': 'np.int64'}), '(dst_id, dtype=np.int64)\n', (6042, 6066), True, 'import numpy as np\n'), ((8711, 8745), 'numpy.array', 'np.array', (['graph_id'], {'dtype': 'np.int64'}), '(graph_id, dtype=np.int64)\n', (8719, 8745), True, 'import numpy as np\n'), ((15116, 15169), 'os.path.join', 'os.path.join', (['data_path', 'DGLCSVDataset.META_YAML_NAME'], {}), '(data_path, DGLCSVDataset.META_YAML_NAME)\n', (15128, 15169), False, 'import os\n'), ((17242, 17290), 'os.path.join', 'os.path.join', (['self.save_path', "(self.name + '.bin')"], {}), "(self.save_path, self.name + '.bin')\n", (17254, 17290), False, 'import os\n'), ((17336, 17362), 'os.path.exists', 'os.path.exists', (['graph_path'], {}), '(graph_path)\n', (17350, 17362), False, 'import os\n'), ((17545, 17593), 'os.path.join', 'os.path.join', (['self.save_path', "(self.name + '.bin')"], {}), "(self.save_path, self.name + '.bin')\n", (17557, 17593), False, 'import os\n'), ((17753, 17801), 'os.path.join', 'os.path.join', (['self.save_path', "(self.name + '.bin')"], {}), "(self.save_path, self.name + '.bin')\n", (17765, 17801), False, 'import os\n'), ((3177, 3209), 'os.path.join', 'os.path.join', (['base_dir', 'csv_path'], {}), '(base_dir, csv_path)\n', (3189, 3209), False, 'import os\n'), ((3824, 3856), 'numpy.array', 'np.array', (['graph_id'], {'dtype': 'np.int'}), '(graph_id, dtype=np.int)\n', (3832, 3856), True, 'import numpy as np\n'), ((4902, 4928), 'numpy.unique', 'np.unique', (['n_data.graph_id'], {}), '(n_data.graph_id)\n', (4911, 4928), True, 'import numpy as np\n'), ((6185, 6217), 'numpy.array', 'np.array', (['graph_id'], {'dtype': 'np.int'}), '(graph_id, dtype=np.int)\n', (6193, 6217), True, 'import numpy as np\n'), ((7470, 7496), 'numpy.unique', 'np.unique', (['e_data.graph_id'], {}), '(e_data.graph_id)\n', (7479, 7496), True, 'import numpy as np\n'), ((15185, 15215), 'os.path.exists', 'os.path.exists', (['meta_yaml_path'], {}), '(meta_yaml_path)\n', (15199, 15215), False, 'import os\n'), ((5090, 5123), 'numpy.unique', 'np.unique', (['ids'], {'return_index': '(True)'}), '(ids, return_index=True)\n', (5099, 5123), True, 'import numpy as np\n'), ((10758, 10771), 'numpy.full', 'np.full', (['(1)', '(0)'], {}), '(1, 0)\n', (10765, 10771), True, 'import numpy as np\n'), ((15500, 15531), 'os.path.dirname', 'os.path.dirname', (['meta_yaml_path'], {}), '(meta_yaml_path)\n', (15515, 15531), False, 'import os\n'), ((12687, 12708), 'ast.literal_eval', 'ast.literal_eval', (['row'], {}), '(row)\n', (12703, 12708), False, 'import ast\n')]
# -------------------------------------------------------------- # SNIPER: Efficient Multi-Scale Training # Licensed under The Apache-2.0 License [see LICENSE for details] # by <NAME> and <NAME> # -------------------------------------------------------------- import chips from bbox.bbox_transform import clip_boxes, ignore_overlaps import numpy as np class chip_generator(object): def __init__(self, chip_stride=32, use_cpp=True): self.use_cpp = use_cpp self.chip_stride = chip_stride def generate(self, boxes, width, height, chipsize): if self.use_cpp: return self._cgenerate(boxes, width, height, chipsize, self.chip_stride) else: return self._pygenerate(boxes, width, height, chipsize, self.chip_stride) @staticmethod def _cgenerate(boxes, width, height, chipsize, stride): boxes = clip_boxes(boxes, np.array([height - 1, width - 1])) return chips.generate(np.ascontiguousarray(boxes, dtype=np.float32), width, height, chipsize, stride) @staticmethod def _pygenerate(boxes, width, height, chipsize, stride): chips = [] boxes = clip_boxes(boxes, np.array([height-1, width-1])) # ensure coverage of image for worst case # corners chips.append([max(width - chipsize, 0), 0, width - 1, min(chipsize, height-1)]) chips.append([0, max(height - chipsize, 0), min(chipsize, width-1), height-1]) chips.append([max(width - chipsize, 0), max(height - chipsize, 0), width-1, height-1]) for i in range(0, width - int(chipsize), stride): for j in range(0, height - int(chipsize), stride): x1 = i y1 = j x2 = i + chipsize - 1 y2 = j + chipsize - 1 chips.append([x1, y1, x2, y2]) for j in range(0, height - int(chipsize), stride): x1 = max(width - chipsize - 1,0) y1 = j x2 = width - 1 y2 = j + chipsize - 1 chips.append([x1, y1, x2, y2]) for i in range(0, width - int(chipsize), stride): x1 = i y1 = max(height - chipsize - 1,0) x2 = i + chipsize - 1 y2 = height - 1 chips.append([x1, y1, x2, y2]) chips = np.array(chips).astype(np.float) p = np.random.permutation(chips.shape[0]) chips = chips[p] overlaps = ignore_overlaps(chips, boxes.astype(np.float)) chip_matches = [] num_matches = [] for j in range(len(chips)): nvids = np.where(overlaps[j, :] == 1)[0] chip_matches.append(set(nvids.tolist())) num_matches.append(len(nvids)) fchips = [] totalmatches = 0 while True: max_matches = 0 max_match = max(num_matches) mid = np.argmax(np.array(num_matches)) if max_match == 0: break if max_match > max_matches: max_matches = max_match maxid = mid bestchip = chip_matches[maxid] fchips.append(chips[maxid]) totalmatches = totalmatches + max_matches # now remove all rois in bestchip for j in range(len(num_matches)): chip_matches[j] = chip_matches[j] - bestchip num_matches[j] = len(chip_matches[j]) return fchips
[ "numpy.where", "chips.append", "numpy.array", "numpy.random.permutation", "numpy.ascontiguousarray" ]
[((2376, 2413), 'numpy.random.permutation', 'np.random.permutation', (['chips.shape[0]'], {}), '(chips.shape[0])\n', (2397, 2413), True, 'import numpy as np\n'), ((888, 921), 'numpy.array', 'np.array', (['[height - 1, width - 1]'], {}), '([height - 1, width - 1])\n', (896, 921), True, 'import numpy as np\n'), ((953, 998), 'numpy.ascontiguousarray', 'np.ascontiguousarray', (['boxes'], {'dtype': 'np.float32'}), '(boxes, dtype=np.float32)\n', (973, 998), True, 'import numpy as np\n'), ((1196, 1229), 'numpy.array', 'np.array', (['[height - 1, width - 1]'], {}), '([height - 1, width - 1])\n', (1204, 1229), True, 'import numpy as np\n'), ((2053, 2083), 'chips.append', 'chips.append', (['[x1, y1, x2, y2]'], {}), '([x1, y1, x2, y2])\n', (2065, 2083), False, 'import chips\n'), ((2282, 2312), 'chips.append', 'chips.append', (['[x1, y1, x2, y2]'], {}), '([x1, y1, x2, y2])\n', (2294, 2312), False, 'import chips\n'), ((1825, 1855), 'chips.append', 'chips.append', (['[x1, y1, x2, y2]'], {}), '([x1, y1, x2, y2])\n', (1837, 1855), False, 'import chips\n'), ((2330, 2345), 'numpy.array', 'np.array', (['chips'], {}), '(chips)\n', (2338, 2345), True, 'import numpy as np\n'), ((2613, 2642), 'numpy.where', 'np.where', (['(overlaps[j, :] == 1)'], {}), '(overlaps[j, :] == 1)\n', (2621, 2642), True, 'import numpy as np\n'), ((2905, 2926), 'numpy.array', 'np.array', (['num_matches'], {}), '(num_matches)\n', (2913, 2926), True, 'import numpy as np\n')]
import os import sys sys.path.append("../") # go to parent dir import glob import time import pathlib import logging import numpy as np from scipy.sparse import linalg as spla from dedalus.tools.config import config from simple_sphere import SimpleSphere, TensorField, TensorSystem import equations import matplotlib matplotlib.use("TkAgg") import matplotlib.pyplot as plt import cartopy.crs as ccrs from dedalus.extras import plot_tools import logging from mpl_toolkits import mplot3d logger = logging.getLogger(__name__) sphere_inds = [3] plt.figure(figsize=(4,3), dpi=200) for sphere_ind in sphere_inds: input_folder = "data/sphere%i" %(sphere_ind) output_folder = "plots" print('sphere%i' %(sphere_ind)) first_frame = 1 last_frame = len(glob.glob1("".join([input_folder,'/']),"*.npz")) dpi = 256 fields = ['om'] # Setup output folder if not os.path.exists(output_folder): os.makedirs(output_folder) t_arr = np.zeros(last_frame) for ind in range(first_frame, last_frame + 1, 1): logger.info('Frame: %i' %ind) with np.load(os.path.join(input_folder, 'output_%i.npz' %(ind))) as file: if ind == first_frame: phi = file['phi'] theta = file['theta'] L_max = len(theta)-1 S_max = 4 simplesphere = SimpleSphere(L_max, S_max) omega = TensorField(simplesphere, rank=0) coeffs_all = np.zeros((last_frame,L_max+1, L_max+1), dtype=complex) om = file['om'] time = file['t'][0] t_arr[ind-1] = time # assign loaded data omega.component_fields[0]['g'] = om # spectral transform omega.forward_phi() omega.forward_theta() coeffs = omega.coeffs for m in range(len(coeffs)): coeffs_all[ind-1, m, m:] = coeffs[m] E = np.zeros(t_arr.shape) L_max = len(theta)-1 #calculate energy for m in range(L_max+1): for ell in range(L_max+1): if ell!=0: E = E + (np.abs(coeffs_all[:,m,ell])**2)/(ell*(ell+1)) plt.plot(t_arr, E) plt.savefig("%s/energy_plot.eps" %(output_folder)) plt.show()
[ "sys.path.append", "simple_sphere.TensorField", "matplotlib.pyplot.show", "os.makedirs", "matplotlib.pyplot.plot", "numpy.abs", "numpy.zeros", "os.path.exists", "logging.getLogger", "simple_sphere.SimpleSphere", "matplotlib.pyplot.figure", "matplotlib.use", "os.path.join", "matplotlib.pypl...
[((21, 43), 'sys.path.append', 'sys.path.append', (['"""../"""'], {}), "('../')\n", (36, 43), False, 'import sys\n'), ((317, 340), 'matplotlib.use', 'matplotlib.use', (['"""TkAgg"""'], {}), "('TkAgg')\n", (331, 340), False, 'import matplotlib\n'), ((495, 522), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (512, 522), False, 'import logging\n'), ((543, 578), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(4, 3)', 'dpi': '(200)'}), '(figsize=(4, 3), dpi=200)\n', (553, 578), True, 'import matplotlib.pyplot as plt\n'), ((2170, 2219), 'matplotlib.pyplot.savefig', 'plt.savefig', (["('%s/energy_plot.eps' % output_folder)"], {}), "('%s/energy_plot.eps' % output_folder)\n", (2181, 2219), True, 'import matplotlib.pyplot as plt\n'), ((2221, 2231), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2229, 2231), True, 'import matplotlib.pyplot as plt\n'), ((970, 990), 'numpy.zeros', 'np.zeros', (['last_frame'], {}), '(last_frame)\n', (978, 990), True, 'import numpy as np\n'), ((1917, 1938), 'numpy.zeros', 'np.zeros', (['t_arr.shape'], {}), '(t_arr.shape)\n', (1925, 1938), True, 'import numpy as np\n'), ((2150, 2168), 'matplotlib.pyplot.plot', 'plt.plot', (['t_arr', 'E'], {}), '(t_arr, E)\n', (2158, 2168), True, 'import matplotlib.pyplot as plt\n'), ((887, 916), 'os.path.exists', 'os.path.exists', (['output_folder'], {}), '(output_folder)\n', (901, 916), False, 'import os\n'), ((930, 956), 'os.makedirs', 'os.makedirs', (['output_folder'], {}), '(output_folder)\n', (941, 956), False, 'import os\n'), ((1106, 1155), 'os.path.join', 'os.path.join', (['input_folder', "('output_%i.npz' % ind)"], {}), "(input_folder, 'output_%i.npz' % ind)\n", (1118, 1155), False, 'import os\n'), ((1368, 1394), 'simple_sphere.SimpleSphere', 'SimpleSphere', (['L_max', 'S_max'], {}), '(L_max, S_max)\n', (1380, 1394), False, 'from simple_sphere import SimpleSphere, TensorField, TensorSystem\n'), ((1419, 1452), 'simple_sphere.TensorField', 'TensorField', (['simplesphere'], {'rank': '(0)'}), '(simplesphere, rank=0)\n', (1430, 1452), False, 'from simple_sphere import SimpleSphere, TensorField, TensorSystem\n'), ((1482, 1541), 'numpy.zeros', 'np.zeros', (['(last_frame, L_max + 1, L_max + 1)'], {'dtype': 'complex'}), '((last_frame, L_max + 1, L_max + 1), dtype=complex)\n', (1490, 1541), True, 'import numpy as np\n'), ((2099, 2128), 'numpy.abs', 'np.abs', (['coeffs_all[:, m, ell]'], {}), '(coeffs_all[:, m, ell])\n', (2105, 2128), True, 'import numpy as np\n')]
""" Run PyTorch Reinforce on Pusher2D3DofGoalCompoEnv. NOTE: You need PyTorch 0.4 """ import numpy as np import robolearn.torch.utils.pytorch_util as ptu from robolearn.utils.launchers.launcher_util import setup_logger from robolearn_gym_envs.pybullet import Reacher2D3DofBulletEnv from robolearn.algorithms.rl_algos import MDGPS from robolearn.torch.policies import MlpPolicy from robolearn.torch.policies import LinearGaussianPolicy import argparse N_LOCAL_POLS = 3 PATH_LENGTH = 100 PATHS_PER_LOCAL_POL = 5 PATHS_PER_EVAL = 1 SIM_TIMESTEP = 0.001 FRAME_SKIP = 10 DT = SIM_TIMESTEP * FRAME_SKIP def experiment(variant): ptu.set_gpu_mode(variant['gpu']) # env = NormalizedBoxEnv( # Reacher2D3DofBulletEnv(**variant['env_params']) # ) env = Reacher2D3DofBulletEnv(**variant['env_params']) obs_dim = int(np.prod(env.observation_space.shape)) action_dim = int(np.prod(env.action_space.shape)) initial_conds = [ [10, 5, 20, 0.2, 0.5, 0], [10, 5, 20, 0.1, 0.1, 0], [10, 5, 20, 0.15, 0.8, 0], ] for init_cond in initial_conds: env.add_initial_condition(robot_config=np.deg2rad(init_cond[:3]), tgt_state=init_cond[-3:]) net_size = variant['net_size'] # global_policy = TanhGaussianPolicy( global_policy = MlpPolicy( hidden_sizes=[net_size, net_size], obs_dim=obs_dim, action_dim=action_dim, ) local_policies = [LinearGaussianPolicy(obs_dim=obs_dim, action_dim=action_dim, T=PATH_LENGTH, ) for _ in range(N_LOCAL_POLS)] # # replay_buffer = FakeReplayBuffer() # variant['algo_params']['replay_buffer'] = replay_buffer # # # QF Plot # # variant['algo_params']['epoch_plotter'] = None algorithm = MDGPS( env=env, eval_env=env, save_environment=False, local_policies=local_policies, global_policy=global_policy, **variant['algo_params'] ) if ptu.gpu_enabled(): algorithm.cuda() algorithm.train() return algorithm expt_params = dict( algo_name=MDGPS.__name__, algo_params=dict( # Common RLAlgo params num_epochs=10, # n_epochs rollouts_per_epoch=N_LOCAL_POLS * PATHS_PER_LOCAL_POL, num_steps_per_epoch=N_LOCAL_POLS * PATHS_PER_LOCAL_POL * PATH_LENGTH, num_updates_per_train_call=1, # How to many run algorithm train fcn num_steps_per_eval=N_LOCAL_POLS * PATHS_PER_EVAL * PATH_LENGTH, # EnvSampler params max_path_length=PATH_LENGTH, # max_path_length render=False, # MDGPS params traj_opt_inner_iters=1, train_cond_idxs=[0, 1, 2], test_cond_idxs=[0, 1, 2], ), net_size=64 ) env_params = dict( is_render=False, obs_with_img=False, rdn_tgt_pos=True, tgt_pose=None, rdn_robot_config=True, robot_config=None, sim_timestep=SIM_TIMESTEP, frame_skip=FRAME_SKIP, obs_distances=False, # If True obs contain 'distance' vectors instead poses tgt_cost_weight=1.0, ctrl_cost_weight=1.0e-2, use_log_distances=False, # use_log_distances=False, log_alpha=1e-6, tgt_tolerance=0.05, max_time=10, # max_time=PATH_LENGTH*DT, half_env=False, ) def parse_args(): parser = argparse.ArgumentParser() parser.add_argument('--net_size', type=int, default=None) parser.add_argument('--expt_name', type=str, default=None) # parser.add_argument('--expt_name', type=str, default=timestamp()) # Logging arguments parser.add_argument('--snap_mode', type=str, default='gap_and_last') parser.add_argument('--snap_gap', type=int, default=50) # parser.add_argument('--mode', type=str, default='local') parser.add_argument('--log_dir', type=str, default=None) parser.add_argument('--render', action="store_true") parser.add_argument('--gpu', action="store_true") args = parser.parse_args() return args if __name__ == "__main__": args = parse_args() expt_variant = expt_params # Net size if args.net_size is not None: expt_variant['net_size'] = args.net_size expt_variant['gpu'] = args.gpu # Experiment name if args.expt_name is None: expt_name = 'reacher_gps' else: expt_name = args.expt_name expt_variant['algo_params']['render'] = args.render expt_variant['env_params'] = env_params expt_variant['env_params']['is_render'] = args.render setup_logger(expt_name, variant=expt_variant, snapshot_mode=args.snap_mode, snapshot_gap=args.snap_gap, log_dir=args.log_dir) algo = experiment(expt_variant) input('Press a key to close the script...')
[ "robolearn.algorithms.rl_algos.MDGPS", "argparse.ArgumentParser", "numpy.deg2rad", "robolearn_gym_envs.pybullet.Reacher2D3DofBulletEnv", "robolearn.torch.policies.LinearGaussianPolicy", "robolearn.utils.launchers.launcher_util.setup_logger", "robolearn.torch.utils.pytorch_util.gpu_enabled", "robolearn...
[((635, 667), 'robolearn.torch.utils.pytorch_util.set_gpu_mode', 'ptu.set_gpu_mode', (["variant['gpu']"], {}), "(variant['gpu'])\n", (651, 667), True, 'import robolearn.torch.utils.pytorch_util as ptu\n'), ((775, 822), 'robolearn_gym_envs.pybullet.Reacher2D3DofBulletEnv', 'Reacher2D3DofBulletEnv', ([], {}), "(**variant['env_params'])\n", (797, 822), False, 'from robolearn_gym_envs.pybullet import Reacher2D3DofBulletEnv\n'), ((1334, 1423), 'robolearn.torch.policies.MlpPolicy', 'MlpPolicy', ([], {'hidden_sizes': '[net_size, net_size]', 'obs_dim': 'obs_dim', 'action_dim': 'action_dim'}), '(hidden_sizes=[net_size, net_size], obs_dim=obs_dim, action_dim=\n action_dim)\n', (1343, 1423), False, 'from robolearn.torch.policies import MlpPolicy\n'), ((1934, 2077), 'robolearn.algorithms.rl_algos.MDGPS', 'MDGPS', ([], {'env': 'env', 'eval_env': 'env', 'save_environment': '(False)', 'local_policies': 'local_policies', 'global_policy': 'global_policy'}), "(env=env, eval_env=env, save_environment=False, local_policies=\n local_policies, global_policy=global_policy, **variant['algo_params'])\n", (1939, 2077), False, 'from robolearn.algorithms.rl_algos import MDGPS\n'), ((2134, 2151), 'robolearn.torch.utils.pytorch_util.gpu_enabled', 'ptu.gpu_enabled', ([], {}), '()\n', (2149, 2151), True, 'import robolearn.torch.utils.pytorch_util as ptu\n'), ((3464, 3489), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (3487, 3489), False, 'import argparse\n'), ((4645, 4774), 'robolearn.utils.launchers.launcher_util.setup_logger', 'setup_logger', (['expt_name'], {'variant': 'expt_variant', 'snapshot_mode': 'args.snap_mode', 'snapshot_gap': 'args.snap_gap', 'log_dir': 'args.log_dir'}), '(expt_name, variant=expt_variant, snapshot_mode=args.snap_mode,\n snapshot_gap=args.snap_gap, log_dir=args.log_dir)\n', (4657, 4774), False, 'from robolearn.utils.launchers.launcher_util import setup_logger\n'), ((841, 877), 'numpy.prod', 'np.prod', (['env.observation_space.shape'], {}), '(env.observation_space.shape)\n', (848, 877), True, 'import numpy as np\n'), ((900, 931), 'numpy.prod', 'np.prod', (['env.action_space.shape'], {}), '(env.action_space.shape)\n', (907, 931), True, 'import numpy as np\n'), ((1472, 1547), 'robolearn.torch.policies.LinearGaussianPolicy', 'LinearGaussianPolicy', ([], {'obs_dim': 'obs_dim', 'action_dim': 'action_dim', 'T': 'PATH_LENGTH'}), '(obs_dim=obs_dim, action_dim=action_dim, T=PATH_LENGTH)\n', (1492, 1547), False, 'from robolearn.torch.policies import LinearGaussianPolicy\n'), ((1149, 1174), 'numpy.deg2rad', 'np.deg2rad', (['init_cond[:3]'], {}), '(init_cond[:3])\n', (1159, 1174), True, 'import numpy as np\n')]
import pandas as pd import numpy as np import talib def get_label(revenue, period_length): if period_length == 1: if revenue <= 0.1: lab = 0 elif 0.1 < revenue <= 1: lab = 1 elif 1 < revenue <= 3: lab = 2 else: lab = 3 elif period_length == 2: if revenue <= 0.1: lab = 0 elif 0.1 < revenue <= 2: lab = 1 elif 2 < revenue <= 5: lab = 2 else: lab = 3 elif period_length == 4: if revenue <= 0.2: lab = 0 elif 0.2 < revenue <= 3: lab = 1 elif 3 < revenue <= 8: lab = 2 else: lab = 3 else: if revenue <= 0.3: lab = 0 elif 0.3 < revenue <= 4: lab = 1 elif 4 < revenue <= 12: lab = 2 else: lab = 3 return lab def get_info(dataset, info_name): info_array = np.array([float(x) for x in dataset[info_name]]) return info_array # stockCode = '002371' # stockCode = '600036' stockCode = '600048' kMultiples = [0.5, 1, 3, 6, 12, 24, 48, 96] dayPeriods = [1, 2, 4, 8] startDate = '2017-08-01' endDate = '2018-08-01' rootPath = '.././' inputFile = rootPath + stockCode + '**.csv' data = pd.read_csv(inputFile, engine='python', skipfooter=1) data['DateTime'] = pd.to_datetime(data['DateTime']) close = get_info(data, 'close') high = get_info(data, 'high') low = get_info(data, 'low') volume = get_info(data, 'volume') df = pd.DataFrame(data['DateTime'].values, columns=['DateTime']) for k in kMultiples: macd1, macd2, _ = talib.MACD(close, fastperiod=10*k, slowperiod=22*k, signalperiod=8*k) macd3, macd4, _ = talib.MACD(close, fastperiod=12*k, slowperiod=26*k, signalperiod=9*k) macdDiff1 = macd1 - macd2 macdDiff2 = macd3 - macd4 feaName1 = 'MACD1_' + str(k) feaName2 = 'MACD2_' + str(k) feaName3 = 'ADOSC_' + str(k) df[feaName1] = macdDiff1 df[feaName2] = macdDiff2 if k >=1: df[feaName3] = talib.ADOSC(high, low, close, volume, fastperiod=3*k, slowperiod=10*k) for dayPeriod in dayPeriods: dayPeriod_min = int(dayPeriod * 4 * 60 / 5) labelName = 'Class_' + str(dayPeriod) labelList = [np.nan] * dayPeriod_min for i in range(dayPeriod_min, len(close)): j = i - dayPeriod_min rev = (close[i] - close[j]) / close[j] * 100 label = get_label(rev, dayPeriod) labelList.append(label) df[labelName] = np.array(labelList) mask = (df['DateTime'] > startDate) & (df['DateTime'] < endDate) df = df.loc[mask] writingPath = rootPath + stockCode + 'train.csv' df.to_csv(writingPath, index=False)
[ "pandas.DataFrame", "talib.MACD", "pandas.read_csv", "pandas.to_datetime", "numpy.array", "talib.ADOSC" ]
[((1333, 1386), 'pandas.read_csv', 'pd.read_csv', (['inputFile'], {'engine': '"""python"""', 'skipfooter': '(1)'}), "(inputFile, engine='python', skipfooter=1)\n", (1344, 1386), True, 'import pandas as pd\n'), ((1407, 1439), 'pandas.to_datetime', 'pd.to_datetime', (["data['DateTime']"], {}), "(data['DateTime'])\n", (1421, 1439), True, 'import pandas as pd\n'), ((1570, 1629), 'pandas.DataFrame', 'pd.DataFrame', (["data['DateTime'].values"], {'columns': "['DateTime']"}), "(data['DateTime'].values, columns=['DateTime'])\n", (1582, 1629), True, 'import pandas as pd\n'), ((1674, 1749), 'talib.MACD', 'talib.MACD', (['close'], {'fastperiod': '(10 * k)', 'slowperiod': '(22 * k)', 'signalperiod': '(8 * k)'}), '(close, fastperiod=10 * k, slowperiod=22 * k, signalperiod=8 * k)\n', (1684, 1749), False, 'import talib\n'), ((1766, 1841), 'talib.MACD', 'talib.MACD', (['close'], {'fastperiod': '(12 * k)', 'slowperiod': '(26 * k)', 'signalperiod': '(9 * k)'}), '(close, fastperiod=12 * k, slowperiod=26 * k, signalperiod=9 * k)\n', (1776, 1841), False, 'import talib\n'), ((2546, 2565), 'numpy.array', 'np.array', (['labelList'], {}), '(labelList)\n', (2554, 2565), True, 'import numpy as np\n'), ((2090, 2164), 'talib.ADOSC', 'talib.ADOSC', (['high', 'low', 'close', 'volume'], {'fastperiod': '(3 * k)', 'slowperiod': '(10 * k)'}), '(high, low, close, volume, fastperiod=3 * k, slowperiod=10 * k)\n', (2101, 2164), False, 'import talib\n')]
import numpy as np #Radius of subconductor code: # Variables from Radius of subconductors : diameter_strand = float(input("diameter of strand?\n")) number_of_strands = float(input("Input number of strands?\n")) #number_of_layers = 2 #radius_subconductor = 0 layers_1 = ((3)+((9-(4*(3)*(1-number_of_strands)))**0.5))/6 layers_2 = ((3)-((9-(4*(3)*(1-number_of_strands)))**0.5))/6 if ((-1)*abs(layers_1) == layers_1): number_of_layers = layers_2 else: number_of_layers = layers_1 radius_subconductor = ((2*number_of_layers - 1) * diameter_strand)*0.5 ############################################################################## #Output 1 code # Variables from Output 1 #SGMD, called later distance_subconductors = float(input("input distance between subconductors?\n")) #Q1 #m = number_of_strands**2 resultant_radius = 0.7788 * radius_subconductor number_subconductors = float(input("number of subconductors?\n")) #Distance between the phase conductors: symmetric_input = input("Is it symmentric? type 'yes' or 'no'.\n") #MGMD, called later in if statement #inductance, called in the end if symmetric_input == "yes": distances = float(input("What is the distance between phase conductors?\n")) MGMD = distances else: distancex = float(input("Distance - x??\n")) distancey = float(input("Distance - y??\n")) distancez = float(input("Distance - z??\n")) MGMD = (distancex*distancey*distancez)**(1/3) #SGMD calculation: if number_subconductors == 2: # 2 subconductors: SGMD = ( (resultant_radius**2) * (distance_subconductors**2) )**(1/4) elif number_subconductors == 3: # 3 subconductors: SGMD = ( (resultant_radius**3) * (distance_subconductors**6) )**(1/9) elif number_subconductors == 4: # 4 subconductors: SGMD = ( (resultant_radius**4) * (distance_subconductors**12) * ( (2**0.5)**4 ) )**(1/16) elif number_subconductors == 6: # 6 subconductors: SGMD = ( ( resultant_radius * (3*2) * (distance_subconductors**5) ) ** (1/6)) else: print("please choose between 2,3,4 and 6\n\n") inductance = 2*(10**(-7)) * np.log(MGMD/SGMD) * 1000 # per km print("Inductance per phase conductor:\n") print("inductance",inductance) ######################################################################### #OUTPUT 2 pi = 3.14159 electric_permittivity = 8.85 * (10**(-12)) capacitance = (2*pi*electric_permittivity)/(np.log(MGMD/SGMD)) * 1000 # per km print ("capacitance:", capacitance ) ######################################################################### power_freequency = float(input("what is the power freequency?\n")) #HZ line_length_km = float(input("what is the line length in km?\n")) #Output 3 inductive_reactance = ((-1)**0.5)* 2*pi*power_freequency*inductance * line_length_km print("inductive reactance:",inductive_reactance) #Output 4 capacitive_reactance =((-1) * ((-1)**0.5))/((2*pi*power_freequency*capacitance * line_length_km )) print("Capacitive reactance", capacitive_reactance) #Output 5 nominal_system_voltage = float(input("What is nominal system voltage?\n")) #charging_current = (nominal_system_voltage)/ ( capacitive_reactance/((-1)**0.5)) #print("Charging Current:", abs(charging_current)) ######################################################################### #Output 6 line_model = input("Line model: short, nominal, pi, long?\n") resistance_line_km = float(input("what is the resistance per kilometer\n")) z = (inductive_reactance + (resistance_line_km*line_length_km)) gamma = (capacitive_reactance*z)**0.5 # NOTE: check if the reactances are found for per meter or complete line. and check km to m if line_model == "short": # short excludes capacitive effect a = 1 b = z c = 0 d = 1 elif line_model == "pi": #medium transmission, pi model, t is not considered anywhere a = ( 1 + (capacitive_reactance*inductive_reactance)*0.5) b = z c = capacitive_reactance + ((capacitive_reactance**2)*z*0.25) d = a elif line_model == "nominal": #medium transmission, pi model, t is not considered anywhere a = (1+capacitive_reactance*z*0.5) b = z + ((capacitive_reactance*(z**2)))*0.25 c = capacitive_reactance d = a elif line_model == "long": a = np.cosh(gamma*line_length_km*1000) # *1000 to change to meters b = inductive_reactance* np.sinh(gamma)#*line_length_km) c = (1/inductive_reactance)*np.sinh(gamma)#*line_length_km) d = a else: print("error in input\n") print("a = ",a,"\n","b = ",b,"\n","c = ",c,"\n","d = ",d,"\n") charging_current = ((-1)**0.5)*nominal_system_voltage / capacitive_reactance ######################################################################### #Output 7 to 11: receivingend_load_MW = float(input("what is the receiving end load in MW?\n")) pf_receiving_load = float(input("what is the powerfactor of the receiving load?\n")) receivingend_current = (receivingend_load_MW * (10**6))/((3**0.5)*nominal_system_voltage*pf_receiving_load) sendingend_voltage = (a*nominal_system_voltage) + (b* receivingend_current) sendingend_current = (c*nominal_system_voltage) + (d*receivingend_current) #outputs are in volts print("sending end voltage kv = ", abs(sendingend_voltage)/1000,"\n") # Output 7 print("sending end current Amps= ", abs(sendingend_current),"\n") # Output 8 voltage_regulation = ((sendingend_voltage-nominal_system_voltage)*100)/sendingend_voltage #Output 9 powerloss = 3*(sendingend_current**2)*resistance_line_km*line_length_km # output 10 #check if you have multiplied line length in places involving distance and R per km. powerloss_MW = powerloss / (10**6) print("powerloss in MW:\n",powerloss_MW,"\n") transmission_efficiency = (receivingend_load_MW *100 )/ (receivingend_load_MW + powerloss_MW) #Output 11 print("transmission efficiency:\n",transmission_efficiency,"\n") ######################################################################### # Last Updated 19:43 14/04 #Notes: # 1) All outputs are in km # 2) Verify gamma values # 3) Both the reactances have been calculated for the complete line length #To- Do: # 1) Complete charging current output # 2) 12/13 Output # 3) Complete integration # 4) Final Testing from reportlab.pdfgen import canvas pdf = canvas.Canvas("Output_dd_mm") pdf.setTitle("Assignment3_Output") #the answers have to be assigned to the correct variables answer1 = inductance answer2 = capacitance answer3 = inductive_reactance answer4 = capacitive_reactance answer5 = charging_current answer7 = sendingend_voltage answer8 = sendingend_current answer9 = voltage_regulation answer10 = powerloss_MW answer11 = transmission_efficiency answer12 = 12 answer13 = 13 textLines = ["1. Inductance per phase per km in H/km:" + " "*3 + str(answer1), "2. Capacitance per phase per km in F/km:" + " "*3 + str(answer2), "3. Inductive reactance of the line in Ohm:" + " "*3 + str(answer3), "4. Capacitive reactance of the line in Ohm:" + " "*3 + str(answer4), "5. Charging current drawn from the sending end substation:" + " "*2 + str(answer5), "6. Calculate ABCD parameters of the line:" + " "*3 + str(a)+ str(b)+ str(c)+ str(d), "7. Calculate the sending end voltage in kV:" + " "*3 + str(answer7), "8. Calculate the sending end current in A:" + " "*3 + str(answer8), "9. Calculate the percentage voltage regulation:" + " "*3 + str(answer9), "10. Calculate the power loss in the line in MW:" + " "*3 + str(answer10), "11. Calculate the transmission efficiency:"+ " "*3 + str(answer11), "The graph for 12 & 13 has been saved as image" ] #Title: pdf.drawCentredString(300,770,"Assignment 3 Output") pdf.setFont("Courier",12) pdf.drawCentredString(290,720,"Darshan (107118090), Shubham (107118094) & Pramoth (107118074)") pdf.line(30, 710, 550, 710) text = pdf.beginText(40, 680) for line in textLines: text.textLine(line) pdf.drawText(text) pdf.save()
[ "reportlab.pdfgen.canvas.Canvas", "numpy.cosh", "numpy.sinh", "numpy.log" ]
[((6211, 6240), 'reportlab.pdfgen.canvas.Canvas', 'canvas.Canvas', (['"""Output_dd_mm"""'], {}), "('Output_dd_mm')\n", (6224, 6240), False, 'from reportlab.pdfgen import canvas\n'), ((2096, 2115), 'numpy.log', 'np.log', (['(MGMD / SGMD)'], {}), '(MGMD / SGMD)\n', (2102, 2115), True, 'import numpy as np\n'), ((2389, 2408), 'numpy.log', 'np.log', (['(MGMD / SGMD)'], {}), '(MGMD / SGMD)\n', (2395, 2408), True, 'import numpy as np\n'), ((4220, 4258), 'numpy.cosh', 'np.cosh', (['(gamma * line_length_km * 1000)'], {}), '(gamma * line_length_km * 1000)\n', (4227, 4258), True, 'import numpy as np\n'), ((4312, 4326), 'numpy.sinh', 'np.sinh', (['gamma'], {}), '(gamma)\n', (4319, 4326), True, 'import numpy as np\n'), ((4376, 4390), 'numpy.sinh', 'np.sinh', (['gamma'], {}), '(gamma)\n', (4383, 4390), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- # Copyright (c) 2020. Distributed under the terms of the MIT License. from pathlib import Path import pytest from pymatgen.core import Composition from pymatgen.io.vasp import Vasprun from vise.analyzer.plot_band import BandEdge, XTicks, BandMplSettings from vise.analyzer.plot_brillouin_zone import BZPlotlyPlotter from vise.analyzer.vasp.plot_band import greek_to_unicode, italic_to_roman, \ BandPlotInfoFromVasp from vise.analyzer.plot_band import BandPlotter import numpy as np from vise.util.dash_helper import show_png try: import psutil PSUTIL_NOT_PRESENT = False except ModuleNotFoundError: PSUTIL_NOT_PRESENT = True def test_greek_to_unicode(): assert greek_to_unicode("GAMMA") == "Γ" assert greek_to_unicode("SIGMA") == "Σ" assert greek_to_unicode("DELTA") == "Δ" def test_italic_to_roman(): assert italic_to_roman(r"S$\mid$$S_0$") == "S$\mid$${\\rm S}_0$" test_data = [(True, None), (False, BandEdge(vbm=-100, cbm=100, vbm_distances=[0], cbm_distances=[1, 2]))] @pytest.mark.parametrize("is_metal,expected_band_edge", test_data) def test_vasp_band_plotter(is_metal, expected_band_edge, mocker): mock_bs = mocker.MagicMock() mock_bs.efermi = 10 mock_bs.is_metal.return_value = is_metal stub_vasprun = mocker.MagicMock() stub_vasprun.final_structure.composition = Composition("MgO2") stub_vasprun.get_band_structure.return_value = mock_bs energy = {"1": [np.array([[0.1], [0.2], [0.3]])]} distances = [np.array([0.0, 0.1, 0.2])] labels = ["A", "$A_0$", "GAMMA"] label_distances = [0.0, 0.1, 0.2] plot_data = {"energy": energy, "distances": distances, "vbm": [[0, -100]], "cbm": [[1, 100], [2, 100]]} mock_bsp = mocker.patch("vise.analyzer.vasp.plot_band.BSPlotter", auto_spec=True) mock_bsp.return_value.bs_plot_data.return_value = plot_data mock_bsp.return_value.get_ticks_old.return_value = {"label": labels, "distance": [0.0, 0.1, 0.2]} plot_info = BandPlotInfoFromVasp(stub_vasprun, "KPOINTS").make_band_plot_info() expected_x_ticks = XTicks(labels=["A", "${\\rm A}_0$", "Γ"], distances=label_distances) assert plot_info.band_info_set[0].band_energies == [[[[0.1], [0.2], [0.3]]]] assert plot_info.band_info_set[0].band_edge == expected_band_edge assert plot_info.distances_by_branch == [[0.0, 0.1, 0.2]] assert plot_info.x_ticks == expected_x_ticks assert plot_info.title == "MgO$_{2}$" def test_draw_band_plotter_with_actual_vasp_files(test_data_files: Path): vasprun_file = str(test_data_files / "KO2_band_vasprun.xml") kpoints_file = str(test_data_files / "KO2_band_KPOINTS") vasprun = Vasprun(vasprun_file) plot_info = BandPlotInfoFromVasp(vasprun, kpoints_file).make_band_plot_info() plotter = BandPlotter(plot_info, [-10, 10]) plotter.construct_plot() plotter.plt.show() @pytest.mark.skipif(PSUTIL_NOT_PRESENT, reason="psutil does not exist") def test_bz_plotter_with_actual_vasp_files(test_data_files: Path): vasprun_file = str(test_data_files / "KO2_band_vasprun.xml") kpoints_file = str(test_data_files / "KO2_band_KPOINTS") vasprun = Vasprun(vasprun_file) bz_plot_info = BandPlotInfoFromVasp(vasprun, kpoints_file).make_bz_plot_info() fig = BZPlotlyPlotter(bz_plot_info).create_figure() # fig.show() show_png(fig) def test_draw_two_bands(test_data_files: Path): mpl_settings = BandMplSettings(linewidth=[0.3, 1.0], circle_size=50, show_legend=False) vasprun_file = str(test_data_files / "CdAs2O6-vasprun1.xml") vasprun2_file = str(test_data_files / "CdAs2O6-vasprun2.xml") kpoints_file = str(test_data_files / "CdAs2O6-KPOINTS") vasprun = Vasprun(vasprun_file) vasprun2 = Vasprun(vasprun2_file) plot_info = BandPlotInfoFromVasp( vasprun, kpoints_file, vasprun2, energy_window=[-20.0, 20.0]).make_band_plot_info() plotter = BandPlotter(plot_info, [-10, 10], mpl_defaults=mpl_settings) plotter.construct_plot() plotter.plt.show() def test_energy_window(mocker): mock_bs = mocker.MagicMock() mock_bs.efermi = 0 mock_bs.is_metal.return_value = True stub_vasprun = mocker.MagicMock() stub_vasprun.final_structure.composition = Composition("MgO2") stub_vasprun.get_band_structure.return_value = mock_bs energy = {"1": [np.array([[-0.2, -0.1, -0.3, -0.1], [-0.2, -0.1, -0.3, 0.1], [1.2, 1.3, 1.1, 1.2]])]} distances = [[0.0, 1.0]] labels = ["A", "GAMMA"] label_distances = [0.0, 1.0] plot_data = {"energy": energy, "distances": distances, "vbm": None, "cbm": None} mock_bsp = mocker.patch("vise.analyzer.vasp.plot_band.BSPlotter", auto_spec=True) mock_bsp.return_value.bs_plot_data.return_value = plot_data mock_bsp.return_value.get_ticks_old.return_value = {"label": labels, "distance": distances[0]} plot_info = BandPlotInfoFromVasp(stub_vasprun, "KPOINTS", energy_window=[0.0, 1.0]).make_band_plot_info() assert (plot_info.band_info_set[0].band_energies == [[[[-0.2, -0.1, -0.3, 0.1]]]])
[ "pymatgen.io.vasp.Vasprun", "vise.analyzer.vasp.plot_band.BandPlotInfoFromVasp", "vise.util.dash_helper.show_png", "vise.analyzer.plot_band.BandPlotter", "vise.analyzer.plot_brillouin_zone.BZPlotlyPlotter", "vise.analyzer.plot_band.XTicks", "vise.analyzer.vasp.plot_band.italic_to_roman", "vise.analyze...
[((1086, 1151), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""is_metal,expected_band_edge"""', 'test_data'], {}), "('is_metal,expected_band_edge', test_data)\n", (1109, 1151), False, 'import pytest\n'), ((3007, 3077), 'pytest.mark.skipif', 'pytest.mark.skipif', (['PSUTIL_NOT_PRESENT'], {'reason': '"""psutil does not exist"""'}), "(PSUTIL_NOT_PRESENT, reason='psutil does not exist')\n", (3025, 3077), False, 'import pytest\n'), ((1406, 1425), 'pymatgen.core.Composition', 'Composition', (['"""MgO2"""'], {}), "('MgO2')\n", (1417, 1425), False, 'from pymatgen.core import Composition\n'), ((2180, 2248), 'vise.analyzer.plot_band.XTicks', 'XTicks', ([], {'labels': "['A', '${\\\\rm A}_0$', 'Γ']", 'distances': 'label_distances'}), "(labels=['A', '${\\\\rm A}_0$', 'Γ'], distances=label_distances)\n", (2186, 2248), False, 'from vise.analyzer.plot_band import BandEdge, XTicks, BandMplSettings\n'), ((2800, 2821), 'pymatgen.io.vasp.Vasprun', 'Vasprun', (['vasprun_file'], {}), '(vasprun_file)\n', (2807, 2821), False, 'from pymatgen.io.vasp import Vasprun\n'), ((2918, 2951), 'vise.analyzer.plot_band.BandPlotter', 'BandPlotter', (['plot_info', '[-10, 10]'], {}), '(plot_info, [-10, 10])\n', (2929, 2951), False, 'from vise.analyzer.plot_band import BandPlotter\n'), ((3285, 3306), 'pymatgen.io.vasp.Vasprun', 'Vasprun', (['vasprun_file'], {}), '(vasprun_file)\n', (3292, 3306), False, 'from pymatgen.io.vasp import Vasprun\n'), ((3467, 3480), 'vise.util.dash_helper.show_png', 'show_png', (['fig'], {}), '(fig)\n', (3475, 3480), False, 'from vise.util.dash_helper import show_png\n'), ((3550, 3622), 'vise.analyzer.plot_band.BandMplSettings', 'BandMplSettings', ([], {'linewidth': '[0.3, 1.0]', 'circle_size': '(50)', 'show_legend': '(False)'}), '(linewidth=[0.3, 1.0], circle_size=50, show_legend=False)\n', (3565, 3622), False, 'from vise.analyzer.plot_band import BandEdge, XTicks, BandMplSettings\n'), ((3899, 3920), 'pymatgen.io.vasp.Vasprun', 'Vasprun', (['vasprun_file'], {}), '(vasprun_file)\n', (3906, 3920), False, 'from pymatgen.io.vasp import Vasprun\n'), ((3936, 3958), 'pymatgen.io.vasp.Vasprun', 'Vasprun', (['vasprun2_file'], {}), '(vasprun2_file)\n', (3943, 3958), False, 'from pymatgen.io.vasp import Vasprun\n'), ((4112, 4172), 'vise.analyzer.plot_band.BandPlotter', 'BandPlotter', (['plot_info', '[-10, 10]'], {'mpl_defaults': 'mpl_settings'}), '(plot_info, [-10, 10], mpl_defaults=mpl_settings)\n', (4123, 4172), False, 'from vise.analyzer.plot_band import BandPlotter\n'), ((4442, 4461), 'pymatgen.core.Composition', 'Composition', (['"""MgO2"""'], {}), "('MgO2')\n", (4453, 4461), False, 'from pymatgen.core import Composition\n'), ((712, 737), 'vise.analyzer.vasp.plot_band.greek_to_unicode', 'greek_to_unicode', (['"""GAMMA"""'], {}), "('GAMMA')\n", (728, 737), False, 'from vise.analyzer.vasp.plot_band import greek_to_unicode, italic_to_roman, BandPlotInfoFromVasp\n'), ((756, 781), 'vise.analyzer.vasp.plot_band.greek_to_unicode', 'greek_to_unicode', (['"""SIGMA"""'], {}), "('SIGMA')\n", (772, 781), False, 'from vise.analyzer.vasp.plot_band import greek_to_unicode, italic_to_roman, BandPlotInfoFromVasp\n'), ((800, 825), 'vise.analyzer.vasp.plot_band.greek_to_unicode', 'greek_to_unicode', (['"""DELTA"""'], {}), "('DELTA')\n", (816, 825), False, 'from vise.analyzer.vasp.plot_band import greek_to_unicode, italic_to_roman, BandPlotInfoFromVasp\n'), ((874, 906), 'vise.analyzer.vasp.plot_band.italic_to_roman', 'italic_to_roman', (['"""S$\\\\mid$$S_0$"""'], {}), "('S$\\\\mid$$S_0$')\n", (889, 906), False, 'from vise.analyzer.vasp.plot_band import greek_to_unicode, italic_to_roman, BandPlotInfoFromVasp\n'), ((982, 1050), 'vise.analyzer.plot_band.BandEdge', 'BandEdge', ([], {'vbm': '(-100)', 'cbm': '(100)', 'vbm_distances': '[0]', 'cbm_distances': '[1, 2]'}), '(vbm=-100, cbm=100, vbm_distances=[0], cbm_distances=[1, 2])\n', (990, 1050), False, 'from vise.analyzer.plot_band import BandEdge, XTicks, BandMplSettings\n'), ((1557, 1582), 'numpy.array', 'np.array', (['[0.0, 0.1, 0.2]'], {}), '([0.0, 0.1, 0.2])\n', (1565, 1582), True, 'import numpy as np\n'), ((1506, 1537), 'numpy.array', 'np.array', (['[[0.1], [0.2], [0.3]]'], {}), '([[0.1], [0.2], [0.3]])\n', (1514, 1537), True, 'import numpy as np\n'), ((2088, 2133), 'vise.analyzer.vasp.plot_band.BandPlotInfoFromVasp', 'BandPlotInfoFromVasp', (['stub_vasprun', '"""KPOINTS"""'], {}), "(stub_vasprun, 'KPOINTS')\n", (2108, 2133), False, 'from vise.analyzer.vasp.plot_band import greek_to_unicode, italic_to_roman, BandPlotInfoFromVasp\n'), ((2838, 2881), 'vise.analyzer.vasp.plot_band.BandPlotInfoFromVasp', 'BandPlotInfoFromVasp', (['vasprun', 'kpoints_file'], {}), '(vasprun, kpoints_file)\n', (2858, 2881), False, 'from vise.analyzer.vasp.plot_band import greek_to_unicode, italic_to_roman, BandPlotInfoFromVasp\n'), ((3326, 3369), 'vise.analyzer.vasp.plot_band.BandPlotInfoFromVasp', 'BandPlotInfoFromVasp', (['vasprun', 'kpoints_file'], {}), '(vasprun, kpoints_file)\n', (3346, 3369), False, 'from vise.analyzer.vasp.plot_band import greek_to_unicode, italic_to_roman, BandPlotInfoFromVasp\n'), ((3400, 3429), 'vise.analyzer.plot_brillouin_zone.BZPlotlyPlotter', 'BZPlotlyPlotter', (['bz_plot_info'], {}), '(bz_plot_info)\n', (3415, 3429), False, 'from vise.analyzer.plot_brillouin_zone import BZPlotlyPlotter\n'), ((3975, 4061), 'vise.analyzer.vasp.plot_band.BandPlotInfoFromVasp', 'BandPlotInfoFromVasp', (['vasprun', 'kpoints_file', 'vasprun2'], {'energy_window': '[-20.0, 20.0]'}), '(vasprun, kpoints_file, vasprun2, energy_window=[-20.0,\n 20.0])\n', (3995, 4061), False, 'from vise.analyzer.vasp.plot_band import greek_to_unicode, italic_to_roman, BandPlotInfoFromVasp\n'), ((4542, 4629), 'numpy.array', 'np.array', (['[[-0.2, -0.1, -0.3, -0.1], [-0.2, -0.1, -0.3, 0.1], [1.2, 1.3, 1.1, 1.2]]'], {}), '([[-0.2, -0.1, -0.3, -0.1], [-0.2, -0.1, -0.3, 0.1], [1.2, 1.3, 1.1,\n 1.2]])\n', (4550, 4629), True, 'import numpy as np\n'), ((5181, 5252), 'vise.analyzer.vasp.plot_band.BandPlotInfoFromVasp', 'BandPlotInfoFromVasp', (['stub_vasprun', '"""KPOINTS"""'], {'energy_window': '[0.0, 1.0]'}), "(stub_vasprun, 'KPOINTS', energy_window=[0.0, 1.0])\n", (5201, 5252), False, 'from vise.analyzer.vasp.plot_band import greek_to_unicode, italic_to_roman, BandPlotInfoFromVasp\n')]
import numpy as np import pandas as pd # peason def Peason(x,y): x = np.squeeze(x) y = np.squeeze(y) x = x - x.mean() y = y - y.mean() return x.dot(y)/(np.linalg.norm(x)*np.linalg.norm(y)) # Jaccard def Jaccard(x,y): x = np.squeeze(x) y = np.squeeze(y) a = x.dot(y) b = np.linalg.norm(x) c = np.linalg.norm(y) return a/(np.power(b,2)+np.power(c,2)-a) # cosine def Cosine(x,y): x = np.squeeze(x) y = np.squeeze(y) return x.dot(y)/(np.linalg.norm(x)*np.linalg.norm(y)) def split_train_test(root_file,raw=True,percemtage = 0.75): outdata = pd.read_excel(root_file,sheet_name="train") names = outdata.iloc[:, 0] y_value = outdata.iloc[:, 2] x_value = outdata.iloc[:, 3:] if raw: return x_value.values,y_value.values[:, np.newaxis] else: length = len(outdata) train_len = int(percemtage*length) train_x_names = names[:train_len] train_x = x_value[:train_len] train_y = y_value[:train_len] test_x_names = names[train_len:] test_x = x_value[train_len:] test_y = y_value[train_len:] return (train_x.values,train_y.values[:, np.newaxis]),\ (test_x.values,test_y.values[:, np.newaxis])
[ "numpy.squeeze", "numpy.power", "numpy.linalg.norm", "pandas.read_excel" ]
[((74, 87), 'numpy.squeeze', 'np.squeeze', (['x'], {}), '(x)\n', (84, 87), True, 'import numpy as np\n'), ((96, 109), 'numpy.squeeze', 'np.squeeze', (['y'], {}), '(y)\n', (106, 109), True, 'import numpy as np\n'), ((246, 259), 'numpy.squeeze', 'np.squeeze', (['x'], {}), '(x)\n', (256, 259), True, 'import numpy as np\n'), ((268, 281), 'numpy.squeeze', 'np.squeeze', (['y'], {}), '(y)\n', (278, 281), True, 'import numpy as np\n'), ((307, 324), 'numpy.linalg.norm', 'np.linalg.norm', (['x'], {}), '(x)\n', (321, 324), True, 'import numpy as np\n'), ((333, 350), 'numpy.linalg.norm', 'np.linalg.norm', (['y'], {}), '(y)\n', (347, 350), True, 'import numpy as np\n'), ((430, 443), 'numpy.squeeze', 'np.squeeze', (['x'], {}), '(x)\n', (440, 443), True, 'import numpy as np\n'), ((452, 465), 'numpy.squeeze', 'np.squeeze', (['y'], {}), '(y)\n', (462, 465), True, 'import numpy as np\n'), ((598, 642), 'pandas.read_excel', 'pd.read_excel', (['root_file'], {'sheet_name': '"""train"""'}), "(root_file, sheet_name='train')\n", (611, 642), True, 'import pandas as pd\n'), ((173, 190), 'numpy.linalg.norm', 'np.linalg.norm', (['x'], {}), '(x)\n', (187, 190), True, 'import numpy as np\n'), ((191, 208), 'numpy.linalg.norm', 'np.linalg.norm', (['y'], {}), '(y)\n', (205, 208), True, 'import numpy as np\n'), ((487, 504), 'numpy.linalg.norm', 'np.linalg.norm', (['x'], {}), '(x)\n', (501, 504), True, 'import numpy as np\n'), ((505, 522), 'numpy.linalg.norm', 'np.linalg.norm', (['y'], {}), '(y)\n', (519, 522), True, 'import numpy as np\n'), ((365, 379), 'numpy.power', 'np.power', (['b', '(2)'], {}), '(b, 2)\n', (373, 379), True, 'import numpy as np\n'), ((379, 393), 'numpy.power', 'np.power', (['c', '(2)'], {}), '(c, 2)\n', (387, 393), True, 'import numpy as np\n')]
import math import numpy as np # Converts URx's rotation vector into a rotation matrix # # I did not derive this nor do I fully understand the maths behind this :0 # I took it from: https://dof.robotiq.com/discussion/1648/around-which-axes-are-the-rotation-vector-angles-defined def convert_tool_pose_to_transformation_matrix(tool_pose): r = tool_pose[3:] rx = r[0] ry = r[1] rz = r[2] theta = math.sqrt( (rx ** 2) + (ry ** 2) + (rz ** 2) ) ux = rx / theta uy = ry / theta uz = rz / theta c = math.cos(theta) s = math.sin(theta) C = 1 - c # base_to_tcp = np.array([0, -600, -135]) base_to_tcp = tool_pose[:3] T = np.array([ [(ux * ux * C) + c , (ux * uy * C) - (uz * s), (ux * uz * C) + (uy * s), base_to_tcp[0]], [(uy * ux * C) + (uz * s), (uy * uy * C) + c , (uy * uz * C) - (ux * s), base_to_tcp[1]], [(uz * ux * C) - (uy * s), (uz * uy * C) + (ux * s), (uz * uz * C) + c , base_to_tcp[2]], [0,0,0,1] ]) return T # Calculates hand position in absolute coordinates def calculate_hand_position(transformation_matrix, relative_palm_postion): # Formats raw hand coordinates hand_coordinates_raw = relative_palm_postion hand_coordinates_raw = [50, 0, 0] hand_coordinates_raw.append(1) hand_coordinates = np.array(hand_coordinates_raw) * [1, -1, 1, 1] # Gets abolsolute matrix by transformation matrix multiplication absolute_position = transformation_matrix.dot(hand_coordinates) return np.round(absolute_position[:3],3) def calculate_required_robot_position(absolute_hand_position, y_offset=0): required_robot_position = absolute_hand_position + [0, 130, 0] # required_robot_position = absolute_hand_position + y_offset return required_robot_position def main(): tool_pose = [50, -600, -135, 0, 3.14, 0] T = convert_tool_pose_to_transformation_matrix(tool_pose) relative_palm_postion = [0, 103, 0] absolute_hand_position = calculate_hand_position(T, relative_palm_postion) print(absolute_hand_position) required_robot_position = calculate_required_robot_position(absolute_hand_position) print(required_robot_position) main()
[ "math.sqrt", "math.sin", "numpy.array", "math.cos", "numpy.round" ]
[((409, 447), 'math.sqrt', 'math.sqrt', (['(rx ** 2 + ry ** 2 + rz ** 2)'], {}), '(rx ** 2 + ry ** 2 + rz ** 2)\n', (418, 447), False, 'import math\n'), ((518, 533), 'math.cos', 'math.cos', (['theta'], {}), '(theta)\n', (526, 533), False, 'import math\n'), ((540, 555), 'math.sin', 'math.sin', (['theta'], {}), '(theta)\n', (548, 555), False, 'import math\n'), ((650, 925), 'numpy.array', 'np.array', (['[[ux * ux * C + c, ux * uy * C - uz * s, ux * uz * C + uy * s, base_to_tcp[\n 0]], [uy * ux * C + uz * s, uy * uy * C + c, uy * uz * C - ux * s,\n base_to_tcp[1]], [uz * ux * C - uy * s, uz * uy * C + ux * s, uz * uz *\n C + c, base_to_tcp[2]], [0, 0, 0, 1]]'], {}), '([[ux * ux * C + c, ux * uy * C - uz * s, ux * uz * C + uy * s,\n base_to_tcp[0]], [uy * ux * C + uz * s, uy * uy * C + c, uy * uz * C - \n ux * s, base_to_tcp[1]], [uz * ux * C - uy * s, uz * uy * C + ux * s, \n uz * uz * C + c, base_to_tcp[2]], [0, 0, 0, 1]])\n', (658, 925), True, 'import numpy as np\n'), ((1496, 1530), 'numpy.round', 'np.round', (['absolute_position[:3]', '(3)'], {}), '(absolute_position[:3], 3)\n', (1504, 1530), True, 'import numpy as np\n'), ((1305, 1335), 'numpy.array', 'np.array', (['hand_coordinates_raw'], {}), '(hand_coordinates_raw)\n', (1313, 1335), True, 'import numpy as np\n')]
import os import time import sys from glob import glob import numpy as np from tqdm import tqdm import pdb import matplotlib #matplotlib.use('Agg') import matplotlib.pyplot as plt import torch import torch.nn as nn import torch.optim as optim from torch.utils.data import DataLoader import argparse import torch.nn.functional as F from torchvision import datasets, transforms from _dct import LinearDCT import cv2 class CCL_(nn.Module): def __init__(self, c_in, c_out, kernel, stride): super(CCL_, self).__init__() if np.isscalar(kernel): kernel = np.array([kernel, kernel]) if np.isscalar(stride): stride = np.array([stride, stride]) K = np.sqrt(1/(c_in*kernel.prod())) init = (2*torch.rand(c_out,c_in, kernel[0],kernel[1])-1)*K self.weight = nn.Parameter(init) init=(2*torch.rand(c_out)-1)*K self.bias = nn.Parameter(init) self.stride = stride def forward(self, x): # x: N x C_in x H x W dims = x.shape[-2:] dct = LinearDCT(dims[0], 'dct') idct = LinearDCT(dims[0], 'idct') x = dct(x.permute(0,1,3,2)).permute(0,1,3,2) x = torch.fft.rfft(x).unsqueeze(1) w = dct(F.pad(self.weight.permute(0,1,3,2), [0,dims[0]-self.weight.shape[-2]])).permute(0,1,3,2) w = torch.fft.rfft(w, dims[1]) h = (x * w).sum(2) h = torch.fft.irfft(h, dims[1]) h = idct(h.permute(0,1,3,2)).permute(0,1,3,2) + self.bias.reshape(-1, 1, 1) return h[:,:,::self.stride[0],::self.stride[1]] class CCL(nn.Module): def __init__(self, c_in, c_out, kernel, stride): super(CCL, self).__init__() if np.isscalar(kernel): kernel = np.array([kernel, kernel]) if np.isscalar(stride): stride = np.array([stride, stride]) K = np.sqrt(1/(c_in*kernel[0]*kernel[1])) init = (2*torch.rand(c_out,c_in, kernel[0],kernel[1])-1)*K self.weight = nn.Parameter(init) init=(2*torch.rand(c_out)-1)*K self.bias = nn.Parameter(init) self.stride = stride def forward(self, x): # x: N x C_in x H x W dims = x.shape[-2:] x = torch.fft.rfft2(x).unsqueeze(1) w = torch.fft.rfft2(self.weight, dims) h = (x * w).sum(2) h = torch.fft.irfft2(h, dims) + self.bias.reshape(-1, 1, 1) return h[:,:,::self.stride[0],::self.stride[1]] class Net_CNN(nn.Module): def __init__(self): super(Net_CNN, self).__init__() self.conv1 = nn.Conv2d(1, 50, (3, 7), 1, (1,3)) self.conv2 = nn.Conv2d(50, 50, (3,7), 1, (1,3)) self.pool = nn.MaxPool2d((2,4),(2,4)) self.conv3 = nn.ConvTranspose2d(50, 50, (3,5), (2,4),(1,1),(1,1)) self.conv4 = nn.ConvTranspose2d(50, 50, (3,7), (2,4),(1,2),(1,1)) #self.conv3 = nn.ConvTranspose2d(20, 20, (3,5), (1,1),(1,2),(0,0)) #self.conv4 = nn.ConvTranspose2d(20, 20, (3,7), (1,1),(1,3),(0,0)) self.conv5 = nn.ConvTranspose2d(50, 1, (3,7), 1,(1,3)) self.sigmoid = nn.Sigmoid() def forward(self, x): x = x.reshape(-1, 1, x.shape[-2], x.shape[-1]) x = self.pool(self.conv1(x)) x = F.relu(x) x = self.pool(self.conv2(x)) x = F.relu(x) x = x.reshape(-1, 2, x.shape[-3], x.shape[-2], x.shape[-1]) x = x[:, 0]+x[:, 1].mean([-1,-2]).unsqueeze(-1).unsqueeze(-1) x = self.conv3(x) x = F.relu(x) x = self.conv4(x) x = F.relu(x) x = self.sigmoid(self.conv5(x)).squeeze(1) return x class Net_CCL(nn.Module): def __init__(self): super(Net_CCL, self).__init__() self.conv1 = CCL(1, 50, (3, 7), 1) self.conv2 = CCL(50, 50, (3,7), 1) self.pool = nn.MaxPool2d((2,4),(2,4)) self.conv3 = CCL(50, 50, (3,5), 1) self.conv4 = CCL(50, 50, (3,7), 1) self.conv5 = CCL(50, 1, (3,7), 1) self.sigmoid = nn.Sigmoid() def forward(self, x): x = x.reshape(-1, 1, x.shape[-2], x.shape[-1]) x = self.pool(self.conv1(x)) x = F.relu(x) x = self.pool(self.conv2(x)) x = F.relu(x) x = x.reshape(-1, 2, x.shape[-3], x.shape[-2], x.shape[-1]) x = x[:, 0]+x[:, 1].mean([-1,-2]).unsqueeze(-1).unsqueeze(-1) y = torch.zeros(x.shape[0],x.shape[1],x.shape[2]*2,x.shape[3]*4) y[:,:,::2,::4] = x x = self.conv3(y) x = F.relu(x) y = torch.zeros(x.shape[0],x.shape[1],x.shape[2]*2,x.shape[3]*4) y[:,:,::2,::4] = x x = self.conv4(y) x = F.relu(x) x = self.sigmoid(self.conv5(x)).squeeze(1) return x def train(args, model, device, train_loader, optimizer, epoch): model.train() correct = 0 for batch_idx, data in enumerate(train_loader): data = data.to(device) optimizer.zero_grad() output = model(data[:,:2].unsqueeze(2)*2-1) loss = BCE(output, data[:,2]) loss.backward() optimizer.step() correct += ((output > 0.5).type(torch.bool) == (data[:,2]>0.5).type(torch.bool)).sum().item() if batch_idx % args.log_interval == 0: print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format( epoch, batch_idx * len(data), len(train_loader.dataset), 100. * batch_idx / len(train_loader), loss.item())) if args.dry_run: break print('train accuracy: %.2f' %(100. * correct / (len(train_loader.dataset)*data.shape[-1]*data.shape[-2]))) def test(model, device, test_loader, roll=0, flag=False): model.eval() test_loss = 0 correct = 0 conf = np.zeros(4) #[tp,tn,fp,fn] with torch.no_grad(): for i, data in enumerate(test_loader): data = data.to(device) #data = data.flip(-2) #data = data.roll(roll, -1) data[:,[0,2]] = data[:,[0,2]].roll(roll,-1) #data = data.roll(roll,-2) #data[:,:,:roll]=0 output = model(data[:,:2].unsqueeze(2)*2-1) test_loss += BCE(output, data[:,2]).item() # sum up batch loss correct += ((output[:,:,:10] > 0.5).type(torch.bool) == (data[:,2,:,:10]>0.5).type(torch.bool)).sum().item() #pdb.set_trace() #tp = (((output[:,:,:10]>0.5)==data[:,2,:,:10])*(data[:,2,:,:10]==1)).sum().item() #tn = (((output[:,:,:10]>0.5)==data[:,2,:,:10])*(data[:,2,:,:10]==0)).sum().item() if flag: output = torch.cat((data[0,2],output[0]>0.5)).numpy()*255 #pdb.set_trace() output1 = torch.cat((data[0,0],data[0,1])).numpy()*255 cv2.imwrite(save_path + '%.3d.jpg'%i, output) cv2.imwrite(save_path + '%.3d_r.jpg'%i, output1) test_loss /= len(test_loader.dataset) print('\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format( test_loss, correct, len(test_loader.dataset), 100. * correct / (len(test_loader.dataset)*10*data.shape[-2])))#data.shape[-1]*data.shape[-2]))) def main(): # Training settings parser = argparse.ArgumentParser(description='PyTorch MNIST Example') parser.add_argument('--batch-size', type=int, default=1, metavar='N', help='input batch size for training (default: 64)') parser.add_argument('--test-batch-size', type=int, default=1, metavar='N', help='input batch size for testing (default: 1000)') parser.add_argument('--epochs', type=int, default=200, metavar='N', help='number of epochs to train (default: 14)') parser.add_argument('--lr', type=float, default=0.001, metavar='LR', help='learning rate (default: 1.0)') parser.add_argument('--gamma', type=float, default=0.7, metavar='M', help='Learning rate step gamma (default: 0.7)') parser.add_argument('--no-cuda', action='store_true', default=False, help='disables CUDA training') parser.add_argument('--dry-run', action='store_true', default=False, help='quickly check a single pass') parser.add_argument('--seed', type=int, default=1, metavar='S', help='random seed (default: 1)') parser.add_argument('--log-interval', type=int, default=10, metavar='N', help='how many batches to wait before logging training status') parser.add_argument('--save-model', action='store_false', default=True, help='For Saving the current Model') parser.add_argument('--train', action='store_true', default=False, help='For Saving the current Model') parser.add_argument('--which', type=str, default='CCL', help='Choose CCL or CNN layer') args = parser.parse_args() use_cuda = not args.no_cuda and torch.cuda.is_available() torch.manual_seed(args.seed) np.random.seed(args.seed) device = torch.device("cuda" if use_cuda else "cpu") train_kwargs = {'batch_size': args.batch_size} test_kwargs = {'batch_size': args.test_batch_size} if use_cuda: cuda_kwargs = {'num_workers': 1, 'pin_memory': True, 'shuffle': True} train_kwargs.update(cuda_kwargs) test_kwargs.update(cuda_kwargs) data_path = './TSUNAMI/' images = np.zeros((100, 3, 28, 128)) for i in range(100): r_0 = np.random.randint(0,128//2) r_1 = np.random.randint(0,128//2) # if i==34: # cv2.imwrite(save_path+'orig34.jpg',np.concatenate((np.roll(cv2.imread(data_path+'t0/%.8d.jpg'%i),19*8,-2), # np.roll(cv2.imread(data_path+'t1/%.8d.jpg'%i),24*8,-2)))) # pdb.set_trace() images[i,0] = np.roll(cv2.imread(data_path+'t0/%.8d.jpg'%i, 0)[::8,::8],r_0,-1) images[i,1] = np.roll(cv2.imread(data_path+'t1/%.8d.jpg'%i, 0)[::8,::8],r_1,-1) images[i,2] = np.roll(cv2.imread(data_path+'mask/%.8d.png'%i, 0)[::8,::8],r_0,-1) images = torch.FloatTensor(images)/255 idxs = torch.randperm(len(images)) train_idxs = idxs[:int(len(images)*0.8)] test_idxs = idxs[int(len(images)*0.8):] dataset1 = [images[i] for i in train_idxs] dataset2 = [images[i] for i in test_idxs] del images train_loader = torch.utils.data.DataLoader(dataset1, batch_size=args.batch_size, shuffle=True, num_workers=0) test_loader = torch.utils.data.DataLoader(dataset2, batch_size=args.test_batch_size, shuffle=False, num_workers=0) if args.which == 'CNN': model = Net_CNN().to(device) else: model = Net_CCL().to(device) optimizer = optim.Adam(model.parameters(), lr=args.lr) if args.train: #model.load_state_dict(torch.load("change_cnn_%s.pt" %which)) for epoch in range(1, args.epochs + 1): train(args, model, device, train_loader, optimizer, epoch) test(model, device, test_loader,roll=63) if args.save_model: torch.save(model.state_dict(), "change_%s.pt"%args.which) else: model.load_state_dict(torch.load("change_%s.pt"%args.which)) for roll in [15]:#range(128//2): test(model, device, train_loader, roll, flag=False) if __name__ == '__main__': #save_path = './results%s/'%args.which BCE = nn.BCELoss() main()
[ "numpy.random.seed", "argparse.ArgumentParser", "torch.cat", "numpy.random.randint", "_dct.LinearDCT", "torch.fft.irfft", "torch.device", "numpy.sqrt", "torch.no_grad", "torch.nn.BCELoss", "torch.utils.data.DataLoader", "cv2.imwrite", "torch.load", "torch.FloatTensor", "torch.nn.function...
[((6005, 6016), 'numpy.zeros', 'np.zeros', (['(4)'], {}), '(4)\n', (6013, 6016), True, 'import numpy as np\n'), ((7503, 7563), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""PyTorch MNIST Example"""'}), "(description='PyTorch MNIST Example')\n", (7526, 7563), False, 'import argparse\n'), ((9361, 9389), 'torch.manual_seed', 'torch.manual_seed', (['args.seed'], {}), '(args.seed)\n', (9378, 9389), False, 'import torch\n'), ((9395, 9420), 'numpy.random.seed', 'np.random.seed', (['args.seed'], {}), '(args.seed)\n', (9409, 9420), True, 'import numpy as np\n'), ((9437, 9480), 'torch.device', 'torch.device', (["('cuda' if use_cuda else 'cpu')"], {}), "('cuda' if use_cuda else 'cpu')\n", (9449, 9480), False, 'import torch\n'), ((9867, 9894), 'numpy.zeros', 'np.zeros', (['(100, 3, 28, 128)'], {}), '((100, 3, 28, 128))\n', (9875, 9894), True, 'import numpy as np\n'), ((10837, 10936), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['dataset1'], {'batch_size': 'args.batch_size', 'shuffle': '(True)', 'num_workers': '(0)'}), '(dataset1, batch_size=args.batch_size, shuffle=\n True, num_workers=0)\n', (10864, 10936), False, 'import torch\n'), ((10993, 11097), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['dataset2'], {'batch_size': 'args.test_batch_size', 'shuffle': '(False)', 'num_workers': '(0)'}), '(dataset2, batch_size=args.test_batch_size,\n shuffle=False, num_workers=0)\n', (11020, 11097), False, 'import torch\n'), ((11967, 11979), 'torch.nn.BCELoss', 'nn.BCELoss', ([], {}), '()\n', (11977, 11979), True, 'import torch.nn as nn\n'), ((578, 597), 'numpy.isscalar', 'np.isscalar', (['kernel'], {}), '(kernel)\n', (589, 597), True, 'import numpy as np\n'), ((660, 679), 'numpy.isscalar', 'np.isscalar', (['stride'], {}), '(stride)\n', (671, 679), True, 'import numpy as np\n'), ((890, 908), 'torch.nn.Parameter', 'nn.Parameter', (['init'], {}), '(init)\n', (902, 908), True, 'import torch.nn as nn\n'), ((980, 998), 'torch.nn.Parameter', 'nn.Parameter', (['init'], {}), '(init)\n', (992, 998), True, 'import torch.nn as nn\n'), ((1134, 1159), '_dct.LinearDCT', 'LinearDCT', (['dims[0]', '"""dct"""'], {}), "(dims[0], 'dct')\n", (1143, 1159), False, 'from _dct import LinearDCT\n'), ((1176, 1202), '_dct.LinearDCT', 'LinearDCT', (['dims[0]', '"""idct"""'], {}), "(dims[0], 'idct')\n", (1185, 1202), False, 'from _dct import LinearDCT\n'), ((1445, 1471), 'torch.fft.rfft', 'torch.fft.rfft', (['w', 'dims[1]'], {}), '(w, dims[1])\n', (1459, 1471), False, 'import torch\n'), ((1523, 1550), 'torch.fft.irfft', 'torch.fft.irfft', (['h', 'dims[1]'], {}), '(h, dims[1])\n', (1538, 1550), False, 'import torch\n'), ((1848, 1867), 'numpy.isscalar', 'np.isscalar', (['kernel'], {}), '(kernel)\n', (1859, 1867), True, 'import numpy as np\n'), ((1930, 1949), 'numpy.isscalar', 'np.isscalar', (['stride'], {}), '(stride)\n', (1941, 1949), True, 'import numpy as np\n'), ((2027, 2070), 'numpy.sqrt', 'np.sqrt', (['(1 / (c_in * kernel[0] * kernel[1]))'], {}), '(1 / (c_in * kernel[0] * kernel[1]))\n', (2034, 2070), True, 'import numpy as np\n'), ((2166, 2184), 'torch.nn.Parameter', 'nn.Parameter', (['init'], {}), '(init)\n', (2178, 2184), True, 'import torch.nn as nn\n'), ((2256, 2274), 'torch.nn.Parameter', 'nn.Parameter', (['init'], {}), '(init)\n', (2268, 2274), True, 'import torch.nn as nn\n'), ((2463, 2497), 'torch.fft.rfft2', 'torch.fft.rfft2', (['self.weight', 'dims'], {}), '(self.weight, dims)\n', (2478, 2497), False, 'import torch\n'), ((2793, 2828), 'torch.nn.Conv2d', 'nn.Conv2d', (['(1)', '(50)', '(3, 7)', '(1)', '(1, 3)'], {}), '(1, 50, (3, 7), 1, (1, 3))\n', (2802, 2828), True, 'import torch.nn as nn\n'), ((2850, 2886), 'torch.nn.Conv2d', 'nn.Conv2d', (['(50)', '(50)', '(3, 7)', '(1)', '(1, 3)'], {}), '(50, 50, (3, 7), 1, (1, 3))\n', (2859, 2886), True, 'import torch.nn as nn\n'), ((2906, 2934), 'torch.nn.MaxPool2d', 'nn.MaxPool2d', (['(2, 4)', '(2, 4)'], {}), '((2, 4), (2, 4))\n', (2918, 2934), True, 'import torch.nn as nn\n'), ((2954, 3012), 'torch.nn.ConvTranspose2d', 'nn.ConvTranspose2d', (['(50)', '(50)', '(3, 5)', '(2, 4)', '(1, 1)', '(1, 1)'], {}), '(50, 50, (3, 5), (2, 4), (1, 1), (1, 1))\n', (2972, 3012), True, 'import torch.nn as nn\n'), ((3029, 3087), 'torch.nn.ConvTranspose2d', 'nn.ConvTranspose2d', (['(50)', '(50)', '(3, 7)', '(2, 4)', '(1, 2)', '(1, 1)'], {}), '(50, 50, (3, 7), (2, 4), (1, 2), (1, 1))\n', (3047, 3087), True, 'import torch.nn as nn\n'), ((3256, 3300), 'torch.nn.ConvTranspose2d', 'nn.ConvTranspose2d', (['(50)', '(1)', '(3, 7)', '(1)', '(1, 3)'], {}), '(50, 1, (3, 7), 1, (1, 3))\n', (3274, 3300), True, 'import torch.nn as nn\n'), ((3322, 3334), 'torch.nn.Sigmoid', 'nn.Sigmoid', ([], {}), '()\n', (3332, 3334), True, 'import torch.nn as nn\n'), ((3471, 3480), 'torch.nn.functional.relu', 'F.relu', (['x'], {}), '(x)\n', (3477, 3480), True, 'import torch.nn.functional as F\n'), ((3532, 3541), 'torch.nn.functional.relu', 'F.relu', (['x'], {}), '(x)\n', (3538, 3541), True, 'import torch.nn.functional as F\n'), ((3722, 3731), 'torch.nn.functional.relu', 'F.relu', (['x'], {}), '(x)\n', (3728, 3731), True, 'import torch.nn.functional as F\n'), ((3772, 3781), 'torch.nn.functional.relu', 'F.relu', (['x'], {}), '(x)\n', (3778, 3781), True, 'import torch.nn.functional as F\n'), ((4062, 4090), 'torch.nn.MaxPool2d', 'nn.MaxPool2d', (['(2, 4)', '(2, 4)'], {}), '((2, 4), (2, 4))\n', (4074, 4090), True, 'import torch.nn as nn\n'), ((4243, 4255), 'torch.nn.Sigmoid', 'nn.Sigmoid', ([], {}), '()\n', (4253, 4255), True, 'import torch.nn as nn\n'), ((4390, 4399), 'torch.nn.functional.relu', 'F.relu', (['x'], {}), '(x)\n', (4396, 4399), True, 'import torch.nn.functional as F\n'), ((4451, 4460), 'torch.nn.functional.relu', 'F.relu', (['x'], {}), '(x)\n', (4457, 4460), True, 'import torch.nn.functional as F\n'), ((4614, 4681), 'torch.zeros', 'torch.zeros', (['x.shape[0]', 'x.shape[1]', '(x.shape[2] * 2)', '(x.shape[3] * 4)'], {}), '(x.shape[0], x.shape[1], x.shape[2] * 2, x.shape[3] * 4)\n', (4625, 4681), False, 'import torch\n'), ((4743, 4752), 'torch.nn.functional.relu', 'F.relu', (['x'], {}), '(x)\n', (4749, 4752), True, 'import torch.nn.functional as F\n'), ((4766, 4833), 'torch.zeros', 'torch.zeros', (['x.shape[0]', 'x.shape[1]', '(x.shape[2] * 2)', '(x.shape[3] * 4)'], {}), '(x.shape[0], x.shape[1], x.shape[2] * 2, x.shape[3] * 4)\n', (4777, 4833), False, 'import torch\n'), ((4895, 4904), 'torch.nn.functional.relu', 'F.relu', (['x'], {}), '(x)\n', (4901, 4904), True, 'import torch.nn.functional as F\n'), ((6042, 6057), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (6055, 6057), False, 'import torch\n'), ((9328, 9353), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (9351, 9353), False, 'import torch\n'), ((9937, 9967), 'numpy.random.randint', 'np.random.randint', (['(0)', '(128 // 2)'], {}), '(0, 128 // 2)\n', (9954, 9967), True, 'import numpy as np\n'), ((9980, 10010), 'numpy.random.randint', 'np.random.randint', (['(0)', '(128 // 2)'], {}), '(0, 128 // 2)\n', (9997, 10010), True, 'import numpy as np\n'), ((10537, 10562), 'torch.FloatTensor', 'torch.FloatTensor', (['images'], {}), '(images)\n', (10554, 10562), False, 'import torch\n'), ((621, 647), 'numpy.array', 'np.array', (['[kernel, kernel]'], {}), '([kernel, kernel])\n', (629, 647), True, 'import numpy as np\n'), ((703, 729), 'numpy.array', 'np.array', (['[stride, stride]'], {}), '([stride, stride])\n', (711, 729), True, 'import numpy as np\n'), ((1891, 1917), 'numpy.array', 'np.array', (['[kernel, kernel]'], {}), '([kernel, kernel])\n', (1899, 1917), True, 'import numpy as np\n'), ((1973, 1999), 'numpy.array', 'np.array', (['[stride, stride]'], {}), '([stride, stride])\n', (1981, 1999), True, 'import numpy as np\n'), ((2549, 2574), 'torch.fft.irfft2', 'torch.fft.irfft2', (['h', 'dims'], {}), '(h, dims)\n', (2565, 2574), False, 'import torch\n'), ((11734, 11773), 'torch.load', 'torch.load', (["('change_%s.pt' % args.which)"], {}), "('change_%s.pt' % args.which)\n", (11744, 11773), False, 'import torch\n'), ((1272, 1289), 'torch.fft.rfft', 'torch.fft.rfft', (['x'], {}), '(x)\n', (1286, 1289), False, 'import torch\n'), ((2418, 2436), 'torch.fft.rfft2', 'torch.fft.rfft2', (['x'], {}), '(x)\n', (2433, 2436), False, 'import torch\n'), ((7046, 7093), 'cv2.imwrite', 'cv2.imwrite', (["(save_path + '%.3d.jpg' % i)", 'output'], {}), "(save_path + '%.3d.jpg' % i, output)\n", (7057, 7093), False, 'import cv2\n'), ((7109, 7159), 'cv2.imwrite', 'cv2.imwrite', (["(save_path + '%.3d_r.jpg' % i)", 'output1'], {}), "(save_path + '%.3d_r.jpg' % i, output1)\n", (7120, 7159), False, 'import cv2\n'), ((10282, 10326), 'cv2.imread', 'cv2.imread', (["(data_path + 't0/%.8d.jpg' % i)", '(0)'], {}), "(data_path + 't0/%.8d.jpg' % i, 0)\n", (10292, 10326), False, 'import cv2\n'), ((10372, 10416), 'cv2.imread', 'cv2.imread', (["(data_path + 't1/%.8d.jpg' % i)", '(0)'], {}), "(data_path + 't1/%.8d.jpg' % i, 0)\n", (10382, 10416), False, 'import cv2\n'), ((10461, 10507), 'cv2.imread', 'cv2.imread', (["(data_path + 'mask/%.8d.png' % i)", '(0)'], {}), "(data_path + 'mask/%.8d.png' % i, 0)\n", (10471, 10507), False, 'import cv2\n'), ((818, 863), 'torch.rand', 'torch.rand', (['c_out', 'c_in', 'kernel[0]', 'kernel[1]'], {}), '(c_out, c_in, kernel[0], kernel[1])\n', (828, 863), False, 'import torch\n'), ((936, 953), 'torch.rand', 'torch.rand', (['c_out'], {}), '(c_out)\n', (946, 953), False, 'import torch\n'), ((2094, 2139), 'torch.rand', 'torch.rand', (['c_out', 'c_in', 'kernel[0]', 'kernel[1]'], {}), '(c_out, c_in, kernel[0], kernel[1])\n', (2104, 2139), False, 'import torch\n'), ((2212, 2229), 'torch.rand', 'torch.rand', (['c_out'], {}), '(c_out)\n', (2222, 2229), False, 'import torch\n'), ((6874, 6914), 'torch.cat', 'torch.cat', (['(data[0, 2], output[0] > 0.5)'], {}), '((data[0, 2], output[0] > 0.5))\n', (6883, 6914), False, 'import torch\n'), ((6984, 7019), 'torch.cat', 'torch.cat', (['(data[0, 0], data[0, 1])'], {}), '((data[0, 0], data[0, 1]))\n', (6993, 7019), False, 'import torch\n')]
import osqp # solver import numpy as np from scipy import sparse from scipy.sparse import vstack, hstack, eye from warnings import warn class CCOCP: """ CC-OCP: chance-constrained optimal control problem Defines a CC-OCP and adds the model specific constraints and objectives. Parser from model functions, to a CC-OCP problem formulation, to an OSQP problem. Initialization inputs: - m: model object (e.g. Astrobee Model) - verbose_osqp Inner Parameters Information "last" denotes the last iteration around which we linearize OSQP Optimization Problem Definition min 1/2 x^T P x + q^T x s.t. l <= A x <= u with x = [x(1);x(2),...;x(N);u(1);...;u(N-1);slack_vars], where x(k) is (m.n_x), and u(k) is (m.n_u). """ def __init__(self, m, verbose_osqp=False): print('[CCOCP::__init__]: Nb. nodes =', m.N) self.N, N = m.N, m.N # Variables: self.n_t = (N-1) # slack_variables for penalization of trust region csontraints self.nb_vars = N*m.n_x+(N-1)*m.n_u+self.n_t # Optimization Parameters: self.par = dict() self.par['X_last'] = np.empty(shape=[m.n_x, N ]) self.par['U_last'] = np.empty(shape=[m.n_u, N-1]) self.par['f_all_last'] = np.empty(shape=[m.n_x, N-1]) self.par['A_all_last'] = np.empty(shape=[m.n_x*m.n_x, N-1]) self.par['B_all_last'] = np.empty(shape=[m.n_x*m.n_u, N-1]) # Solver Parameters self.params = m.scp_params self.params['eps_dyn'] = 1e-5 self.params['padding_obs'] = 0. self.par['omega'] = self.params["omega0"] # penalization weight self.par['tr_radius'] = self.params["tr_radius0"] # trust region radius # ---------------------------------------------------------------------- # INITIALIZATION self.par['X_last'], self.par['U_last'] = m.initialize_trajectory(N) f_all, A_all, B_all = m.compute_dynamics( self.par['X_last'], self.par['U_last']) Vars_all, Vars_dxu_all = m.propagate_variances(self.par['X_last'], self.par['U_last'], A_all, B_all) self.par['f_all_last'] = f_all self.par['A_all_last'] = A_all self.par['B_all_last'] = B_all self.par['Vars_all_last'] = Vars_all self.par['Vars_dxu_all_last'] = Vars_dxu_all # objective and constraints self.P, self.q = self.get_objective_coeffs(m) self.A, self.l, self.u = self.get_all_constraints_coeffs(m) # Setup OSQP problem self.verbose_osqp = verbose_osqp self.prob = osqp.OSQP() self.prob.setup(self.P, self.q, self.A, self.l, self.u, warm_start=True, verbose=self.verbose_osqp) print("OSQP Problem size: ", "P =",self.P.shape,"q =",self.q.shape, "A =",self.A.shape,"l =",self.l.shape,"u =",self.u.shape) def get_objective_coeffs(self, m): # min 1/2 z^T P x + q^T z N, n_t = self.N, self.n_t # Quadratic Objective Q = m.quadratic_cost_matrix_state QN = np.zeros((m.n_x,m.n_x)) Qt = np.zeros((n_t,n_t)) # trust region slack vars R = m.quadratic_cost_matrix_controls P = sparse.block_diag([sparse.kron(eye(N-1), Q), QN, sparse.kron(eye(N-1), R), Qt], format='csc') # Linear Objective q = np.zeros(self.nb_vars) q += self.get_trust_region_cost_linear() return P, q def get_all_constraints_coeffs(self, m): # Constraints: # l <= A x <= u, with # x = [x(1);x(2),...;x(N);u(1);...;u(N-1)] Aeq_x0, leq_x0, ueq_x0 = self.get_initial_constraints_coeffs(m) Aeq_xf, leq_xf, ueq_xf = self.get_final_constraints_coeffs(m) Aeq_dyn, leq_dyn, ueq_dyn = self.get_dynamics_constraints_coeffs(m) Aineq_lims, lineq_lims, uineq_lims = self.get_input_state_min_max_ineq_constraints_coeffs(m) Aineq_obs, lineq_obs, uineq_obs = self.get_obs_avoidance_constraints_convexified_coeffs(m) A_slack_t, l_slack_t, u_slack_t = self.get_trust_region_constraints_coeffs(m) self.x0_constraints_idx = range(0, Aeq_x0.shape[0]) self.xf_constraints_idx = range(self.x0_constraints_idx[-1], self.x0_constraints_idx[-1]+Aeq_xf.shape[0]) self.dyns_constraints_idx = range(self.xf_constraints_idx[-1], self.xf_constraints_idx[-1]+Aeq_dyn.shape[0]) self.lims_constraints_idx = range(self.dyns_constraints_idx[-1], self.dyns_constraints_idx[-1]+Aineq_lims.shape[0]) self.obs_constraints_idx = range(self.lims_constraints_idx[-1], self.lims_constraints_idx[-1]+Aineq_obs.shape[0]) self.trust_constraints_idx= range(self.obs_constraints_idx[-1], self.obs_constraints_idx[-1]+A_slack_t.shape[0]) A = sparse.vstack([Aeq_x0, Aeq_xf, Aeq_dyn, Aineq_lims, Aineq_obs, A_slack_t], format='csc') l = np.hstack( [leq_x0, leq_xf, leq_dyn, lineq_lims, lineq_obs, l_slack_t]) u = np.hstack( [ueq_x0, ueq_xf, ueq_dyn, uineq_lims, uineq_obs, u_slack_t]) return A, l, u """ ----------- TRUST REGION CONSTRAINTS ------------------ min {omega * max(x, 0)}, where x = |z-z^j|_1 - Delta_j <=> min { t } s.t. omega*( |z-z^j| - Delta_j) <= t 0 <= t """ def get_trust_region_cost_linear(self): # min sum_k {t_k} q_slack_t = np.ones(self.n_t) q_slack_t = np.concatenate((np.zeros(self.nb_vars-self.n_t),q_slack_t), axis=0) return q_slack_t def get_trust_region_constraints_coeffs(self, m): """ |z-z^j|_1 <= t/omega + Delta_j -t <= 0 """ nb_vars, n_x, n_u, n_t, N = self.nb_vars, m.n_x, m.n_u, self.n_t, self.N X_j, U_j, = self.par['X_last'], self.par['U_last'] omega_j, Delta_j = self.par['omega'], self.par['tr_radius'] """ array of permutations to reformulate 1-norm as linear constraints n_u = 1 -> [1], [-1] n_u = 2 -> [1,1], [-1,1], [1,-1], [-1,-1] n_u = 3 -> [1,1,1], [-1,1,1], [1,-1,1], [-1,-1,1], [1,1,-1], [-1,1,-1], [1,-1,-1], [-1,-1,-1] n_u = ... """ mat_arr_weights_u = np.zeros((2**n_u, n_u)) for ui in range(n_u): mat_arr_weights_u[:, ui] = np.array([(-1)**(j//(2**ui)) for j in range(2**n_u)]) # |z-z^j| - Delta_j <= t/omega n_c_k = 2**n_u # number of cosntraints per timestep Aineq = np.zeros((n_t*n_c_k,nb_vars)) lineq = -np.inf * np.ones(n_t*n_c_k) uineq = np.zeros(n_t*n_c_k) for k in range(n_t): idx_uk = N*n_x + k*n_u idx_ukn = N*n_x + k*n_u + n_u idx_tk = N*n_x + (N-1)*n_u + k for ci in range(n_c_k): Aineq[k*n_c_k+ci, idx_uk:idx_ukn] = mat_arr_weights_u[ci,:] Aineq[k*n_c_k+ci, idx_tk ] = -1./omega_j uineq[k*n_c_k+ci] = Delta_j + mat_arr_weights_u[ci,:]@U_j[:,k] # -t <= 0 A_t = np.zeros((n_t,nb_vars)) A_t[:,nb_vars-n_t:] = -np.eye(n_t) l_t = -np.inf * np.ones(n_t) u_t = np.zeros(n_t) A_slack_t = np.concatenate((Aineq, A_t), axis=0) l_slack_t = np.concatenate((lineq, l_t), axis=0) u_slack_t = np.concatenate((uineq, u_t), axis=0) return A_slack_t, l_slack_t, u_slack_t # ----------- TRUST REGION CONSTRAINTS ------------------ def get_initial_constraints_coeffs(self, m): n_vars, n_x, n_u, n_t, N = self.nb_vars, m.n_x, m.n_u, self.n_t, self.N Aeq = hstack([eye(n_x), np.zeros((n_x, (N-1)*n_x)), np.zeros((n_x, n_vars-N*n_x))]) leq = m.x_init ueq = leq return Aeq, leq, ueq def get_final_constraints_coeffs(self, m): n_vars, n_x, n_u, n_t, N = self.nb_vars, m.n_x, m.n_u, self.n_t, self.N Aeq = hstack([np.zeros((n_x, (N-1)*n_x)), eye(n_x), np.zeros((n_x, n_vars-N*n_x))]) leq = m.x_final - 5e-2 ueq = m.x_final + 5e-2 return Aeq, leq, ueq def get_input_state_min_max_ineq_constraints_coeffs(self, m): n_vars, n_x, n_u, n_t, N = self.nb_vars, m.n_x, m.n_u, self.n_t, self.N Aineq = np.zeros((N*n_x+(N-1)*n_u,n_vars)) Am, lm, um = m.state_input_constraints_convexified(self.par['X_last'], self.par['U_last'], B_uncertainty=True, Sigmas=self.par['Vars_all_last'], Sigmas_dxu=self.par['Vars_dxu_all_last']) # nb_i N xu Aineq[:, :(N*n_x) ] = np.reshape(Am[ :, :, :n_x], (-1, N*n_x), order='C') Aineq[:, (N*n_x):(n_vars-n_t)] = np.reshape(Am[ :, :(N-1), n_x:], (-1, (N-1)*n_u), order='C') Aineq = sparse.csr_matrix(Aineq) lineq = lm uineq = um return Aineq, lineq, uineq def get_dynamics_constraints_coeffs(self, m): n_x, n_u, n_t, N = m.n_x, m.n_u, self.n_t, self.N Aeq = np.zeros(((N-1)*n_x, self.nb_vars)) leq = np.zeros((N-1)*n_x) for k in range(N-1): X_kj = self.par['X_last'][:, k] U_kj = self.par['U_last'][:, k] f_dyn_kj = self.par['f_all_last'][:, k] A_kj = np.reshape(self.par['A_all_last'][:, k], (n_x, n_x), order='F') B_kj = np.reshape(self.par['B_all_last'][:, k], (n_x, n_u), order='F') idx_xk = k*n_x idx_xkn = k*n_x + n_x idx_uk = N*n_x + k*n_u # x_{k+1} = f_kj + A_kj@(x_{k}-xj_{k}) + B_kj@(u_{k}-uj_{k} Aeq[idx_xk:idx_xkn, idx_xk :idx_xkn] = A_kj # x_{k} Aeq[idx_xk:idx_xkn, idx_uk :idx_uk +n_u] = B_kj # u_{k} Aeq[idx_xk:idx_xkn, idx_xkn:idx_xkn+n_x] = -np.eye(n_x) # x_{k+1} leq[idx_xk:idx_xkn] = - ( f_dyn_kj - A_kj@X_kj - B_kj@U_kj ) ueq = leq.copy() Aeq = sparse.csr_matrix(Aeq) leq -= self.params['eps_dyn'] ueq += self.params['eps_dyn'] return Aeq, leq, ueq def update_constraints(self, m): """ Problem in OSQP is formatted in the format: min 1/2 x^T P x + q^T x s.t. l <= A x <= u Convention: ### TODO USE INDICES AS GLOBAL VARIABLES !!! - x = (x(0),x(1),...,x(N),u(0),...,u(N-1)) - the first nx constraints l[:nx], u[:nx] correspond to the initial conditions equality constraints. - the next nx constraints l[nx:2*nx], u[nx:2*nx] correspond to the final conditions equality constraints. """ # self.update_dynamics_constraints(m) # self.update_obs_avoidance_constraints(m) # self.prob.update(Ax=self.A.data,l=self.l,u=self.u) P, q = self.get_objective_coeffs(m) A, l, u = self.get_all_constraints_coeffs(m) self.P, self.q = P, q self.A, self.l, self.u = A, l, u self.prob.update(Ax=self.A.data,l=self.l,u=self.u) return False def update_dynamics_constraints_coeffs(self, m, dyn_constraints_idx): n_x, n_u, n_t, N = m.n_x, m.n_u, self.n_t, self.N id0 = dyn_constraints_idx[0] for k in range(N-1): X_kj = self.par['X_last'][:, k] U_kj = self.par['U_last'][:, k] f_dyn_kj = self.par['f_all_last'][:, k] A_kj = np.reshape(self.par['A_all_last'][:, k], (n_x, n_x), order='F') B_kj = np.reshape(self.par['B_all_last'][:, k], (n_x, n_u), order='F') idx_xk = k*n_x idx_xkn = k*n_x + n_x idx_uk = N*n_x + k*n_u idx_c_k = (id0 + idx_xk) idx_c_kn = (id0 + idx_xkn) # x_{k+1} = f_kj + A_kj@(x_{k}-xj_{k}) + B_kj@(u_{k}-uj_{k} self.A[idx_c_k:idx_c_kn, idx_xk :idx_xkn] = A_kj # x_{k} self.A[idx_c_k:idx_c_kn, idx_uk :idx_uk +n_u] = B_kj # u_{k} self.A[idx_c_k:idx_c_kn, idx_xkn:idx_xkn+n_x] = -eye(n_x) # x_{k+1} self.l[idx_c_k:idx_c_kn] = - ( f_dyn_kj - A_kj@X_kj - B_kj@U_kj ) self.u[idx_c_k:idx_c_kn] = self.l[idx_c_k:idx_c_kn] self.l -= self.params['eps_dyn'] self.u += self.params['eps_dyn'] return True def update_dynamics_constraints(self, m): f_all, A_all, B_all = m.compute_dynamics(self.par['X_last'], self.par['U_last']) self.par['f_all_last'] = f_all self.par['A_all_last'] = A_all self.par['B_all_last'] = B_all return self.update_dynamics_constraints_coeffs(m, self.dyns_constraints_idx) def update_obs_avoidance_constraints(self, m): Aineq, lineq, uineq = self.get_obs_avoidance_constraints_convexified_coeffs(m) idx_constraints = self.obs_constraints_idx self.A[idx_constraints, :] = Aineq self.l[idx_constraints] = lineq self.u[idx_constraints] = uineq return True def get_obs_avoidance_constraints_convexified_coeffs(self, m): n_vars, n_x, n_u, n_t, N = self.nb_vars, m.n_x, m.n_u, self.n_t, self.N # Spherical Obstacles n_obs = len(m.obstacles) Aineq = np.zeros((N*n_obs, self.nb_vars)) lineq = -np.inf * np.ones(N*n_obs) uineq = np.zeros(N*n_obs) for k in range(N): Var_k = self.par['Vars_all_last'][:,:,k] Var_dxu_k = self.par['Vars_dxu_all_last'][:,:,:,:,k] for obs_i in range(n_obs): A_i, b_i = m.obs_avoidance_constraint_convexified(self.par['X_last'], self.par['U_last'], obs_i, k, B_uncertainty=True, Sigma_k=Var_k, Sigma_dxu_k=Var_dxu_k, obs_type='sphere') # [N,n_xu] Aineq[k*n_obs+obs_i, :(N*n_x)] = np.reshape(A_i[:, :n_x], (N*n_x), order='C') Aineq[k*n_obs+obs_i, (N*n_x):(n_vars-n_t)] = np.reshape(A_i[:(N-1),n_x:], ((N-1)*n_u), order='C') uineq[k*n_obs+obs_i] = b_i # Rectangular Obstacles n_obs = len(m.poly_obstacles) Aineq_poly = np.zeros((N*n_obs, self.nb_vars)) lineq_poly = -np.inf * np.ones(N*n_obs) uineq_poly = np.zeros(N*n_obs) for k in range(N): Var_k = self.par['Vars_all_last'][:,:,k] Var_dxu_k = self.par['Vars_dxu_all_last'][:,:,:,:,k] for obs_i in range(n_obs): A_i, b_i = m.obs_avoidance_constraint_convexified(self.par['X_last'], self.par['U_last'], obs_i, k, B_uncertainty=True, Sigma_k=Var_k, Sigma_dxu_k=Var_dxu_k, obs_type='poly') # [N,n_xu] Aineq_poly[k*n_obs+obs_i, :(N*n_x)] = np.reshape(A_i[:, :n_x], (N*n_x), order='C') Aineq_poly[k*n_obs+obs_i, (N*n_x):(n_vars-n_t)] = np.reshape(A_i[:(N-1),n_x:], ((N-1)*n_u), order='C') uineq_poly[k*n_obs+obs_i] = b_i Aineq = np.concatenate((Aineq, Aineq_poly), axis=0) lineq = np.concatenate((lineq, lineq_poly), axis=0) uineq = np.concatenate((uineq, uineq_poly), axis=0) Aineq = sparse.csr_matrix(Aineq) lineq = lineq - self.params['padding_obs'] uineq = uineq + self.params['padding_obs'] return Aineq, lineq, uineq def solve_OSQP(self): B_problem_solved = True self.res = self.prob.solve() if self.res.info.status != 'solved': warn("[solve_OSQP]: Problem unfeasible.") B_problem_solved = False return B_problem_solved def solve_ccscp(self, m): N = self.N (tr_radius0, omega0, omegamax, epsilon, rho0, rho1, beta_succ, beta_fail, gamma_fail, conv_thresh) = self.extract_scp_params() self.par['omega'] = self.params["omega0"] self.par['tr_radius'] = self.params["tr_radius0"] # Initialization self.par['X_last'], self.par['U_last'] = m.initialize_trajectory(N) X = self.par['X_last'].copy(); Xp = X.copy() U = self.par['U_last'].copy(); Up = U.copy() all_X, all_U, all_V = [], [], [] it = 0 B_success = False while it<self.params["NB_SCP_iter_max"] and \ not(it!=0 and B_success and self.convergence_metric(X,U,Xp,Up)<conv_thresh) and \ self.par['omega']<self.params["omegamax"]: print('\n'+'=' * 50) print('Iteration ' + str(it)) print('-' * 50) B_success = False self.par['X_last'], self.par['U_last'] = X.copy(), U.copy() f_all, A_all, B_all = m.compute_dynamics( self.par['X_last'], self.par['U_last']) Vars_all, Vars_dxu_all = m.propagate_variances(self.par['X_last'], self.par['U_last'], A_all, B_all) self.par['f_all_last'] = f_all self.par['A_all_last'] = A_all self.par['B_all_last'] = B_all self.par['Vars_all_last'] = Vars_all self.par['Vars_dxu_all_last'] = Vars_dxu_all all_X.append(X.copy()) all_U.append(U.copy()) all_V.append(Vars_all.copy()) # Help to find feasible solution at first iteration (not always necessary) if it == 0: self.params['padding_obs'] = 0.1 else: self.params['padding_obs'] = 0. self.update_constraints(m) self.B_solved_successfully = self.solve_OSQP() X_sol, U_sol = self.get_XU_solution_OSQP(m) if self.B_solved_successfully == False: print('[solve_ccscp] Failure to solve SCP iter #'+str(it)) self.all_X = np.stack(all_X.copy()) self.all_U = np.stack(all_U.copy()) self.all_V = np.stack(all_V.copy()) return False # check trust region Xp, Up = self.par['X_last'].copy(), self.par['U_last'].copy() print('np.linalg.norm(X_sol-Xp,2) = ' + str(np.linalg.norm(X_sol-Xp,2))) if np.linalg.norm(X_sol-Xp,2) < self.par['tr_radius']: rho = self.accuracy_ratio(m, X_sol,U_sol,Xp,Up) if rho > rho1: print('Reject solution.') self.par['tr_radius'] = beta_fail * self.par['tr_radius'] self.par['omega'] = self.par['omega'] B_success = False else: print('-' * 50) print('Accept solution.') print('-' * 50) X, U = X_sol.copy(), U_sol.copy() B_success = True if rho < rho0: self.par['tr_radius'] = np.minimum(beta_succ*self.par['tr_radius'], tr_radius0) else: self.par['tr_radius'] = self.par['tr_radius'] else: print('Reject solution (Outside trust region)') print('norm(x_sol-xp,2)=',np.linalg.norm(X_sol-Xp,2)) self.par['omega'] = gamma_fail * self.par['omega'] B_success = False it += 1 self.all_X, self.all_U, self.all_V = np.stack(all_X), np.stack(all_U), np.stack(all_V) print('[solve_ccscp] Success: '+str(B_success)+', Nb of iterations: '+str(it)) return True def get_XU_solution_OSQP(self, m): nb_vars, n_x, n_u, n_t, N = self.nb_vars, m.n_x, m.n_u, self.n_t, self.N X_sol = np.reshape(self.res.x[:N*n_x], (n_x, N), order='F') U_sol = np.reshape(self.res.x[N*n_x:nb_vars-n_t], (n_u, N-1), order='F') return X_sol, U_sol def get_XU_solution_CCSCP(self, m): return self.get_XU_solution_OSQP(m) def convergence_metric(self, X, U, Xp, Up): conv_metric = ((np.linalg.norm(X-Xp,2)/np.linalg.norm(Xp,2)) + (np.linalg.norm(U-Up,2)/np.linalg.norm(Up,2))) # print('Convergence Metric: '+"{0:.2f}".format(100.*conv_metric)+'%') return conv_metric def accuracy_ratio(self, m, X, U, Xp, Up): num, den = 0.0, 0.0 for k in range(self.N-1): x_k, u_k = X[:,k], U[:,k] x_p, u_p = Xp[:,k], Up[:,k] f_dyn_k = np.squeeze(m.f_dt(x_k, u_k)) f_dyn_p, A_dyn_p, B_dyn_p = m.get_dynamics(x_p, u_p) f_dyn_p = (self.par['f_all_last'][:, k]) linearized = f_dyn_p + A_dyn_p@(x_k-x_p) + B_dyn_p@(u_k-u_p) num += np.dot((f_dyn_k - linearized),(f_dyn_k - linearized)) den += np.dot(linearized,linearized) accuracy_ratio = num/den return accuracy_ratio def extract_scp_params(self): (tr_radius0, omega0, omegamax, epsilon, rho0, rho1, beta_succ, beta_fail, gamma_fail, conv_thresh) = (self.params["tr_radius0"], self.params["omega0"], self.params["omegamax"], self.params["epsilon"], self.params["rho0"], self.params["rho1"], self.params["beta_succ"], self.params["beta_fail"], self.params["gamma_fail"], self.params["convergence_threshold"]) return (tr_radius0, omega0, omegamax, epsilon, rho0, rho1, beta_succ, beta_fail, gamma_fail, conv_thresh) def check_obs_avoidance_constraints_satisfied(self, m, X): N = self.N n_obs = len(m.obstacles) B_inside_obs = False for k in range(N): x_k = X[:,k] for obs_i in range(n_obs): penalty = m.obs_avoidance_constraint(x_k, obs_i) if penalty>1e-9: B_inside_obs = True print("robot inside obstacle ",obs_i,"at k=",k,": penalty=",penalty) return not(B_inside_obs)
[ "numpy.stack", "numpy.minimum", "scipy.sparse.vstack", "numpy.empty", "scipy.sparse.eye", "numpy.zeros", "numpy.ones", "numpy.hstack", "scipy.sparse.csr_matrix", "osqp.OSQP", "numpy.reshape", "numpy.linalg.norm", "numpy.dot", "numpy.eye", "warnings.warn", "numpy.concatenate" ]
[((1342, 1368), 'numpy.empty', 'np.empty', ([], {'shape': '[m.n_x, N]'}), '(shape=[m.n_x, N])\n', (1350, 1368), True, 'import numpy as np\n'), ((1410, 1440), 'numpy.empty', 'np.empty', ([], {'shape': '[m.n_u, N - 1]'}), '(shape=[m.n_u, N - 1])\n', (1418, 1440), True, 'import numpy as np\n'), ((1478, 1508), 'numpy.empty', 'np.empty', ([], {'shape': '[m.n_x, N - 1]'}), '(shape=[m.n_x, N - 1])\n', (1486, 1508), True, 'import numpy as np\n'), ((1546, 1584), 'numpy.empty', 'np.empty', ([], {'shape': '[m.n_x * m.n_x, N - 1]'}), '(shape=[m.n_x * m.n_x, N - 1])\n', (1554, 1584), True, 'import numpy as np\n'), ((1614, 1652), 'numpy.empty', 'np.empty', ([], {'shape': '[m.n_x * m.n_u, N - 1]'}), '(shape=[m.n_x * m.n_u, N - 1])\n', (1622, 1652), True, 'import numpy as np\n'), ((2928, 2939), 'osqp.OSQP', 'osqp.OSQP', ([], {}), '()\n', (2937, 2939), False, 'import osqp\n'), ((3460, 3484), 'numpy.zeros', 'np.zeros', (['(m.n_x, m.n_x)'], {}), '((m.n_x, m.n_x))\n', (3468, 3484), True, 'import numpy as np\n'), ((3497, 3517), 'numpy.zeros', 'np.zeros', (['(n_t, n_t)'], {}), '((n_t, n_t))\n', (3505, 3517), True, 'import numpy as np\n'), ((3772, 3794), 'numpy.zeros', 'np.zeros', (['self.nb_vars'], {}), '(self.nb_vars)\n', (3780, 3794), True, 'import numpy as np\n'), ((5515, 5607), 'scipy.sparse.vstack', 'sparse.vstack', (['[Aeq_x0, Aeq_xf, Aeq_dyn, Aineq_lims, Aineq_obs, A_slack_t]'], {'format': '"""csc"""'}), "([Aeq_x0, Aeq_xf, Aeq_dyn, Aineq_lims, Aineq_obs, A_slack_t],\n format='csc')\n", (5528, 5607), False, 'from scipy import sparse\n'), ((5616, 5686), 'numpy.hstack', 'np.hstack', (['[leq_x0, leq_xf, leq_dyn, lineq_lims, lineq_obs, l_slack_t]'], {}), '([leq_x0, leq_xf, leq_dyn, lineq_lims, lineq_obs, l_slack_t])\n', (5625, 5686), True, 'import numpy as np\n'), ((5703, 5773), 'numpy.hstack', 'np.hstack', (['[ueq_x0, ueq_xf, ueq_dyn, uineq_lims, uineq_obs, u_slack_t]'], {}), '([ueq_x0, ueq_xf, ueq_dyn, uineq_lims, uineq_obs, u_slack_t])\n', (5712, 5773), True, 'import numpy as np\n'), ((6176, 6193), 'numpy.ones', 'np.ones', (['self.n_t'], {}), '(self.n_t)\n', (6183, 6193), True, 'import numpy as np\n'), ((7014, 7039), 'numpy.zeros', 'np.zeros', (['(2 ** n_u, n_u)'], {}), '((2 ** n_u, n_u))\n', (7022, 7039), True, 'import numpy as np\n'), ((7283, 7315), 'numpy.zeros', 'np.zeros', (['(n_t * n_c_k, nb_vars)'], {}), '((n_t * n_c_k, nb_vars))\n', (7291, 7315), True, 'import numpy as np\n'), ((7374, 7395), 'numpy.zeros', 'np.zeros', (['(n_t * n_c_k)'], {}), '(n_t * n_c_k)\n', (7382, 7395), True, 'import numpy as np\n'), ((7853, 7877), 'numpy.zeros', 'np.zeros', (['(n_t, nb_vars)'], {}), '((n_t, nb_vars))\n', (7861, 7877), True, 'import numpy as np\n'), ((7971, 7984), 'numpy.zeros', 'np.zeros', (['n_t'], {}), '(n_t)\n', (7979, 7984), True, 'import numpy as np\n'), ((8007, 8043), 'numpy.concatenate', 'np.concatenate', (['(Aineq, A_t)'], {'axis': '(0)'}), '((Aineq, A_t), axis=0)\n', (8021, 8043), True, 'import numpy as np\n'), ((8064, 8100), 'numpy.concatenate', 'np.concatenate', (['(lineq, l_t)'], {'axis': '(0)'}), '((lineq, l_t), axis=0)\n', (8078, 8100), True, 'import numpy as np\n'), ((8121, 8157), 'numpy.concatenate', 'np.concatenate', (['(uineq, u_t)'], {'axis': '(0)'}), '((uineq, u_t), axis=0)\n', (8135, 8157), True, 'import numpy as np\n'), ((9038, 9081), 'numpy.zeros', 'np.zeros', (['(N * n_x + (N - 1) * n_u, n_vars)'], {}), '((N * n_x + (N - 1) * n_u, n_vars))\n', (9046, 9081), True, 'import numpy as np\n'), ((9532, 9584), 'numpy.reshape', 'np.reshape', (['Am[:, :, :n_x]', '(-1, N * n_x)'], {'order': '"""C"""'}), "(Am[:, :, :n_x], (-1, N * n_x), order='C')\n", (9542, 9584), True, 'import numpy as np\n'), ((9634, 9697), 'numpy.reshape', 'np.reshape', (['Am[:, :N - 1, n_x:]', '(-1, (N - 1) * n_u)'], {'order': '"""C"""'}), "(Am[:, :N - 1, n_x:], (-1, (N - 1) * n_u), order='C')\n", (9644, 9697), True, 'import numpy as np\n'), ((9711, 9735), 'scipy.sparse.csr_matrix', 'sparse.csr_matrix', (['Aineq'], {}), '(Aineq)\n', (9728, 9735), False, 'from scipy import sparse\n'), ((9933, 9972), 'numpy.zeros', 'np.zeros', (['((N - 1) * n_x, self.nb_vars)'], {}), '(((N - 1) * n_x, self.nb_vars))\n', (9941, 9972), True, 'import numpy as np\n'), ((9983, 10006), 'numpy.zeros', 'np.zeros', (['((N - 1) * n_x)'], {}), '((N - 1) * n_x)\n', (9991, 10006), True, 'import numpy as np\n'), ((10894, 10916), 'scipy.sparse.csr_matrix', 'sparse.csr_matrix', (['Aeq'], {}), '(Aeq)\n', (10911, 10916), False, 'from scipy import sparse\n'), ((14212, 14247), 'numpy.zeros', 'np.zeros', (['(N * n_obs, self.nb_vars)'], {}), '((N * n_obs, self.nb_vars))\n', (14220, 14247), True, 'import numpy as np\n'), ((14305, 14324), 'numpy.zeros', 'np.zeros', (['(N * n_obs)'], {}), '(N * n_obs)\n', (14313, 14324), True, 'import numpy as np\n'), ((15178, 15213), 'numpy.zeros', 'np.zeros', (['(N * n_obs, self.nb_vars)'], {}), '((N * n_obs, self.nb_vars))\n', (15186, 15213), True, 'import numpy as np\n'), ((15281, 15300), 'numpy.zeros', 'np.zeros', (['(N * n_obs)'], {}), '(N * n_obs)\n', (15289, 15300), True, 'import numpy as np\n'), ((16087, 16130), 'numpy.concatenate', 'np.concatenate', (['(Aineq, Aineq_poly)'], {'axis': '(0)'}), '((Aineq, Aineq_poly), axis=0)\n', (16101, 16130), True, 'import numpy as np\n'), ((16147, 16190), 'numpy.concatenate', 'np.concatenate', (['(lineq, lineq_poly)'], {'axis': '(0)'}), '((lineq, lineq_poly), axis=0)\n', (16161, 16190), True, 'import numpy as np\n'), ((16207, 16250), 'numpy.concatenate', 'np.concatenate', (['(uineq, uineq_poly)'], {'axis': '(0)'}), '((uineq, uineq_poly), axis=0)\n', (16221, 16250), True, 'import numpy as np\n'), ((16268, 16292), 'scipy.sparse.csr_matrix', 'sparse.csr_matrix', (['Aineq'], {}), '(Aineq)\n', (16285, 16292), False, 'from scipy import sparse\n'), ((20735, 20788), 'numpy.reshape', 'np.reshape', (['self.res.x[:N * n_x]', '(n_x, N)'], {'order': '"""F"""'}), "(self.res.x[:N * n_x], (n_x, N), order='F')\n", (20745, 20788), True, 'import numpy as np\n'), ((20816, 20886), 'numpy.reshape', 'np.reshape', (['self.res.x[N * n_x:nb_vars - n_t]', '(n_u, N - 1)'], {'order': '"""F"""'}), "(self.res.x[N * n_x:nb_vars - n_t], (n_u, N - 1), order='F')\n", (20826, 20886), True, 'import numpy as np\n'), ((7339, 7359), 'numpy.ones', 'np.ones', (['(n_t * n_c_k)'], {}), '(n_t * n_c_k)\n', (7346, 7359), True, 'import numpy as np\n'), ((7908, 7919), 'numpy.eye', 'np.eye', (['n_t'], {}), '(n_t)\n', (7914, 7919), True, 'import numpy as np\n'), ((7944, 7956), 'numpy.ones', 'np.ones', (['n_t'], {}), '(n_t)\n', (7951, 7956), True, 'import numpy as np\n'), ((10203, 10266), 'numpy.reshape', 'np.reshape', (["self.par['A_all_last'][:, k]", '(n_x, n_x)'], {'order': '"""F"""'}), "(self.par['A_all_last'][:, k], (n_x, n_x), order='F')\n", (10213, 10266), True, 'import numpy as np\n'), ((10290, 10353), 'numpy.reshape', 'np.reshape', (["self.par['B_all_last'][:, k]", '(n_x, n_u)'], {'order': '"""F"""'}), "(self.par['B_all_last'][:, k], (n_x, n_u), order='F')\n", (10300, 10353), True, 'import numpy as np\n'), ((12409, 12472), 'numpy.reshape', 'np.reshape', (["self.par['A_all_last'][:, k]", '(n_x, n_x)'], {'order': '"""F"""'}), "(self.par['A_all_last'][:, k], (n_x, n_x), order='F')\n", (12419, 12472), True, 'import numpy as np\n'), ((12496, 12559), 'numpy.reshape', 'np.reshape', (["self.par['B_all_last'][:, k]", '(n_x, n_u)'], {'order': '"""F"""'}), "(self.par['B_all_last'][:, k], (n_x, n_u), order='F')\n", (12506, 12559), True, 'import numpy as np\n'), ((14272, 14290), 'numpy.ones', 'np.ones', (['(N * n_obs)'], {}), '(N * n_obs)\n', (14279, 14290), True, 'import numpy as np\n'), ((15243, 15261), 'numpy.ones', 'np.ones', (['(N * n_obs)'], {}), '(N * n_obs)\n', (15250, 15261), True, 'import numpy as np\n'), ((16585, 16626), 'warnings.warn', 'warn', (['"""[solve_OSQP]: Problem unfeasible."""'], {}), "('[solve_OSQP]: Problem unfeasible.')\n", (16589, 16626), False, 'from warnings import warn\n'), ((20439, 20454), 'numpy.stack', 'np.stack', (['all_X'], {}), '(all_X)\n', (20447, 20454), True, 'import numpy as np\n'), ((20456, 20471), 'numpy.stack', 'np.stack', (['all_U'], {}), '(all_U)\n', (20464, 20471), True, 'import numpy as np\n'), ((20473, 20488), 'numpy.stack', 'np.stack', (['all_V'], {}), '(all_V)\n', (20481, 20488), True, 'import numpy as np\n'), ((21745, 21795), 'numpy.dot', 'np.dot', (['(f_dyn_k - linearized)', '(f_dyn_k - linearized)'], {}), '(f_dyn_k - linearized, f_dyn_k - linearized)\n', (21751, 21795), True, 'import numpy as np\n'), ((21818, 21848), 'numpy.dot', 'np.dot', (['linearized', 'linearized'], {}), '(linearized, linearized)\n', (21824, 21848), True, 'import numpy as np\n'), ((6230, 6263), 'numpy.zeros', 'np.zeros', (['(self.nb_vars - self.n_t)'], {}), '(self.nb_vars - self.n_t)\n', (6238, 6263), True, 'import numpy as np\n'), ((8422, 8430), 'scipy.sparse.eye', 'eye', (['n_x'], {}), '(n_x)\n', (8425, 8430), False, 'from scipy.sparse import vstack, hstack, eye\n'), ((8432, 8462), 'numpy.zeros', 'np.zeros', (['(n_x, (N - 1) * n_x)'], {}), '((n_x, (N - 1) * n_x))\n', (8440, 8462), True, 'import numpy as np\n'), ((8460, 8493), 'numpy.zeros', 'np.zeros', (['(n_x, n_vars - N * n_x)'], {}), '((n_x, n_vars - N * n_x))\n', (8468, 8493), True, 'import numpy as np\n'), ((8713, 8743), 'numpy.zeros', 'np.zeros', (['(n_x, (N - 1) * n_x)'], {}), '((n_x, (N - 1) * n_x))\n', (8721, 8743), True, 'import numpy as np\n'), ((8741, 8749), 'scipy.sparse.eye', 'eye', (['n_x'], {}), '(n_x)\n', (8744, 8749), False, 'from scipy.sparse import vstack, hstack, eye\n'), ((8751, 8784), 'numpy.zeros', 'np.zeros', (['(n_x, n_vars - N * n_x)'], {}), '((n_x, n_vars - N * n_x))\n', (8759, 8784), True, 'import numpy as np\n'), ((10737, 10748), 'numpy.eye', 'np.eye', (['n_x'], {}), '(n_x)\n', (10743, 10748), True, 'import numpy as np\n'), ((13037, 13045), 'scipy.sparse.eye', 'eye', (['n_x'], {}), '(n_x)\n', (13040, 13045), False, 'from scipy.sparse import vstack, hstack, eye\n'), ((14849, 14893), 'numpy.reshape', 'np.reshape', (['A_i[:, :n_x]', '(N * n_x)'], {'order': '"""C"""'}), "(A_i[:, :n_x], N * n_x, order='C')\n", (14859, 14893), True, 'import numpy as np\n'), ((14963, 15018), 'numpy.reshape', 'np.reshape', (['A_i[:N - 1, n_x:]', '((N - 1) * n_u)'], {'order': '"""C"""'}), "(A_i[:N - 1, n_x:], (N - 1) * n_u, order='C')\n", (14973, 15018), True, 'import numpy as np\n'), ((15828, 15872), 'numpy.reshape', 'np.reshape', (['A_i[:, :n_x]', '(N * n_x)'], {'order': '"""C"""'}), "(A_i[:, :n_x], N * n_x, order='C')\n", (15838, 15872), True, 'import numpy as np\n'), ((15947, 16002), 'numpy.reshape', 'np.reshape', (['A_i[:N - 1, n_x:]', '((N - 1) * n_u)'], {'order': '"""C"""'}), "(A_i[:N - 1, n_x:], (N - 1) * n_u, order='C')\n", (15957, 16002), True, 'import numpy as np\n'), ((19272, 19301), 'numpy.linalg.norm', 'np.linalg.norm', (['(X_sol - Xp)', '(2)'], {}), '(X_sol - Xp, 2)\n', (19286, 19301), True, 'import numpy as np\n'), ((21069, 21094), 'numpy.linalg.norm', 'np.linalg.norm', (['(X - Xp)', '(2)'], {}), '(X - Xp, 2)\n', (21083, 21094), True, 'import numpy as np\n'), ((21092, 21113), 'numpy.linalg.norm', 'np.linalg.norm', (['Xp', '(2)'], {}), '(Xp, 2)\n', (21106, 21113), True, 'import numpy as np\n'), ((21141, 21166), 'numpy.linalg.norm', 'np.linalg.norm', (['(U - Up)', '(2)'], {}), '(U - Up, 2)\n', (21155, 21166), True, 'import numpy as np\n'), ((21164, 21185), 'numpy.linalg.norm', 'np.linalg.norm', (['Up', '(2)'], {}), '(Up, 2)\n', (21178, 21185), True, 'import numpy as np\n'), ((3638, 3648), 'scipy.sparse.eye', 'eye', (['(N - 1)'], {}), '(N - 1)\n', (3641, 3648), False, 'from scipy.sparse import vstack, hstack, eye\n'), ((3700, 3710), 'scipy.sparse.eye', 'eye', (['(N - 1)'], {}), '(N - 1)\n', (3703, 3710), False, 'from scipy.sparse import vstack, hstack, eye\n'), ((20235, 20264), 'numpy.linalg.norm', 'np.linalg.norm', (['(X_sol - Xp)', '(2)'], {}), '(X_sol - Xp, 2)\n', (20249, 20264), True, 'import numpy as np\n'), ((19228, 19257), 'numpy.linalg.norm', 'np.linalg.norm', (['(X_sol - Xp)', '(2)'], {}), '(X_sol - Xp, 2)\n', (19242, 19257), True, 'import numpy as np\n'), ((19959, 20016), 'numpy.minimum', 'np.minimum', (["(beta_succ * self.par['tr_radius'])", 'tr_radius0'], {}), "(beta_succ * self.par['tr_radius'], tr_radius0)\n", (19969, 20016), True, 'import numpy as np\n')]
import os import pickle from parameters import * import tensorflow as tf import numpy as np def load_data(): """ Loading Data """ input_file = os.path.join(TEXT_SAVE_DIR) with open(input_file, "r") as f: data = f.read() return data def preprocess_and_save_data(): """ Preprocessing the Book Scripts Dataset """ text = load_data() token_dict = define_tokens() for key, token in token_dict.items(): text = text.replace(key, ' {} '.format(token)) text = text.lower() text = text.split() vocab_to_int, int_to_vocab = create_map(text) int_text = [vocab_to_int[word] for word in text] pickle.dump((int_text, vocab_to_int, int_to_vocab, token_dict), open('processed_text.p', 'wb')) def load_preprocess_file(): """ Loading the processed Book Scripts Data """ return pickle.load(open('processed_text.p', mode='rb')) def save_params(params): """ Saving parameters to file """ pickle.dump(params, open('parameters.p', 'wb')) def load_params(): """ Loading parameters from file """ return pickle.load(open('parameters.p', mode='rb')) def create_map(input_text): """ Map words in vocab to int and vice versa for easy lookup :param input_text: Book Script data split into words :return: A tuple of dicts (vocab_to_int, int_to_vocab) """ vocab = set(input_text) vocab_to_int = {c: i for i, c in enumerate(vocab)} int_to_vocab = dict(enumerate(vocab)) return vocab_to_int, int_to_vocab def define_tokens(): """ Generate a dict to turn punctuation into a token. Note that Sym before each text denotes Symbol :return: Tokenize dictionary where the key is the punctuation and the value is the token """ dict = {'.':'_Sym_Period_', ',':'_Sym_Comma_', '"':'_Sym_Quote_', ';':'_Sym_Semicolon_', '!':'_Sym_Exclamation_', '?':'_Sym_Question_', '(':'_Sym_Left_Parentheses_', ')':'_Sym_Right_Parentheses_', '--':'_Sym_Dash_', '\n':'_Sym_Return_', } return dict def generate_batch_data(int_text): """ Generate batch data of x (inputs) and y (targets) :param int_text: Text with the words replaced by their ids :return: Batches as a Numpy array """ num_batches = len(int_text) // (BATCH_SIZE * SEQ_LENGTH) x = np.array(int_text[:num_batches * (BATCH_SIZE * SEQ_LENGTH)]) y = np.array(int_text[1:num_batches * (BATCH_SIZE * SEQ_LENGTH) + 1]) x_batches = np.split(x.reshape(BATCH_SIZE, -1), num_batches, 1) y_batches = np.split(y.reshape(BATCH_SIZE, -1), num_batches, 1) batches = np.array(list(zip(x_batches, y_batches))) return batches def extract_tensors(tf_graph): """ Get input, initial state, final state, and probabilities tensor from the graph :param loaded_graph: TensorFlow graph loaded from file :return: Tuple (tensor_input,tensor_initial_state,tensor_final_state, tensor_probs) """ tensor_input = tf_graph.get_tensor_by_name("Input/input:0") tensor_initial_state = tf_graph.get_tensor_by_name("Network/initial_state:0") tensor_final_state = tf_graph.get_tensor_by_name("Network/final_state:0") tensor_probs = tf_graph.get_tensor_by_name("Network/probs:0") return tensor_input, tensor_initial_state, tensor_final_state, tensor_probs def select_next_word(probs, int_to_vocab): """ Select the next work for the generated text :param probs: list of probabilities of all the words in vocab which can be selected as next word :param int_to_vocab: Dictionary of word ids as the keys and words as the values :return: predicted next word """ index = np.argmax(probs) word = int_to_vocab[index] return word def predict_book_script(): _, vocab_to_int, int_to_vocab, token_dict = load_preprocess_file() seq_length, load_dir = load_params() script_length = 250 # Length of Book script to generate. 250 denotes 250 words first_word = 'postgresql' # postgresql or any other word from the book loaded_graph = tf.Graph() with tf.Session(graph=loaded_graph) as sess: # Load saved model loader = tf.train.import_meta_graph(load_dir + '.meta') loader.restore(sess, load_dir) # Get Tensors from loaded model input_text, initial_state, final_state, probs = extract_tensors(loaded_graph) # Sentences generation setup sentences = [first_word] previous_state = sess.run(initial_state, {input_text: np.array([[1]])}) # Generate sentences for i in range(script_length): # Dynamic Input dynamic_input = [[vocab_to_int[word] for word in sentences[-seq_length:]]] dynamic_seq_length = len(dynamic_input[0]) # Get Prediction probabilities, previous_state = sess.run([probs, final_state], {input_text: dynamic_input, initial_state: previous_state}) probabilities= np.squeeze(probabilities) pred_word = select_next_word(probabilities[dynamic_seq_length - 1], int_to_vocab) sentences.append(pred_word) # Scraping out tokens from the words book_script = ' '.join(sentences) for key, token in token_dict.items(): book_script = book_script.replace(' ' + token.lower(), key) book_script = book_script.replace('\n ', '\n') book_script = book_script.replace('( ', '(') # Write the generated script to a file with open("book_script", "w") as text_file: text_file.write(book_script) print(book_script)
[ "numpy.argmax", "tensorflow.train.import_meta_graph", "tensorflow.Session", "numpy.array", "tensorflow.Graph", "numpy.squeeze", "os.path.join" ]
[((160, 187), 'os.path.join', 'os.path.join', (['TEXT_SAVE_DIR'], {}), '(TEXT_SAVE_DIR)\n', (172, 187), False, 'import os\n'), ((2436, 2496), 'numpy.array', 'np.array', (['int_text[:num_batches * (BATCH_SIZE * SEQ_LENGTH)]'], {}), '(int_text[:num_batches * (BATCH_SIZE * SEQ_LENGTH)])\n', (2444, 2496), True, 'import numpy as np\n'), ((2505, 2570), 'numpy.array', 'np.array', (['int_text[1:num_batches * (BATCH_SIZE * SEQ_LENGTH) + 1]'], {}), '(int_text[1:num_batches * (BATCH_SIZE * SEQ_LENGTH) + 1])\n', (2513, 2570), True, 'import numpy as np\n'), ((3769, 3785), 'numpy.argmax', 'np.argmax', (['probs'], {}), '(probs)\n', (3778, 3785), True, 'import numpy as np\n'), ((4154, 4164), 'tensorflow.Graph', 'tf.Graph', ([], {}), '()\n', (4162, 4164), True, 'import tensorflow as tf\n'), ((4174, 4204), 'tensorflow.Session', 'tf.Session', ([], {'graph': 'loaded_graph'}), '(graph=loaded_graph)\n', (4184, 4204), True, 'import tensorflow as tf\n'), ((4258, 4304), 'tensorflow.train.import_meta_graph', 'tf.train.import_meta_graph', (["(load_dir + '.meta')"], {}), "(load_dir + '.meta')\n", (4284, 4304), True, 'import tensorflow as tf\n'), ((5052, 5077), 'numpy.squeeze', 'np.squeeze', (['probabilities'], {}), '(probabilities)\n', (5062, 5077), True, 'import numpy as np\n'), ((4604, 4619), 'numpy.array', 'np.array', (['[[1]]'], {}), '([[1]])\n', (4612, 4619), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- import numpy as np # Constructs the problem data also used in the thesis # When multiple problems of the same dimensions are used, we count up the rng seed # CQP_problem constructs CQP problem data # min 1/2x^TPx + q^Tx # s.t Ax >= b def CQP_problem(m,n): rng = np.random.default_rng(65687777) P = rng.random((n,n)) P = P.T@P+n*np.eye(n) q = rng.random(n) A = rng.random((m,n)) b = rng.random(m) return(P,q,A,b) # Lasso_problem constructs ols problem data # min 1/2||Ax-b||_2^2 def Lasso_problem(n,m): rng = np.random.default_rng(65687777) A = rng.random((m,n)) b = rng.random(m) return(A,b)
[ "numpy.random.default_rng", "numpy.eye" ]
[((318, 349), 'numpy.random.default_rng', 'np.random.default_rng', (['(65687777)'], {}), '(65687777)\n', (339, 349), True, 'import numpy as np\n'), ((621, 652), 'numpy.random.default_rng', 'np.random.default_rng', (['(65687777)'], {}), '(65687777)\n', (642, 652), True, 'import numpy as np\n'), ((398, 407), 'numpy.eye', 'np.eye', (['n'], {}), '(n)\n', (404, 407), True, 'import numpy as np\n')]
#!/usr/bin/env pythonu # -*- coding: utf-8 -*- """ Module containing Bicubic class and EfitData class for handling all interpolation related computations. """ from __future__ import division, print_function, absolute_import import numpy as np import matplotlib.pyplot as plt from scipy.ndimage import zoom def Bicubic(f, fx: 'array-like', fy: 'array-like', fxy: 'array-like', x0: float, y0: float, derivs: str = '') -> float: """ Bicubic interpolation on unit square [0,1]x[0,1]. Returns the value of the interpolated polynomial at the given interior point (x0,y0). f, fx, fy, fxy can be arrays, lists, tulpes etc. They must each have four values and are ordered: .. math:: f_{i,j}, f_{i,j+1}, f_{i+1,j}, f_{i+1,j+1}. This is the natural order produced by the locate cell method, in the EfitData.EFit_Data class, which how this function is usually called. Parameters ---------- f : array-like Contains the value of the function of each cell coordinate. fx : array-like Contains the x or R derivative fy : array-like Contains the y or Z derivative fxy : array-like Contains the cross derivative, xy or RZ x0 : float Normalized x or R coordinate of the point of interest y0 : float Normalized y or Z coordinate of the point derivs : str, optional Contains the tag for the type of derivative we want. Accepts 'v', 'vr', 'vz', 'vrz' Returns ------- The value of the function of its derivative at a given location """ # All known quantities on 4 vertices. xall = np.array([[f[0], f[2], fy[0], fy[2]], [f[1], f[3], fy[1], fy[3]], [fx[0], fx[2], fxy[0], fxy[2]], [fx[1], fx[3], fxy[1], fxy[3]]]) # use two coefficient matrices A1 = np.array([[1, 0, 0, 0], [0, 0, 1, 0], [-3, 3, -2, -1], [2, -2, 1, 1]]) A2 = np.array([[1, 0, -3, 2], [0, 0, 3, -2], [0, 1, -2, 1], [0, 0, -1, 1]]) alp = np.matmul(A1, np.matmul(xall, A2)) # build the polynomial using the relative coordinates if derivs == 'v' or derivs == '': res = np.matmul([1, x0, x0**2, x0**3], np.matmul(alp, [1, y0, y0**2, y0**3]), dtype=np.ndarray) elif derivs == 'vr': res = np.matmul([0, 1, 2 * x0, 3 * x0**2], np.matmul(alp, [1, y0, y0**2, y0**3])) elif derivs == 'vz': res = np.matmul([1, x0, x0**2, x0**3], np.matmul(alp, [0, 1, 2 * y0, 3 * y0**2])) elif derivs == 'vrz': res = np.matmul([0, 1, 2 * x0, 3 * x0**2], np.matmul(alp, [0, 1, 2 * y0, 3 * y0**2])) elif derivs == 'vrr': res = np.matmul([0, 0, 2, 6 * x0], np.matmul(alp, [1, y0, y0**2, y0**3])) elif derivs == 'vzz': res = np.matmul([1, x0, x0**2, x0**3], np.matmul(alp, [0, 0, 2, 6 * y0])) return res class EfitData: """ Structure to store the rectangular grid of psi data. It uses cylindrical coordinates, where R and Z are similar to the cartesian x and y. The phi components goes away due to the symmetry of a tokamak. Parameters ---------- rmin : float, optional left boundary of the grid rmax : float, optional right boundary nr : int, optional number of grid points in the R direction zmin : float, optional bottom boundary for the grid zmax : float, optional top boundary nz : int, optional number of grid points in the Z direction name : str, optional Specify the title of the figure the data will be plotted on. """ def __init__(self, rmin=0.0, rmax=1.0, nr=10, zmin=0.0, zmax=2.0, nz=20, rcenter=1.6955000, bcenter=-2.1094041, rlimiter=None, zlimiter=None, rmagx=0.0, zmagx=0.0, name='unnamed', parent=None): r, dr = np.linspace(rmin, rmax, nr, retstep=True) z, dz = np.linspace(zmin, zmax, nz, retstep=True) rgrid, zgrid = np.meshgrid(r, z, indexing='ij') value = np.zeros([nr, nz]) self.nr = nr self.nz = nz self.rmin = rmin self.rmax = rmax self.zmin = zmin self.zmax = zmax self.r = rgrid self.z = zgrid self.v = value self.vr = value self.vz = value self.vrz = value self.dr = dr self.dz = dz self.rcenter = rcenter self.bcenter = bcenter self.rmagx = rmagx self.zmagx = zmagx self.rlimiter = rlimiter self.zlimiter = zlimiter self.name = name self.parent = parent self.psi_levels = {} def Gradient(self, xy: tuple) -> 'np.ndarray': """ Combines the first partial derivatives to solve the system for maximum, minimum, and saddle locations. Parameters ---------- xy : array-like Contains x and y. Ex: xy = (x0, y0). Returns ------- F : array Vector function to be used in find root. """ # combine the deriv functions to solve the system x, y = xy F = np.zeros(2) F[0] = self.get_psi(x, y, tag='vr') F[1] = self.get_psi(x, y, tag='vz') return F def Hessian(self, xy: tuple) -> 'np.ndarray': """ Compute the Hessian at a point. Parameters ---------- xy : array-like Contains x and y. Ex: xy = (x0, y0). Returns ------- H : array Numpy array of shape (2, 2) representing the Hessian at xy. """ x, y = xy H = np.zeros((2, 2)) H[0, 0] = self.get_psi(x, y, 'vrr') H[1, 1] = self.get_psi(x, y, 'vzz') H[0, 1] = self.get_psi(x, y, 'vrz') H[1, 0] = self.get_psi(x, y, 'vrz') return H def PsiFunction(self, xy): x, y = xy return self.get_psi(x, y) def get_v(self, tag: str = 'v') -> 'np.ndarray': """ Returns the entire array of v, vr, vz, or vrz. If you want a single value use self.get_psi Parameters ---------- tag : str, optional Specify the type of derivative. 'v', 'vr', 'vz', 'vrz' Returns ------- ndarray value of the function or its derivative over the entire grid. """ if tag == 'v': return self.v elif tag == 'vr': return self.vr elif tag == 'vz': return self.vz elif tag == 'vrz': return self.vrz def set_v(self, value, coords=None, tag='v'): """ sets a value for v, vr, vz, or vrz. Parameters ---------- value : ndarray, float new set of values for the function. Must be the same shape as the grid if you are setting every value. Also accepts a single float for setting spevific values. coords : array-like, optional The coordinates of a single value, if you are setting one value. if set to none, it will set the entire value """ if coords is not None: if tag == 'v': self.v[coords[0], coords[1]] = value elif tag == 'vr': self.vr[coords[0], coords[1]] = value elif tag == 'vz': self.vz[coords[0], coords[1]] = value elif tag == 'vrz': self.vrz[coords[0], coords[1]] = value else: if tag == 'v': self.v = value elif tag == 'vr': self.vr = value elif tag == 'vz': self.vz = value elif tag == 'vrz': self.vrz = value def Calculate_PDeriv(self, unit_spacing=True): """ Calculate partial derivatives at grid nodes. Use finite differences to increase accuracy at the boundaries. These formulas are derived from Taylor Series representations. Values for vr, vz, and vrz are produced and saved within the grid structure. Parameters ---------- unit_spacing : bool, optional Allow for the derivatives to be calculated on a unit cell, or on a grid with any other spacing. Default is true. """ # planning to make this more efficient using array slicing # need a place to store the new values of the grid from time import time print("Beginning Derivative calculation") start = time() f = self.v vr = np.zeros_like(self.vr) vz = np.zeros_like(self.vz) vrz = np.zeros_like(self.vrz) nr = self.nr nz = self.nz # step size becomes one because of the unit grid if unit_spacing: dr = 1 dz = 1 else: dr = self.dr dz = self.dz # inner square - can use centered difference for i in range(1, self.nr - 1): for j in range(1, self.nz - 1): vr[i, j] = (self.v[i + 1, j] - self.v[i - 1, j]) / 2 / dr vz[i, j] = (self.v[i, j + 1] - self.v[i, j - 1]) / 2 / dz vrz[i, j] = (self.v[i + 1, j + 1] + self.v[i - 1, j - 1] - self.v[i - 1, j + 1] - self.v[i + 1, j - 1]) / 4 / dr / dz # missed a row in x for i in range(1, self.nr - 1): for j in [0, self.nz - 1]: vr[i, j] = (self.v[i + 1, j] - self.v[i - 1, j]) / 2 / dr # and in y for i in [0, self.nr - 1]: for j in range(1, self.nz - 1): vz[i, j] = (self.v[i, j + 1] - self.v[i, j - 1]) / 2 / dz # forward difference accuracy h^2 for j in range(self.nz): vr[0, j] = (4 * self.v[1, j] - self.v[2, j] - 3 * self.v[0, j]) / 2 / dr vr[-1, j] = -(4 * self.v[-2, j] - self.v[-3, j] - 3 * self.v[-1, j]) / 2 / dr for i in range(self.nr): vz[i, 0] = (4 * self.v[i, 1] - self.v[i, 2] - 3 * self.v[i, 0]) / 2 / dz vz[i, -1] = -(4 * self.v[i, -2] - self.v[i, -3] - 3 * self.v[i, -1]) / 2 / dz # cross derivative on the edges for j in range(2, nz - 2): i = 0 # left Edge vrz[i, j] = (f[i + 2, j + 2] - 2 * f[i + 1, j + 1] + 2 * f[i + 1, j - 1] - f[i + 2, j - 2]) / 4 / dr / dz i = nr - 1 # right edge vrz[i, j] = (f[i - 2, j + 2] - 2 * f[i - 2, j + 1] + 2 * f[i - 1, j - 1] - f[i - 2, j - 2]) / 4 / dr / dz for i in range(2, nr - 2): j = 0 # bottom edge vrz[i, j] = (f[i - 1, j + 2] - 2 * f[i - 1, j + 1] + 2 * f[i + 1, j + 1] - f[i + 2, j + 2]) / 4 / dr / dz j = nz - 1 # top edge vrz[i, j] = (f[i - 1, j - 2] - 2 * f[i - 1, j - 1] + 2 * f[i + 1, j - 1] - f[i + 2, j - 2]) / 4 / dr / dz # cross derivatives at the corners for i, j in [[0, 0], [0, 1], [1, 0]]: # bottom left vrz[i, j] = (f[i, j] - f[i + 1, j] + f[i + 1, j + 1] - f[i, j + 1]) / dr / dz for i, j in [[nr - 2, 0], [nr - 1, 0], [nr - 1, 1]]: # bottom right vrz[i, j] = - (f[i, j] - f[i, j + 1] + f[i - 1, j + 1] - f[i - 1, j]) / dr / dz for i, j in [[0, nz - 2], [0, nz - 1], [1, nz - 1]]: # top left vrz[i, j] = - (f[i, j] - f[i, j - 1] + f[i + 1, j - 1] - f[i + 1, j]) / dr / dz for i, j in [[nr - 2, nz - 1], [nr - 1, nr - 1], [nr - 1, nz - 2]]: # top right vrz[i, j] = (f[i, j] - f[i - 1, j] + f[i - 1, j - 1] - f[i, j - 1]) / dr / dz # reload the new derivative values self.vr = vr self.vz = vz self.vrz = vrz end = time() print("Time calculating derivatives", end - start) def locate_cell(self, r0: float, z0: float) -> dict: """ Locate the cell on the rectangular grid that surrounds a point of interest. Parameters ---------- r0 : float R or x coordinate of the point z0 : float Z or y coordinate of the tested point Returns ------- A dict with node indices of grid cell encompassing tested point """ # indices of lower left vertex of the cell # (and make sure they are within [0,nr-1]) ir = int(max([min([np.floor((r0 - self.rmin) / self.dr), self.nr - 2]), 0])) iz = int(max([min([np.floor((z0 - self.zmin) / self.dz), self.nz - 2]), 0])) ircell = [ir, ir + 1, ir, ir + 1] izcell = [iz, iz, iz + 1, iz + 1] return {'ir': ircell, 'iz': izcell} def get_psi(self, r0, z0, tag='v'): """ find grid cell encompassing (r0,z0) note: grid is the crude grid. Uses Bicubic Interpolation to calculate the exact value at the point. Useful for finding information inbetween grid points. Parameters ---------- r0 : float R coordinate of the point of interest z0 : float Z coordinate of same point. tag : str, optional tag is the type of derivative we want: v, vr, vz, vrz if nothing is provided, it assumes no derivative (v). Returns ------- float Value of psi or its derviative at the coordinate specified. """ cell = self.locate_cell(r0, z0) rcell = self.r[cell['ir'], cell['iz']] zcell = self.z[cell['ir'], cell['iz']] fcell = self.v[cell['ir'], cell['iz']] frcell = self.vr[cell['ir'], cell['iz']] fzcell = self.vz[cell['ir'], cell['iz']] frzcell = self.vrz[cell['ir'], cell['iz']] # ==BICUBIC INTERPOLATION== # NOTE: assumes unit cell r0norm = (r0 - rcell[0]) / self.dr z0norm = (z0 - zcell[0]) / self.dz res = Bicubic(fcell, frcell, fzcell, frzcell, x0=r0norm, y0=z0norm, derivs=tag) if tag == 'vr': res /= self.dr elif tag == 'vz': res /= self.dz elif tag == 'vrz': res /= self.dr * self.dz elif tag == 'vrr': res /= self.dr * self.dr elif tag == 'vzz': res /= self.dz * self.dz return res def plot_levels(self, level=1.0, color='red'): """ This function is useful if you need to quickly see where a particular line of constant psi is. It in't able to store points of intersection, and cannot be generalized. If you need just a segment of psi, use the draw_lines method in the line tracing class. Parameters ---------- level : float, optional Value of psi you wish to see color : str, optional color of the line. """ # draw contour line on top of existing figure level = float(level) self.ax.contour(self.r, self.z, self.v, level, colors=color) def PlotLevel(self: object, level: float = 1.0, color: str = 'red', label: str = '', linestyles: str = 'solid', refined: bool = True, refine_factor: int = 10) -> None: """ Plot a psi level and provide it a label. This function is useful for management of psi boundaries such as 'psi_pf', 'psi_core', etc and ensuring the contour will be properly replotted (no duplicate of same label). Parameters ---------- level : float, optional Psi level to plot. Default to 1.0 (separatrix of normalized psi) color : str, optional Color to pass to matplotlib contour function label : str, optional Label to associate with the psi level linestyles : str, optional Line style to pass to matplotlib contour function refined : bool, optional Plot level with hi-resolution cubic spline representation refine_factor: int, optional Refinement factor for to be passed to SciPy zoom method """ data = self.v rgrid = self.r zgrid = self.z if refined is True: data = zoom(input=self.v, zoom=refine_factor) rgrid, zgrid = np.meshgrid(np.linspace(self.rmin, self.rmax, data.shape[0]), np.linspace(self.zmin, self.zmax, data.shape[1]), indexing='ij') try: self.psi_levels[label].collections[0].remove() self.psi_levels[label] = plt.contour(rgrid, zgrid, data, [float(level)], colors=color, label=label, linestyles=linestyles) self.psi_levels[label].collections[0].set_label(label) except: self.psi_levels[label] = plt.contour(rgrid, zgrid, data, [float(level)], colors=color, label=label, linestyles=linestyles) self.psi_levels[label].collections[0].set_label(label) def plot_data(self: object, nlevs: int = 30, interactive: bool = True, fig: object = None, ax: object = None, view_mode: str = 'filled', refined: bool = True, refine_factor: int = 10): """ generates the plot that we will be able to manipulate using the root finder Parameters ---------- nlev : int, optional number of levels we want to be plotted interactive : bool, optional Set matplotlib interactive mode on or off fig : object, optional Matplotlib figure handle ax : object, optional Matplotlib axes handle view_mode : str, optional Represent EFIT data with standard contour lines or filled contour lines. String value of ``filled" enables filled contours, whereas ``lines" omits filling of contours. refined : bool, optional Plot level with hi-resolution cubic spline representation refine_factor: int, optional Refinement factor for to be passed to SciPy zoom method """ lev = self.v.min() + (self.v.max() - self.v.min()) * np.arange(nlevs) / (nlevs - 1) self.fig = fig if fig is not None else plt.figure('INGRID: ' + self.name, figsize=(8, 10)) self.fig.subplots_adjust(bottom=0.075) self.ax = ax if ax is not None else self.fig.add_subplot(111) data = self.v rgrid = self.r zgrid = self.z if refined is True: data = zoom(input=self.v, zoom=refine_factor) rgrid, zgrid = np.meshgrid(np.linspace(self.rmin, self.rmax, data.shape[0]), np.linspace(self.zmin, self.zmax, data.shape[1]), indexing='ij') if view_mode == 'lines': self.ax.contour(rgrid, zgrid, data, lev, cmap='gist_gray') elif view_mode == 'filled': self.ax.contourf(rgrid, zgrid, data, lev, cmap='gist_gray') self.ax.set_aspect('equal', adjustable='box') #self.ax.set_title(f'{self.name}') self.ax.set_xlabel('R') self.ax.set_ylabel('Z') self.ax.set_xlim(self.rmin, self.rmax) self.ax.set_ylim(self.zmin, self.zmax) if interactive: plt.ion() self.fig.show() def clear_plot(self): if plt.get_fignums(): plt.clf() else: pass
[ "numpy.meshgrid", "numpy.zeros_like", "matplotlib.pyplot.clf", "numpy.floor", "numpy.zeros", "scipy.ndimage.zoom", "time.time", "matplotlib.pyplot.ion", "matplotlib.pyplot.figure", "numpy.array", "numpy.arange", "numpy.linspace", "numpy.matmul", "matplotlib.pyplot.get_fignums" ]
[((1638, 1772), 'numpy.array', 'np.array', (['[[f[0], f[2], fy[0], fy[2]], [f[1], f[3], fy[1], fy[3]], [fx[0], fx[2], fxy\n [0], fxy[2]], [fx[1], fx[3], fxy[1], fxy[3]]]'], {}), '([[f[0], f[2], fy[0], fy[2]], [f[1], f[3], fy[1], fy[3]], [fx[0],\n fx[2], fxy[0], fxy[2]], [fx[1], fx[3], fxy[1], fxy[3]]])\n', (1646, 1772), True, 'import numpy as np\n'), ((1877, 1947), 'numpy.array', 'np.array', (['[[1, 0, 0, 0], [0, 0, 1, 0], [-3, 3, -2, -1], [2, -2, 1, 1]]'], {}), '([[1, 0, 0, 0], [0, 0, 1, 0], [-3, 3, -2, -1], [2, -2, 1, 1]])\n', (1885, 1947), True, 'import numpy as np\n'), ((2015, 2085), 'numpy.array', 'np.array', (['[[1, 0, -3, 2], [0, 0, 3, -2], [0, 1, -2, 1], [0, 0, -1, 1]]'], {}), '([[1, 0, -3, 2], [0, 0, 3, -2], [0, 1, -2, 1], [0, 0, -1, 1]])\n', (2023, 2085), True, 'import numpy as np\n'), ((2168, 2187), 'numpy.matmul', 'np.matmul', (['xall', 'A2'], {}), '(xall, A2)\n', (2177, 2187), True, 'import numpy as np\n'), ((3976, 4017), 'numpy.linspace', 'np.linspace', (['rmin', 'rmax', 'nr'], {'retstep': '(True)'}), '(rmin, rmax, nr, retstep=True)\n', (3987, 4017), True, 'import numpy as np\n'), ((4034, 4075), 'numpy.linspace', 'np.linspace', (['zmin', 'zmax', 'nz'], {'retstep': '(True)'}), '(zmin, zmax, nz, retstep=True)\n', (4045, 4075), True, 'import numpy as np\n'), ((4099, 4131), 'numpy.meshgrid', 'np.meshgrid', (['r', 'z'], {'indexing': '"""ij"""'}), "(r, z, indexing='ij')\n", (4110, 4131), True, 'import numpy as np\n'), ((4148, 4166), 'numpy.zeros', 'np.zeros', (['[nr, nz]'], {}), '([nr, nz])\n', (4156, 4166), True, 'import numpy as np\n'), ((5250, 5261), 'numpy.zeros', 'np.zeros', (['(2)'], {}), '(2)\n', (5258, 5261), True, 'import numpy as np\n'), ((5739, 5755), 'numpy.zeros', 'np.zeros', (['(2, 2)'], {}), '((2, 2))\n', (5747, 5755), True, 'import numpy as np\n'), ((8666, 8672), 'time.time', 'time', ([], {}), '()\n', (8670, 8672), False, 'from time import time\n'), ((8707, 8729), 'numpy.zeros_like', 'np.zeros_like', (['self.vr'], {}), '(self.vr)\n', (8720, 8729), True, 'import numpy as np\n'), ((8743, 8765), 'numpy.zeros_like', 'np.zeros_like', (['self.vz'], {}), '(self.vz)\n', (8756, 8765), True, 'import numpy as np\n'), ((8780, 8803), 'numpy.zeros_like', 'np.zeros_like', (['self.vrz'], {}), '(self.vrz)\n', (8793, 8803), True, 'import numpy as np\n'), ((12095, 12101), 'time.time', 'time', ([], {}), '()\n', (12099, 12101), False, 'from time import time\n'), ((19745, 19762), 'matplotlib.pyplot.get_fignums', 'plt.get_fignums', ([], {}), '()\n', (19760, 19762), True, 'import matplotlib.pyplot as plt\n'), ((2333, 2374), 'numpy.matmul', 'np.matmul', (['alp', '[1, y0, y0 ** 2, y0 ** 3]'], {}), '(alp, [1, y0, y0 ** 2, y0 ** 3])\n', (2342, 2374), True, 'import numpy as np\n'), ((16606, 16644), 'scipy.ndimage.zoom', 'zoom', ([], {'input': 'self.v', 'zoom': 'refine_factor'}), '(input=self.v, zoom=refine_factor)\n', (16610, 16644), False, 'from scipy.ndimage import zoom\n'), ((18613, 18664), 'matplotlib.pyplot.figure', 'plt.figure', (["('INGRID: ' + self.name)"], {'figsize': '(8, 10)'}), "('INGRID: ' + self.name, figsize=(8, 10))\n", (18623, 18664), True, 'import matplotlib.pyplot as plt\n'), ((18899, 18937), 'scipy.ndimage.zoom', 'zoom', ([], {'input': 'self.v', 'zoom': 'refine_factor'}), '(input=self.v, zoom=refine_factor)\n', (18903, 18937), False, 'from scipy.ndimage import zoom\n'), ((19673, 19682), 'matplotlib.pyplot.ion', 'plt.ion', ([], {}), '()\n', (19680, 19682), True, 'import matplotlib.pyplot as plt\n'), ((19776, 19785), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (19783, 19785), True, 'import matplotlib.pyplot as plt\n'), ((2467, 2508), 'numpy.matmul', 'np.matmul', (['alp', '[1, y0, y0 ** 2, y0 ** 3]'], {}), '(alp, [1, y0, y0 ** 2, y0 ** 3])\n', (2476, 2508), True, 'import numpy as np\n'), ((16684, 16732), 'numpy.linspace', 'np.linspace', (['self.rmin', 'self.rmax', 'data.shape[0]'], {}), '(self.rmin, self.rmax, data.shape[0])\n', (16695, 16732), True, 'import numpy as np\n'), ((16773, 16821), 'numpy.linspace', 'np.linspace', (['self.zmin', 'self.zmax', 'data.shape[1]'], {}), '(self.zmin, self.zmax, data.shape[1])\n', (16784, 16821), True, 'import numpy as np\n'), ((18977, 19025), 'numpy.linspace', 'np.linspace', (['self.rmin', 'self.rmax', 'data.shape[0]'], {}), '(self.rmin, self.rmax, data.shape[0])\n', (18988, 19025), True, 'import numpy as np\n'), ((19066, 19114), 'numpy.linspace', 'np.linspace', (['self.zmin', 'self.zmax', 'data.shape[1]'], {}), '(self.zmin, self.zmax, data.shape[1])\n', (19077, 19114), True, 'import numpy as np\n'), ((2579, 2622), 'numpy.matmul', 'np.matmul', (['alp', '[0, 1, 2 * y0, 3 * y0 ** 2]'], {}), '(alp, [0, 1, 2 * y0, 3 * y0 ** 2])\n', (2588, 2622), True, 'import numpy as np\n'), ((18535, 18551), 'numpy.arange', 'np.arange', (['nlevs'], {}), '(nlevs)\n', (18544, 18551), True, 'import numpy as np\n'), ((2700, 2743), 'numpy.matmul', 'np.matmul', (['alp', '[0, 1, 2 * y0, 3 * y0 ** 2]'], {}), '(alp, [0, 1, 2 * y0, 3 * y0 ** 2])\n', (2709, 2743), True, 'import numpy as np\n'), ((2813, 2854), 'numpy.matmul', 'np.matmul', (['alp', '[1, y0, y0 ** 2, y0 ** 3]'], {}), '(alp, [1, y0, y0 ** 2, y0 ** 3])\n', (2822, 2854), True, 'import numpy as np\n'), ((12743, 12779), 'numpy.floor', 'np.floor', (['((r0 - self.rmin) / self.dr)'], {}), '((r0 - self.rmin) / self.dr)\n', (12751, 12779), True, 'import numpy as np\n'), ((12855, 12891), 'numpy.floor', 'np.floor', (['((z0 - self.zmin) / self.dz)'], {}), '((z0 - self.zmin) / self.dz)\n', (12863, 12891), True, 'import numpy as np\n'), ((2926, 2959), 'numpy.matmul', 'np.matmul', (['alp', '[0, 0, 2, 6 * y0]'], {}), '(alp, [0, 0, 2, 6 * y0])\n', (2935, 2959), True, 'import numpy as np\n')]
import matplotlib.pyplot as plt from matplotlib import style import numpy as np import pandas as pd import seaborn as sns import gym import numpy import math import os import random import cntk as C isFast = True C.device.try_set_default_device(C.device.gpu(0)) env = gym.make('CartPole-v0') STATE_COUNT = env.observation_space.shape[0] ACTION_COUNT = env.action_space.n print("State count", STATE_COUNT, "action count", ACTION_COUNT) # Targetted reward REWARD_TARGET = 30 if isFast else 200 # Averaged over these these many episodes BATCH_SIZE_BASELINE = 20 if isFast else 50 H = 64 # hidden layer size class Brain: def __init__(self): self.params = {} self.model, self.trainer, self.loss = self._create() # self.model.load_weights("cartpole-basic.h5") def _create(self): observation = C.sequence.input_variable(STATE_COUNT, np.float32, name="s") q_target = C.sequence.input_variable(ACTION_COUNT, np.float32, name="q") # Following a style similar to Keras l1 = C.layers.Dense(H, activation=C.relu) l2 = C.layers.Dense(ACTION_COUNT) unbound_model = C.layers.Sequential([l1, l2]) model = unbound_model(observation) self.params = dict(W1=l1.W, b1=l1.b, W2=l2.W, b2=l2.b) # loss='mse' loss = C.reduce_mean(C.square(model - q_target), axis=0) meas = C.reduce_mean(C.square(model - q_target), axis=0) # optimizer lr = 0.00025 lr_schedule = C.learning_parameter_schedule(lr) learner = C.sgd(model.parameters, lr_schedule, gradient_clipping_threshold_per_sample=10) trainer = C.Trainer(model, (loss, meas), learner) # CNTK: return trainer and loss as well return model, trainer, loss def train(self, x, y, epoch=1, verbose=0): #self.model.fit(x, y, batch_size=64, nb_epoch=epoch, verbose=verbose) arguments = dict(zip(self.loss.arguments, [x,y])) updated, results =self.trainer.train_minibatch(arguments, outputs=[self.loss.output]) def predict(self, s): return self.model.eval([s]) class Memory: # stored as ( s, a, r, s_ ) samples = [] def __init__(self, capacity): self.capacity = capacity def add(self, sample): self.samples.append(sample) if len(self.samples) > self.capacity: self.samples.pop(0) def sample(self, n): n = min(n, len(self.samples)) return random.sample(self.samples, n) MEMORY_CAPACITY = 100000 BATCH_SIZE = 64 GAMMA = 0.99 # discount factor MAX_EPSILON = 1 MIN_EPSILON = 0.01 # stay a bit curious even when getting old LAMBDA = 0.0001 # speed of decay class Agent: steps = 0 epsilon = MAX_EPSILON def __init__(self): self.brain = Brain() self.memory = Memory(MEMORY_CAPACITY) def act(self, s): if random.random() < self.epsilon: return random.randint(0, ACTION_COUNT-1) else: return numpy.argmax(self.brain.predict(s)) def observe(self, sample): # in (s, a, r, s_) format self.memory.add(sample) # slowly decrease Epsilon based on our eperience self.steps += 1 self.epsilon = MIN_EPSILON + (MAX_EPSILON - MIN_EPSILON) * math.exp(-LAMBDA * self.steps) def replay(self): batch = self.memory.sample(BATCH_SIZE) batchLen = len(batch) no_state = numpy.zeros(STATE_COUNT) # CNTK: explicitly setting to float32 states = numpy.array([ o[0] for o in batch ], dtype=np.float32) states_ = numpy.array([(no_state if o[3] is None else o[3]) for o in batch ], dtype=np.float32) print('AAA states', states) print('AAA states_', states_) p = self.brain.predict(states) print('AAA p is', p) p_ = self.brain.predict(states_) print('AAA p_ is', p_) # CNTK: explicitly setting to float32 x = numpy.zeros((batchLen, STATE_COUNT)).astype(np.float32) y = numpy.zeros((batchLen, ACTION_COUNT)).astype(np.float32) for i in range(batchLen): s, a, r, s_ = batch[i] # CNTK: [0] because of sequence dimension t = p[0][i] if s_ is None: t[a] = r else: t[a] = r + GAMMA * numpy.amax(p_[0][i]) print('AAA t', t) x[i] = s y[i] = t self.brain.train(x, y) def plot_weights(weights, figsize=(7, 5)): '''Heat map of weights to see which neurons play which role''' sns.set(style="white") f, ax = plt.subplots(len(weights), figsize=figsize) cmap = sns.diverging_palette(220, 10, as_cmap=True) for i, data in enumerate(weights): axi = ax if len(weights) == 1 else ax[i] if isinstance(data, tuple): w, title = data axi.set_title(title) else: w = data sns.heatmap(w.asarray(), cmap=cmap, square=True, center=True, # annot=True, linewidths=.5, cbar_kws={"shrink": .25}, ax=axi) def epsilon(steps): return MIN_EPSILON + (MAX_EPSILON - MIN_EPSILON) * np.exp(-LAMBDA * steps) plt.plot(range(10000), [epsilon(x) for x in range(10000)], 'r') plt.xlabel('step');plt.ylabel('$\epsilon$') TOTAL_EPISODES = 2000 if isFast else 3000 def run(agent): s = env.reset() R = 0 while True: # Uncomment the line below to visualize the cartpole # env.render() # CNTK: explicitly setting to float32 a = agent.act(s.astype(np.float32)) s_, r, done, info = env.step(a) if done: # terminal state s_ = None agent.observe((s, a, r, s_)) agent.replay() s = s_ R += r if done: return R agent = Agent() episode_number = 0 reward_sum = 0 while episode_number < TOTAL_EPISODES: reward_sum += run(agent) episode_number += 1 if episode_number % BATCH_SIZE_BASELINE == 0: print('Episode: %d, Average reward for episode %f.' % (episode_number, reward_sum / BATCH_SIZE_BASELINE)) if episode_number%200==0: plot_weights([(agent.brain.params['W1'], 'Episode %i $W_1$'%episode_number)], figsize=(14,5)) if reward_sum / BATCH_SIZE_BASELINE > REWARD_TARGET: print('Task solved in %d episodes' % episode_number) plot_weights([(agent.brain.params['W1'], 'Episode %i $W_1$'%episode_number)], figsize=(14,5)) break reward_sum = 0 agent.brain.model.save('dqn.mod')
[ "cntk.learning_parameter_schedule", "cntk.sgd", "random.sample", "numpy.exp", "cntk.layers.Sequential", "cntk.layers.Dense", "random.randint", "cntk.sequence.input_variable", "cntk.square", "seaborn.set", "random.random", "cntk.Trainer", "matplotlib.pyplot.ylabel", "cntk.device.gpu", "ma...
[((291, 314), 'gym.make', 'gym.make', (['"""CartPole-v0"""'], {}), "('CartPole-v0')\n", (299, 314), False, 'import gym\n'), ((5418, 5436), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""step"""'], {}), "('step')\n", (5428, 5436), True, 'import matplotlib.pyplot as plt\n'), ((5437, 5462), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""$\\\\epsilon$"""'], {}), "('$\\\\epsilon$')\n", (5447, 5462), True, 'import matplotlib.pyplot as plt\n'), ((263, 278), 'cntk.device.gpu', 'C.device.gpu', (['(0)'], {}), '(0)\n', (275, 278), True, 'import cntk as C\n'), ((4723, 4745), 'seaborn.set', 'sns.set', ([], {'style': '"""white"""'}), "(style='white')\n", (4730, 4745), True, 'import seaborn as sns\n'), ((4815, 4859), 'seaborn.diverging_palette', 'sns.diverging_palette', (['(220)', '(10)'], {'as_cmap': '(True)'}), '(220, 10, as_cmap=True)\n', (4836, 4859), True, 'import seaborn as sns\n'), ((878, 938), 'cntk.sequence.input_variable', 'C.sequence.input_variable', (['STATE_COUNT', 'np.float32'], {'name': '"""s"""'}), "(STATE_COUNT, np.float32, name='s')\n", (903, 938), True, 'import cntk as C\n'), ((959, 1020), 'cntk.sequence.input_variable', 'C.sequence.input_variable', (['ACTION_COUNT', 'np.float32'], {'name': '"""q"""'}), "(ACTION_COUNT, np.float32, name='q')\n", (984, 1020), True, 'import cntk as C\n'), ((1083, 1119), 'cntk.layers.Dense', 'C.layers.Dense', (['H'], {'activation': 'C.relu'}), '(H, activation=C.relu)\n', (1097, 1119), True, 'import cntk as C\n'), ((1134, 1162), 'cntk.layers.Dense', 'C.layers.Dense', (['ACTION_COUNT'], {}), '(ACTION_COUNT)\n', (1148, 1162), True, 'import cntk as C\n'), ((1188, 1217), 'cntk.layers.Sequential', 'C.layers.Sequential', (['[l1, l2]'], {}), '([l1, l2])\n', (1207, 1217), True, 'import cntk as C\n'), ((1552, 1585), 'cntk.learning_parameter_schedule', 'C.learning_parameter_schedule', (['lr'], {}), '(lr)\n', (1581, 1585), True, 'import cntk as C\n'), ((1605, 1684), 'cntk.sgd', 'C.sgd', (['model.parameters', 'lr_schedule'], {'gradient_clipping_threshold_per_sample': '(10)'}), '(model.parameters, lr_schedule, gradient_clipping_threshold_per_sample=10)\n', (1610, 1684), True, 'import cntk as C\n'), ((1704, 1743), 'cntk.Trainer', 'C.Trainer', (['model', '(loss, meas)', 'learner'], {}), '(model, (loss, meas), learner)\n', (1713, 1743), True, 'import cntk as C\n'), ((2551, 2581), 'random.sample', 'random.sample', (['self.samples', 'n'], {}), '(self.samples, n)\n', (2564, 2581), False, 'import random\n'), ((3542, 3566), 'numpy.zeros', 'numpy.zeros', (['STATE_COUNT'], {}), '(STATE_COUNT)\n', (3553, 3566), False, 'import numpy\n'), ((3636, 3688), 'numpy.array', 'numpy.array', (['[o[0] for o in batch]'], {'dtype': 'np.float32'}), '([o[0] for o in batch], dtype=np.float32)\n', (3647, 3688), False, 'import numpy\n'), ((3710, 3799), 'numpy.array', 'numpy.array', (['[(no_state if o[3] is None else o[3]) for o in batch]'], {'dtype': 'np.float32'}), '([(no_state if o[3] is None else o[3]) for o in batch], dtype=np\n .float32)\n', (3721, 3799), False, 'import numpy\n'), ((1382, 1408), 'cntk.square', 'C.square', (['(model - q_target)'], {}), '(model - q_target)\n', (1390, 1408), True, 'import cntk as C\n'), ((1448, 1474), 'cntk.square', 'C.square', (['(model - q_target)'], {}), '(model - q_target)\n', (1456, 1474), True, 'import cntk as C\n'), ((2981, 2996), 'random.random', 'random.random', ([], {}), '()\n', (2994, 2996), False, 'import random\n'), ((3033, 3068), 'random.randint', 'random.randint', (['(0)', '(ACTION_COUNT - 1)'], {}), '(0, ACTION_COUNT - 1)\n', (3047, 3068), False, 'import random\n'), ((5326, 5349), 'numpy.exp', 'np.exp', (['(-LAMBDA * steps)'], {}), '(-LAMBDA * steps)\n', (5332, 5349), True, 'import numpy as np\n'), ((3385, 3415), 'math.exp', 'math.exp', (['(-LAMBDA * self.steps)'], {}), '(-LAMBDA * self.steps)\n', (3393, 3415), False, 'import math\n'), ((4080, 4116), 'numpy.zeros', 'numpy.zeros', (['(batchLen, STATE_COUNT)'], {}), '((batchLen, STATE_COUNT))\n', (4091, 4116), False, 'import numpy\n'), ((4149, 4186), 'numpy.zeros', 'numpy.zeros', (['(batchLen, ACTION_COUNT)'], {}), '((batchLen, ACTION_COUNT))\n', (4160, 4186), False, 'import numpy\n'), ((4470, 4490), 'numpy.amax', 'numpy.amax', (['p_[0][i]'], {}), '(p_[0][i])\n', (4480, 4490), False, 'import numpy\n')]
from collections import Counter import datetime import logging import time import attr import numba import numpy as np import dask.array as da import UVDesc from katacomb import AIPSPath, normalise_target_name from katacomb.util import fmt_bytes from katdal.lazy_indexer import DaskLazyIndexer, dask_getitem log = logging.getLogger('katacomb') ONE_DAY_IN_SECONDS = 24*60*60.0 MAX_AIPS_PATH_LEN = 12 LIGHTSPEED = 299792458.0 """ Map correlation characters to correlation id """ CORR_ID_MAP = {('h', 'h'): 0, ('v', 'v'): 1, ('h', 'v'): 2, ('v', 'h'): 3} def aips_timestamps(timestamps, midnight): """ Given katdal timestamps and midnight on the observation date in UTC, calculates the Julian Day offset from midnight on the observation date. Parameters ---------- timestamps : np.ndarray katdal UTC timestamps midnight : float midnight on day of observation in UTC Returns ------- np.ndarray AIPS Julian Day timestamps, offset from midnight on the observation date. """ return (timestamps - midnight) / ONE_DAY_IN_SECONDS def katdal_timestamps(timestamps, midnight): """ Given AIPS Julian day timestamps offset from midnight on the day of the observation, calculates the katdal UTC timestamp Parameters ---------- timestamsp : np.ndarray AIPS Julian Day timestamps, offset from midnight on the observation date. midnight : float midnight on day of observation in UTC Returns ------- np.ndarray katdal UTC timestamps """ return midnight + (timestamps * ONE_DAY_IN_SECONDS) def katdal_ant_nr(ant_name): """Get a unique integer corresponding to an antenna name. Given an antenna name of the form either 'mnnnp' or 'snnnnp' where 'm' or 's' is a character constant denoting 'MeerKAT' and 'SKA' dishes respectively, 'nnn' (or 'nnnn') is the antenna number and 'p' is the (optional) polarisation, returns an ordered antenna number as an integer. The ordered antenna number is defined as 'nnn' for MeerKAT dishes and 'nnnn + 64' for SKA dishes. Parameters ---------- ant_name : str Antenna Name Returns ------ integer antenna number in antenna name """ try: if ant_name[0] == 'm': nr = int(ant_name[1:4]) elif ant_name[0] == 's': nr = int(ant_name[1:5]) + 64 else: raise ValueError except (ValueError, IndexError): raise ValueError("Invalid antenna name '%s'" % ant_name) return nr def aips_ant_nr(ant_name): """Given antenna name get its AIPS antenna number. This is done by adding one to the result of :func:`katdal_ant_nr`. Parameters ---------- ant_name : str Antenna Name Returns ------ integer AIPS antenna number from antenna name """ return katdal_ant_nr(ant_name) + 1 def katdal_ant_name(aips_ant_nr): """Return antenna name, given the AIPS antenna number""" if aips_ant_nr < 65: res = f'm{(aips_ant_nr-1):03d}' else: res = f's{(aips_ant_nr-65):04d}' return res def aips_uvw(uvw, refwave): """ Converts katdal UVW coordinates in metres to AIPS UVW coordinates in wavelengths *at the reference frequency*. Notes ----- Wavelengths at the reference frequency differs from AIPS documentation (AIPS Memo 117, Going AIPS, Obitdoc) which state that UVW coordinates should be in lightseconds. Parameters ---------- uvw : np.ndarray katdal UVW coordinates in metres refwave : float Reference wavelength in metres Returns ------- np.ndarray AIPS UVW coordinates in wavelengths at the reference frequency """ return uvw / refwave def katdal_uvw(uvw, refwave): """ Converts AIPS UVW coordinates in wavelengths *at the reference frequency* to katdal UVW coordinates in metres. Set :function:`aips_uvw` for further discussion. Parameters ---------- uvw : np.ndarray AIPS UVW coordinates in wavelengths at the reference frequency refwave : float Reference wavelength in metres Returns ------- np.ndarray katdal UVW coordinates, in metres """ return refwave * uvw def aips_source_name(name, used=[]): """ Truncates to MAX_AIPS_PATH_LEN, padding with spaces and appending repeat number to repeat names. """ return normalise_target_name(name, used, max_length=MAX_AIPS_PATH_LEN) def aips_catalogue(katdata, nif): """ Creates a catalogue of AIPS sources from :attribute:`katdata.catalogue` It resembles :attribute:`katdal.Dataset.catalogue`. Returns a list of dictionaries following the specification of the AIPS SU table in AIPS Memo 117. Notes ----- At present, the following is set for each source: 1. AIPS Source ID 2. Source name 3. Source position Other quantities such as: 1. Flux 2. Frequency Offset 3. Rest Frequency 4. Bandwidth are defaulted to zero for now as these are not strictly required for the purposes of the continuum pipeline. See Bill Cotton's description of parameter and why it is unnecessary above each row entry in the code. Relevant keys ('[IQUV]FLUX', 'LSRVEL', 'FREQOFF', 'RESTREQ') are repeated `nif` times to allow equal subdivision of the band into IFs. Parameters ---------- katdata : :class:`katdal.Dataset` katdal object nif : int Number of IFs to split band into Returns ------- list of dicts List of dictionaries where each dictionary defines an AIPS source. """ catalogue = [] zero = np.asarray([0.0, 0.0]) used = [] for aips_i, t in enumerate(katdata.catalogue.targets, 1): # Nothings have no position! if "Nothing" == t.name: radec = zero aradec = zero else: radec = t.radec() aradec = t.apparent_radec() # Right Ascension and Declination ra, dec = np.rad2deg(radec) # Apparent position raa, deca = np.rad2deg(aradec) source_name = aips_source_name(t.name, used) aips_source_data = { # Fill in data derived from katpoint target 'ID. NO.': [aips_i], # SOURCE keyword requires 16 characters. 'SOURCE': [source_name.ljust(16, ' ')], 'RAEPO': [ra], 'DECEPO': [dec], 'RAOBS': [raa], 'DECOBS': [deca], 'RAAPP': [raa], 'DECAPP': [deca], 'EPOCH': [2000.0], # NOTE(bcotton) # CALCODE - is used to distinguish type and usage of calibrator # source and is used to carry intent from the scheduling process, # e.g. this is a bandpass calibrator. # Since this data will likely never be used to derive the # external calibration, it is unlikely to ever be used. 'CALCODE': [' ' * 4], # 4 spaces for calibrator code # Following seven key-values technically vary by # spectral window, but we're only handling one SPW # at a time so it doesn't matter # NOTE(bcotton) # I/Q/U/VFLUX are the flux densities, per spectral window, # either determined from a standard model or derived in the # calibration process from a standard calibrator. # Since this data will likely never be used to derive the # external calibration, they are unlikely to ever be used. 'IFLUX': [0.0] * nif, 'QFLUX': [0.0] * nif, 'VFLUX': [0.0] * nif, 'UFLUX': [0.0] * nif, # NOTE(bcotton) # LSRVEL, FREQOFF,RESTFREQ are used in making Doppler corrections # for the Earth's motion. Since MeerKAT data can, in principle # include both HI and OH lines (separate spectral windows?) # the usage may be complicated. Look at the documentation for # either Obit/CVel or AIPS/CVEL for more details on usage. # I'm not sure how the Doppler corrections will be made but # likely not on the data in question. In practice, for # NRAO related telescopes this information is not reliable # and can be supplied as parameters to the correction software. # There are only a handful of transition available to MeerKAT # which all have very well known rest frequencies. # I don't know if MeerKAT plans online Doppler tracking which # I think is a bad idea anyway. 'LSRVEL': [0.0] * nif, # Velocity 'FREQOFF': [0.0] * nif, # Frequency Offset 'RESTFREQ': [0.0] * nif, # Rest Frequency # NOTE(bcotton) # BANDWIDTH was probably a mistake although, in principle, # it can be used to override the value in the FQ table. # I'm not sure if anything actually uses this. 'BANDWIDTH': [0.0], # Bandwidth of the SPW # NOTE(bcotton) # PMRA, PMDEC are the proper motions of Galactic or extragalactic # objects. These are a rather muddled implementation as they also # need both equinox and epoch of the standard position, which for # Hipparcos positions are different. In practice, these are usually # included in the apparent position of date. I can't see these ever # being useful for MeerKAT as they are never more than a few mas/yr. # There is a separate Planetary Ephemeris (PO) table for solar # system objects which may be needed for the Sun or planets # (a whole different bucket of worms). # I can't see these ever being useful for MeerKAT as they are never # more than a few mas/yr. There is a separate # Planetary Ephemeris (PO) table for solar system objects which # may be needed for the Sun or planets # (a whole different bucket of worms). 'PMRA': [0.0], # Proper Motion in Right Ascension 'PMDEC': [0.0], # Proper Motion in Declination # NOTE(bcotton) # QUAL can be used to subdivide data for a given "SOURCE" # (say for a mosaic).# "SOURCE" plus "QUAL" uniquely define # an entry in the table. The MeerKAT field of view is SO HUGE # I can't see this being needed. 'QUAL': [0.0], # Source Qualifier Number } used.append(source_name) catalogue.append(aips_source_data) return catalogue MEERKAT = 'MeerKAT' class _KatdalTransformer(object): """ Small wrapper around a katdal data attribute. Performs two functions 1. Transforms katdal data into AIPS format 2. Implements __getitem__ to proxy indexing calls to the underlying katdal data attribute. Basic idea is as follows: .. code-block:: python def __init__(self, ...): time_xform = lambda idx: (K.timestamps[idx] - midnight) / 86400.0 self._time_xformer = _KatdalTransformer(time_xform, shape=lambda: K.timestamps.shape, dtype=K.timestamps.dtype) @property def timestamps(self): return self._time_xformer """ def __init__(self, transform, shape, dtype): self._transform = transform self._shape = shape self._dtype = dtype def __getitem__(self, index): return self._transform(index) @property def shape(self): return self._shape() @property def dtype(self): return self._dtype def __len__(self): return self.shape[0] class KatdalAdapter(object): """ Adapts a :class:`katdal.DataSet` to look a bit more like a UV file. This is not a true adapter, but perhaps if called that enough, it will become one. """ def __init__(self, katds): """ Constructs a KatdalAdapter. Parameters ---------- katds : :class:`katdal.DataSet` An opened katdal dataset. """ self._katds = katds self._cache = {} self._nif = 1 self._catalogue = aips_catalogue(katds, self._nif) def _vis_xformer(index): """ Transform katdal visibilities indexed by ``index`` into AIPS visiblities. """ if isinstance(self._katds.vis, DaskLazyIndexer): arrays = [self._katds.vis, self._katds.weights, self._katds.flags] vis, weights, flags = [dask_getitem(array.dataset, np.s_[index, :, :]) for array in arrays] else: vis = da.from_array(self._katds.vis[index]) weights = da.from_array(self._katds.weights[index]) flags = da.from_array(self._katds.flags[index]) # Apply flags by negating weights weights = da.where(flags, -32767.0, weights) # Split complex vis dtype into real and imaginary parts vis_dtype = vis.dtype.type(0).real.dtype vis = vis.view(vis_dtype).reshape(vis.shape + (2,)) out_array = np.empty(weights.shape + (3,), dtype=vis_dtype) da.store([vis, weights], [out_array[..., 0:2], out_array[..., 2]], lock=False) return out_array def _time_xformer(index): """ Transform katdal timestamps indexed by ``index`` into AIPS timestamps. These are the Julian days since midnight on the observation date """ return aips_timestamps(self._katds.timestamps[index], self.midnight) # Convert katdal UVW into AIPS UVW def _u_xformer(i): return aips_uvw(self._katds.u[i], self.refwave) def _v_xformer(i): return aips_uvw(self._katds.v[i], self.refwave) def _w_xformer(i): return aips_uvw(self._katds.w[i], self.refwave) # Set up the actual transformers self._vis_xformer = _KatdalTransformer(_vis_xformer, shape=lambda: self._katds.vis.shape, dtype=self._katds.weights.dtype) self._time_xformer = _KatdalTransformer(_time_xformer, shape=lambda: self._katds.timestamps.shape, dtype=self._katds.timestamps.dtype) self._u_xformer = _KatdalTransformer(_u_xformer, shape=lambda: self._katds.u.shape, dtype=self._katds.u.dtype) self._v_xformer = _KatdalTransformer(_v_xformer, shape=lambda: self._katds.u.shape, dtype=self._katds.u.dtype) self._w_xformer = _KatdalTransformer(_w_xformer, shape=lambda: self._katds.u.shape, dtype=self._katds.u.dtype) @property def uv_timestamps(self): """ Returns times in Julian days since midnight on the Observation Date """ return self._time_xformer @property def uv_vis(self): """ Returns AIPS visibilities """ return self._vis_xformer @property def uv_u(self): """ U coordinate in seconds """ return self._u_xformer @property def uv_v(self): """ V coordinate in seconds """ return self._v_xformer @property def uv_w(self): """ W coordinate in seconds """ return self._w_xformer def scans(self): """ Generator iterating through scans in an observation. Proxies :meth:`katdal.Dataset.scans`. Yields ------ scan_index : int Scan index state : str State aips_source : dict AIPS Source """ for si, state, target in self._katds.scans(): yield si, state, self._catalogue[self.target_indices[0]] def aips_path(self, **kwargs): """ Constructs an aips path from a :class:`KatdalAdapter` Parameters ---------- **kwargs (optional): :obj: See :class:`AIPSPath` for information on keyword arguments. Returns ------- :class:`AIPSPath` AIPS path describing this observation """ name = kwargs.pop('name', None) dtype = kwargs.get('dtype', "AIPS") if name is None: name = self._katds.obs_params.get('capture_block_id', self._katds.experiment_id) if dtype == 'AIPS': name = name[-MAX_AIPS_PATH_LEN:] elif dtype == "FITS": name += '.uvfits' else: raise ValueError('Invalid dtype %s' % dtype) return AIPSPath(name=name, **kwargs) def select(self, **kwargs): """ Proxies :meth:`katdal.select` and adds optional `nif` selection. Parameters ---------- nif (optional): int Number of AIPSish IFs of equal frequency width to split the band into. **kwargs (optional): dict :meth:`katdal.select` arguments. See katdal documentation for information """ nif = kwargs.pop('nif', self.nif) result = self._katds.select(**kwargs) # Make sure any possible new channel range in selection is permitted self.nif = nif return result @property def size(self): return self._katds.size @property def shape(self): """ Proxies :meth:`katdal.DataSet.shape` """ return self._katds.shape @property def catalogue(self): """ AIPS source catalogue, resembling :attribute:`katdal.Dataset.catalogue`. """ return self._catalogue @property def scan_indices(self): """ Proxies :attr:`katdal.DataSet.scan_indices` """ return self._katds.scan_indices @property def target_indices(self): """ Proxies :attr:`katdal.DataSet.target_indices` """ return self._katds.target_indices @property def name(self): """ Proxies :attr:`katdal.DataSet.name` """ return self._katds.name @property def experiment_id(self): """ Proxies :attr:`katdal.DataSet.name` """ return self._katds.experiment_id @property def observer(self): """ Proxies :attr:`katdal.DataSet.observer` """ return self._katds.observer @property def description(self): """ Proxies :attr:`katdal.DataSet.description` """ return self._katds.description @property def version(self): """ Proxies :attr:`katdal.DataSet.version` """ return self._katds.version @property def katdal(self): """ The `katdal.DataSet` adapted by this object """ return self._katds @property def obsdat(self): """ Returns ------- str The observation date """ start = time.gmtime(self._katds.start_time.secs) return time.strftime('%Y-%m-%d', start) @property def midnight(self): """ Returns ------- float Midnight on the observation date in unix seconds """ return time.mktime(time.strptime(self.obsdat, '%Y-%m-%d')) @property def today(self): """ Returns ------- str The current date """ return datetime.date.today().strftime('%Y-%m-%d') @property def obs_params(self): """ Proxies :attr:`katdal.DataSet.obs_params` """ return getattr(self._katds, 'obs_params', {}) def correlator_products(self): """ Returns ------- list CorrelatorProduct(antenna1, antenna2, correlator_product_id) objects, with the correlator_product_id mapped as follows: .. code-block:: python { ('h','h'): 0, ('v','v'): 1, ('h','v'): 2, ('v','h'): 3 } """ class CorrelatorProduct(object): def __init__(self, ant1, ant2, cid): self.ant1 = ant1 self.ant2 = ant2 self.cid = cid @property def ant1_ix(self): return katdal_ant_nr(self.ant1.name) @property def ant2_ix(self): return katdal_ant_nr(self.ant2.name) @property def aips_ant1_ix(self): return aips_ant_nr(self.ant1.name) @property def aips_ant2_ix(self): return aips_ant_nr(self.ant2.name) @property def aips_bl_ix(self): """ This produces the AIPS baseline index random parameter """ return self.aips_ant1_ix * 256.0 + self.aips_ant2_ix # { name : antenna } mapping antenna_map = {a.name: a for a in self._katds.ants} products = [] for a1_corr, a2_corr in self._katds.corr_products: # These can look like 'm008v', 'm016h' etc. for MeerKAT # or 's0008v', 's0018h' etc. for SKA. # Separate into name 'm008' and polarisation 'v'. a1_name = a1_corr[:-1] a1_type = a1_corr[-1:].lower() a2_name = a2_corr[:-1] a2_type = a2_corr[-1:].lower() # Derive the correlation id try: cid = CORR_ID_MAP[(a1_type, a2_type)] except KeyError: raise ValueError("Invalid Correlator Product " "['%s, '%s']" % (a1_corr, a2_corr)) # Look up katdal antenna pair a1 = antenna_map[a1_name] a2 = antenna_map[a2_name] products.append(CorrelatorProduct(a1, a2, cid)) return products @property def nstokes(self): """ Returns ------- int The number of stokes parameters in this observation, derived from the number of times we see a pair of antenna names in the correlation products. """ # Count the number of times we see a correlation product counts = Counter((cp.ant1_ix, cp.ant2_ix) for cp in self.correlator_products()) return max(counts.values()) @property def nchan(self): """ Returns ------- int The number of channels in this observation. """ return len(self._katds.channel_freqs) @property def frqsel(self): """ The selected spectral window (FORTRAN-index) .. code-block:: python KA = KatdalAdapter(katdal.open('...')) assert KA.frqsel == 1 Returns ------- int The selected spectral window """ return self._katds.spw + 1 @property def nif(self): """ The number of spectral widows to use in the AIPS uv data. Must equally subdivide the number of frequency channels currently selected. Returns ------- int The number of spectral windows """ return self._nif @nif.setter def nif(self, numif): if self.nchan % numif != 0: raise ValueError('Number of requested IFs (%d) does not divide number of channels (%d)' % (numif, self.nchan)) else: self._nif = numif self._catalogue = aips_catalogue(self._katds, numif) @property def channel_freqs(self): """ Returns ------- list or np.ndarray List of channel frequencies """ return self._katds.channel_freqs @property def chinc(self): """ Returns ------- float The channel increment, or width. """ return self._katds.channel_width @property def reffreq(self): """ Returns ------- float The first channel frequency as the reference frequency, rather than the centre frequency. See `uv_format.rst`. """ return self._katds.channel_freqs[0] @property def refwave(self): """ Returns ------- float Reference wavelength in metres """ return LIGHTSPEED / self.reffreq @property def uv_antenna_keywords(self): """ Returns ------- dict Dictionary containing updates to the AIPS AN antenna table keywords. """ julian_date = UVDesc.PDate2JD(self.obsdat) return { 'ARRNAM': MEERKAT, 'FREQ': self.reffreq, # Reference frequency 'FREQID': self.frqsel, # Frequency setup id 'RDATE': self.obsdat, # Reference date 'NO_IF': self.nif, # Number of spectral windows # GST at 0h on reference data in degrees 'GSTIA0': UVDesc.GST0(julian_date) * 15.0, # Earth's rotation rate (degrees/day) 'DEGPDY': UVDesc.ERate(julian_date) * 360.0, } @property def uv_antenna_rows(self): """ Returns ------- list List of dictionaries describing each antenna. """ return [{ # MeerKAT antenna information 'NOSTA': [aips_ant_nr(a.name)], 'ANNAME': [a.name], 'STABXYZ': list(a.position_ecef), 'DIAMETER': [a.diameter], 'POLAA': [90.0], # Defaults for the rest 'POLAB': [0.0], 'POLCALA': [0.0, 0.0] * self.nif, 'POLCALB': [0.0, 0.0] * self.nif, 'POLTYA': ['X'], 'POLTYB': ['Y'], 'STAXOF': [0.0], 'BEAMFWHM': [0.0] * self.nif, 'ORBPARM': [], 'MNTSTA': [0] } for a in sorted(self._katds.ants)] @property def uv_source_keywords(self): """ Returns ------- dict Dictionary containing updates to the AIPS SU source table keywords. """ return { 'NO_IF': self.nif, # Number of spectral windows 'FREQID': self.frqsel, # Frequency setup ID 'VELDEF': 'RADIO', # Radio/Optical Velocity? # Velocity Frame of Reference (LSR is default) 'VELTYP': 'LSR' } @property def uv_source_rows(self): """ Returns ------- list List of dictionaries describing sources. """ return [self._catalogue[ti] for ti in self._katds.target_indices] @property def uv_spw_keywords(self): """ Returns ------- dict Dictionary containing updates to the AIPS FQ frequency table keywords. """ return {'NO_IF': self.nif} @property def max_antenna_number(self): """ Returns ------- integer The maximum AIPS antenna number """ return max(r['NOSTA'][0] for r in self.uv_antenna_rows) @property def uv_calibration_keywords(self): """ Returns ------- dict Dictionary containing updates to the AIPS CL calibration table keywords. """ return { 'NO_IF': self.nif, 'NO_POL': self.nstokes, 'NO_ANT': self.max_antenna_number, 'NO_TERM': 1, 'MFMOD': 1 } @property def uv_spw_rows(self): """ Returns ------- list List of dictionaries describing each spectral window. """ spw = self._katds.spectral_windows[self._katds.spw] bandwidth = abs(self.chinc) * self.nchan / self.nif return [{ # Fill in data from MeerKAT spectral window 'FRQSEL': [self.frqsel], # Frequency setup ID 'IF FREQ': [if_num * bandwidth for if_num in range(self.nif)], 'CH WIDTH': [self.chinc] * self.nif, # Should be 'BANDCODE' according to AIPS MEMO 117! 'RXCODE': [spw.band], 'SIDEBAND': [spw.sideband] * self.nif, 'TOTAL BANDWIDTH': [bandwidth] * self.nif, }] def fits_descriptor(self): """ FITS visibility descriptor setup """ nstokes = self.nstokes # Set STOKES CRVAL according to AIPS Memo 117 # { RR: -1.0, LL: -2.0, RL: -3.0, LR: -4.0, # XX: -5.0, YY: -6.0, XY: -7.0, YX: -8.0, # I: 1, Q: 2, U: 3, V: 4 } stokes_crval = 1.0 if nstokes == 1 else -5.0 stokes_cdelt = -1.0 # cdelt is always -1.0 return { 'naxis': 6, 'ctype': ['COMPLEX', 'STOKES', 'FREQ', 'IF', 'RA', 'DEC'], 'inaxes': [3, self.nstokes, self.nchan // self.nif, self.nif, 1, 1], 'cdelt': [1.0, stokes_cdelt, self.chinc, 1.0, 0.0, 0.0], 'crval': [1.0, stokes_crval, self.reffreq, 1.0, 0.0, 0.0], 'crpix': [1.0, 1.0, 1.0, 1.0, 1.0, 1.0], 'crota': [0.0, 0.0, 0.0, 0.0, 0.0, 0.0], } def default_table_cmds(self): """ Returns ------- dict """ return { "AIPS AN": { "attach": {'version': 1, 'numIF': self.nif}, "keywords": self.uv_antenna_keywords, "rows": self.uv_antenna_rows, "write": True, }, "AIPS FQ": { "attach": {'version': 1, 'numIF': self.nif}, "keywords": self.uv_spw_keywords, "rows": self.uv_spw_rows, "write": True, }, "AIPS SU": { "attach": {'version': 1, 'numIF': self.nif}, "keywords": self.uv_source_keywords, "rows": self.uv_source_rows, "write": True, }, "AIPS NX": { "attach": {'version': 1}, }, } def uv_descriptor(self): """ Returns ------- dict UV descriptor dictionary, derived from the metadata of a katdal file. Suitable for merging into a UVDesc dictionary when creating a new AIPS UV data file. """ # FITS descriptor is the base for our uv_descriptor desc = self.fits_descriptor() desc.update({ # Observation 'obsdat': self.obsdat, 'observer': self.observer, 'origin': 'katdal export', 'JDObs': UVDesc.PDate2JD(self.obsdat), 'date': self.today, 'epoch': 2000.0, 'equinox': 2000.0, 'teles': MEERKAT, 'instrume': self._katds.spectral_windows[self._katds.spw].product, 'isort': 'TB', # Time, Baseline sort order 'object': 'MULTI', # Source, this implies multiple sources 'nvis': 0, 'firstVis': 0, 'numVisBuff': 0, # These are automatically calculated, but # are left here for illustration # 'incs' : 3, # Stokes 1D increment. 3 floats in COMPLEX # 'incf' : 12, # Frequency 1D increment, 12 = 3*4 STOKES # 'incif' : 49152, # Spectral window 1D increment # # 49152 = 3*4*4096 CHANNELS # Regular parameter indices into ctypes/inaxes/cdelt etc. 'jlocc': 0, # COMPLEX 'jlocs': 1, # SOURCES 'jlocf': 2, # FREQ 'jlocif': 3, # IF 'jlocr': 4, # RA 'jlocd': 5, # DEC }) # Random parameter keys, indices and coordinate systems # index == -1 indicates its absence in the Visibility Buffer RP = attr.make_class("RandomParameters", ["key", "index", "type"]) random_parameters = [ RP('ilocu', 0, 'UU-L-SIN'), # U Coordinate RP('ilocv', 1, 'VV-L-SIN'), # V Coordinate RP('ilocw', 2, 'WW-L-SIN'), # W Coordinate RP('ilocb', 3, 'BASELINE'), # Baseline ID RP('iloct', 4, 'TIME1'), # Timestamp RP('iloscu', 5, 'SOURCE'), # Source Index RP('ilocfq', -1, 'FREQSEL'), # Frequency setup ID RP('ilocit', -1, 'INTTIM'), # Integration Time RP('ilocid', -1, 'CORR-ID'), # VLBA-specific RP('ilocws', -1, 'WEIGHT'), # Ignore # The following used when 'BASELINE' id # can't be calculated because number of antenna > 255 RP('iloca1', -1, 'ANTENNA1'), RP('iloca2', -1, 'ANTENNA2'), RP('ilocsa', -1, 'SUBARRAY'), ] # Construct parameter types for existent random parameters ptype = [rp.type for rp in random_parameters if not rp.index == -1] # Update with random parameters desc.update({rp.key: rp.index for rp in random_parameters}) desc.update({'nrparm': len(ptype), 'ptype': ptype}) return desc def time_chunked_scans(kat_adapter, time_step=4): """ Generator returning vibility data each scan, chunked on the time dimensions in chunks of ``time_step``. Internally, this iterates through :code:`kat_adapter.scan()` to produce a :code:`(si, state, source, data_gen)` tuple, where :code:`si` is the scan index, :code:`state` the state of the scan and :code:`source` the AIPS source dictionary. :code:`data_gen` is itself a generator that yields :code:`time_step` chunks of the data. Parameters ---------- kat_adapter : `KatdalAdapter` Katdal Adapter time_step : integer Size of time chunks (Default 4). 4 timesteps x 1024 channels x 2016 baselines x 4 stokes x 12 bytes works out to about 0.5 GB. Yields ------ si : int Scan index state : str Scan state aips source : dict Dictionary describing AIPS source data_gen : generator Generator yielding (u, v, w, time, baseline_index, visibilities) where :code:`len(time) <= time_step` """ cp = kat_adapter.correlator_products() nstokes = kat_adapter.nstokes # Lexicographically sort correlation products on (a1, a2, cid) def sort_fn(x): return (cp[x].ant1_ix, cp[x].ant2_ix, cp[x].cid) cp_argsort = np.asarray(sorted(range(len(cp)), key=sort_fn)) corr_products = np.asarray([cp[i] for i in cp_argsort]) # Use first stokes parameter index of each baseline bl_argsort = cp_argsort[::nstokes] # Take baseline products so that we don't recompute # UVW coordinates for all correlator products bl_products = corr_products.reshape(-1, nstokes)[:, 0] nbl, = bl_products.shape # AIPS baseline IDs aips_baselines = np.asarray([bp.aips_bl_ix for bp in bl_products], dtype=np.float32) # Get the AIPS visibility data shape (inaxes) # reverse to go from FORTRAN to C ordering fits_desc = kat_adapter.fits_descriptor() inaxes = tuple(reversed(fits_desc['inaxes'][:fits_desc['naxis']])) _, nchan, ncorrprods = kat_adapter.shape out_vis_size = kat_adapter.uv_vis.dtype.itemsize out_vis_shape = (time_step, nbl, nchan, nstokes, 3) vis_size_estimate = np.product(out_vis_shape, dtype=np.int64)*out_vis_size EIGHT_GB = 8*1024**3 if vis_size_estimate > EIGHT_GB: log.warn("Visibility chunk '%s' is greater than '%s'. " "Check that sufficient memory is available", fmt_bytes(vis_size_estimate), fmt_bytes(EIGHT_GB)) # Get some memory to hold reorganised visibilities out_vis = np.empty(out_vis_shape, dtype=kat_adapter.uv_vis.dtype) def _get_data(time_start, time_end): """ Retrieve data for the given time index range. Parameters ---------- time_start : integer Start time index for this scan time_end : integer Ending time index for this scan Returns ------- u : np.ndarray AIPS baseline U coordinates v : np.ndarray AIPS baseline V coordinates w : np.ndarray AIPS baseline W coordinates time : np.ndarray AIPS timestamp baselines : np.ndarray AIPS baselines id's vis : np.ndarray AIPS visibilities """ ntime = time_end - time_start # Retrieve scan data (ntime, nchan, nbl*nstokes) # nbl*nstokes is all mixed up at this point aips_time = kat_adapter.uv_timestamps[time_start:time_end] aips_vis = kat_adapter.uv_vis[time_start:time_end] aips_u = kat_adapter.uv_u[time_start:time_end] aips_v = kat_adapter.uv_v[time_start:time_end] aips_w = kat_adapter.uv_w[time_start:time_end] # Check dimension shapes assert aips_vis.dtype == np.float32 assert aips_time.dtype == np.float64 assert aips_u.dtype == np.float64 assert aips_v.dtype == np.float64 assert aips_w.dtype == np.float64 assert (ntime,) == aips_time.shape assert (ntime, nchan, ncorrprods, 3) == aips_vis.shape assert (ntime, ncorrprods) == aips_u.shape assert (ntime, ncorrprods) == aips_v.shape assert (ntime, ncorrprods) == aips_w.shape # Reorganise correlation product dim of aips_vis so that # correlations are grouped into nstokes per baseline and # baselines are in increasing order. aips_vis = _reorganise_product(aips_vis, cp_argsort.reshape(nbl, nstokes), out_vis[:ntime]) # Reshape to include the full AIPS UV inaxes shape, # including singleton ra and dec dimensions aips_vis.reshape((ntime, nbl,) + inaxes) # Select UVW coordinate of each baseline aips_u = aips_u[:, bl_argsort] aips_v = aips_v[:, bl_argsort] aips_w = aips_w[:, bl_argsort] assert aips_u.shape == (ntime, nbl) assert aips_v.shape == (ntime, nbl) assert aips_w.shape == (ntime, nbl) # Yield this scan's data return (aips_u, aips_v, aips_w, aips_time, aips_baselines, aips_vis) # Iterate through scans for si, state, target in kat_adapter.scans(): ntime = kat_adapter.shape[0] # Create a generator returning data # associated with chunks of time data. data_gen = (_get_data(ts, min(ts+time_step, ntime)) for ts in range(0, ntime, time_step)) # Yield scan variables and the generator yield si, state, target, data_gen @numba.jit(nopython=True, parallel=True) def _reorganise_product(vis, cp_argsort, out_vis): """ Reorganise correlation product dim of vis so that correlations are grouped as given in cp_argsort. Parameters ---------- vis : np.ndarray Input array of visibilities and weights. Shape: (ntime, nchan, nproducts, 3) where nproducts is the number of correlation products (i.e. nbaselines*nstokes). The last axis holds (real_vis, imag_vis, weight). cp_argsort : np.ndarray 2D array of indices to the 3rd axis of vis that are grouped into increasing AIPS baseline order and the Stokes order required of AIPS UV. Shape: (nbaselines, nstokes) out_vis : np.ndarray Output array to store reorganised visibilities in AIPS UV order. Shape: (ntime, nbaselines, nchan, nstokes, 3) Returns ------- out_vis : np.ndarray """ n_time = vis.shape[0] n_chan = vis.shape[1] n_bl = cp_argsort.shape[0] n_stok = cp_argsort.shape[1] for tm in range(n_time): bstep = 128 bblocks = (n_bl + bstep - 1) // bstep for bblock in numba.prange(bblocks): bstart = bblock * bstep bstop = min(n_bl, bstart + bstep) for prod in range(bstart, bstop): in_cp = cp_argsort[prod] for stok in range(n_stok): in_stok = in_cp[stok] for chan in range(n_chan): out_vis[tm, prod, chan, stok] = vis[tm, chan, in_stok] return out_vis
[ "numpy.empty", "time.strftime", "attr.make_class", "numpy.product", "UVDesc.ERate", "numba.prange", "katacomb.normalise_target_name", "UVDesc.PDate2JD", "katacomb.util.fmt_bytes", "UVDesc.GST0", "numpy.asarray", "datetime.date.today", "katacomb.AIPSPath", "dask.array.where", "dask.array....
[((319, 348), 'logging.getLogger', 'logging.getLogger', (['"""katacomb"""'], {}), "('katacomb')\n", (336, 348), False, 'import logging\n'), ((39652, 39691), 'numba.jit', 'numba.jit', ([], {'nopython': '(True)', 'parallel': '(True)'}), '(nopython=True, parallel=True)\n', (39661, 39691), False, 'import numba\n'), ((4577, 4640), 'katacomb.normalise_target_name', 'normalise_target_name', (['name', 'used'], {'max_length': 'MAX_AIPS_PATH_LEN'}), '(name, used, max_length=MAX_AIPS_PATH_LEN)\n', (4598, 4640), False, 'from katacomb import AIPSPath, normalise_target_name\n'), ((5844, 5866), 'numpy.asarray', 'np.asarray', (['[0.0, 0.0]'], {}), '([0.0, 0.0])\n', (5854, 5866), True, 'import numpy as np\n'), ((35397, 35436), 'numpy.asarray', 'np.asarray', (['[cp[i] for i in cp_argsort]'], {}), '([cp[i] for i in cp_argsort])\n', (35407, 35436), True, 'import numpy as np\n'), ((35774, 35841), 'numpy.asarray', 'np.asarray', (['[bp.aips_bl_ix for bp in bl_products]'], {'dtype': 'np.float32'}), '([bp.aips_bl_ix for bp in bl_products], dtype=np.float32)\n', (35784, 35841), True, 'import numpy as np\n'), ((36652, 36707), 'numpy.empty', 'np.empty', (['out_vis_shape'], {'dtype': 'kat_adapter.uv_vis.dtype'}), '(out_vis_shape, dtype=kat_adapter.uv_vis.dtype)\n', (36660, 36707), True, 'import numpy as np\n'), ((6210, 6227), 'numpy.rad2deg', 'np.rad2deg', (['radec'], {}), '(radec)\n', (6220, 6227), True, 'import numpy as np\n'), ((6276, 6294), 'numpy.rad2deg', 'np.rad2deg', (['aradec'], {}), '(aradec)\n', (6286, 6294), True, 'import numpy as np\n'), ((17387, 17416), 'katacomb.AIPSPath', 'AIPSPath', ([], {'name': 'name'}), '(name=name, **kwargs)\n', (17395, 17416), False, 'from katacomb import AIPSPath, normalise_target_name\n'), ((19625, 19665), 'time.gmtime', 'time.gmtime', (['self._katds.start_time.secs'], {}), '(self._katds.start_time.secs)\n', (19636, 19665), False, 'import time\n'), ((19681, 19713), 'time.strftime', 'time.strftime', (['"""%Y-%m-%d"""', 'start'], {}), "('%Y-%m-%d', start)\n", (19694, 19713), False, 'import time\n'), ((25376, 25404), 'UVDesc.PDate2JD', 'UVDesc.PDate2JD', (['self.obsdat'], {}), '(self.obsdat)\n', (25391, 25404), False, 'import UVDesc\n'), ((32759, 32820), 'attr.make_class', 'attr.make_class', (['"""RandomParameters"""', "['key', 'index', 'type']"], {}), "('RandomParameters', ['key', 'index', 'type'])\n", (32774, 32820), False, 'import attr\n'), ((36269, 36310), 'numpy.product', 'np.product', (['out_vis_shape'], {'dtype': 'np.int64'}), '(out_vis_shape, dtype=np.int64)\n', (36279, 36310), True, 'import numpy as np\n'), ((40916, 40937), 'numba.prange', 'numba.prange', (['bblocks'], {}), '(bblocks)\n', (40928, 40937), False, 'import numba\n'), ((13330, 13364), 'dask.array.where', 'da.where', (['flags', '(-32767.0)', 'weights'], {}), '(flags, -32767.0, weights)\n', (13338, 13364), True, 'import dask.array as da\n'), ((13574, 13621), 'numpy.empty', 'np.empty', (['(weights.shape + (3,))'], {'dtype': 'vis_dtype'}), '(weights.shape + (3,), dtype=vis_dtype)\n', (13582, 13621), True, 'import numpy as np\n'), ((13634, 13712), 'dask.array.store', 'da.store', (['[vis, weights]', '[out_array[..., 0:2], out_array[..., 2]]'], {'lock': '(False)'}), '([vis, weights], [out_array[..., 0:2], out_array[..., 2]], lock=False)\n', (13642, 13712), True, 'import dask.array as da\n'), ((19911, 19949), 'time.strptime', 'time.strptime', (['self.obsdat', '"""%Y-%m-%d"""'], {}), "(self.obsdat, '%Y-%m-%d')\n", (19924, 19949), False, 'import time\n'), ((36531, 36559), 'katacomb.util.fmt_bytes', 'fmt_bytes', (['vis_size_estimate'], {}), '(vis_size_estimate)\n', (36540, 36559), False, 'from katacomb.util import fmt_bytes\n'), ((36561, 36580), 'katacomb.util.fmt_bytes', 'fmt_bytes', (['EIGHT_GB'], {}), '(EIGHT_GB)\n', (36570, 36580), False, 'from katacomb.util import fmt_bytes\n'), ((13092, 13129), 'dask.array.from_array', 'da.from_array', (['self._katds.vis[index]'], {}), '(self._katds.vis[index])\n', (13105, 13129), True, 'import dask.array as da\n'), ((13156, 13197), 'dask.array.from_array', 'da.from_array', (['self._katds.weights[index]'], {}), '(self._katds.weights[index])\n', (13169, 13197), True, 'import dask.array as da\n'), ((13222, 13261), 'dask.array.from_array', 'da.from_array', (['self._katds.flags[index]'], {}), '(self._katds.flags[index])\n', (13235, 13261), True, 'import dask.array as da\n'), ((20099, 20120), 'datetime.date.today', 'datetime.date.today', ([], {}), '()\n', (20118, 20120), False, 'import datetime\n'), ((25794, 25818), 'UVDesc.GST0', 'UVDesc.GST0', (['julian_date'], {}), '(julian_date)\n', (25805, 25818), False, 'import UVDesc\n'), ((25899, 25924), 'UVDesc.ERate', 'UVDesc.ERate', (['julian_date'], {}), '(julian_date)\n', (25911, 25924), False, 'import UVDesc\n'), ((31504, 31532), 'UVDesc.PDate2JD', 'UVDesc.PDate2JD', (['self.obsdat'], {}), '(self.obsdat)\n', (31519, 31532), False, 'import UVDesc\n'), ((12944, 12991), 'katdal.lazy_indexer.dask_getitem', 'dask_getitem', (['array.dataset', 'np.s_[index, :, :]'], {}), '(array.dataset, np.s_[index, :, :])\n', (12956, 12991), False, 'from katdal.lazy_indexer import DaskLazyIndexer, dask_getitem\n')]
from Tkinter import * import ttk import Pmw from PIL import Image, ImageTk import os import numpy as np from matplotlib import pyplot as plt from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg from matplotlib.widgets import LassoSelector, RectangleSelector, EllipseSelector from matplotlib import path import matplotlib.patches as patches from matplotlib.patches import Ellipse from DataPreprocessing import* from DatasetSplit import* from MRT_Layer import* from cnn_main import* import scipy.io from tkFileDialog import askopenfilename import h5py # For the MainGUI it is important to change the four Pathes # sFolder: Path of the folder for all Probands # Path_markings: Path for Markings folder # Path_train_results: Path of the train results # Path_data: Path of the splittet Data (Training data, Validation data) class MainGUI(): def __init__(self): self.root = Tk() self.root.title('PatchBased Labeling') self.root.geometry('1425x770') self.root.configure(background="gray38") # Path self.sFolder = "C:/Users/<NAME>/Pictures/MRT" self.Path_markings = "C:/Users/<NAME>/Pictures/Universitaet/Masterarbeit/Markings/" self.Path_train_results = "C:/Users/<NAME>/Pictures/Universitaet/Masterarbeit/Results/" self.Path_data = "C:/Users/<NAME>/Pictures/Universitaet/Masterarbeit/Data_train_test/" Pmw.initialise() self.list_of_images = ["Move.png", "Rectangle.png", "Ellipse.png", "Lasso.png", "3D.png"] self.artefact_list = ["Movement-Artefact", "Shim-Artefact", "Noise-Artefact"] self.tool_buttons = [] self.mrt_layer_names = [] self.mrt_layer_set = [] self.optionlist = [] self.activated_button = 0 self.button1_activated = True self.x_clicked = None self.y_clicked = None self.mouse_second_clicked = False self.nb = Pmw.NoteBook(self.root) self.p1 = self.nb.add('DICOM-Image Processing') self.p2 = self.nb.add('Data Preprocessing') self.p3 = self.nb.add('Convolution Neural Network') self.p4 = self.nb.add('Viewing results') self.nb.pack(padx=5, pady=5, fill=BOTH, expand=1) # GUI first tab: DICOM-Image Processing ################################################################################################################################################################################# self.proband = os.listdir(self.sFolder) self.model = os.listdir(self.sFolder + "/" + self.proband[0] + "/dicom_sorted") self.rahmen1 = Frame(self.p1, bg="gray65", bd=3, relief="sunken") self.rahmen1.place(x=5, y=5, width=215, height=250) self.rahmen2 = Frame(self.p1, bg="gray65", bd=3, relief="sunken") self.rahmen2.place(x=5, y=260, width=215, height=200) image = Image.open("open.png") img_open = ImageTk.PhotoImage(image) label = Label(image=img_open) label.image = img_open self.load_button = Button(self.rahmen1, image=img_open, text="Load MRT-Layer", font=('Arial', 11, 'bold'), bg="gray56", activeforeground='grey', borderwidth=4, compound=LEFT, command = self.load_MRT) self.load_button.place(x=5, y=5, width=200, height=40) self.path_entry = Entry(self.rahmen1) self.path_entry.place(x=88, y=50, width=115, height=25) self.path_entry.insert(0, self.sFolder) self.proband_str = StringVar(self.p1) self.proband_str.set(self.proband[0]) self.proband_option = OptionMenu(self.rahmen1, self.proband_str, *self.proband) self.proband_option.config(bg="gray56") self.artefact_str = StringVar(self.p1) self.artefact_str.set(self.model[0]) self.artefact_option = OptionMenu(self.rahmen1, self.artefact_str, *self.model) self.artefact_option.config(bg="gray56") self.layer = StringVar(self.p1) self.layer.set("(empty)") self.option_layers = OptionMenu(self.rahmen1, self.layer, "(empty)") self.option_layers.config(bg="gray56") self.proband_option.place(x=5, y=80, width=200, height=50) # self.proband_option.place(x=5, y=55, width=200, height=50) self.artefact_option.place(x=5, y=135, width=200, height=50) # self.artefact_option.place(x=5, y=105, width=200, height=50) self.option_layers.place(x=5, y=190, width=200, height=50) # self.option_layers.place(x=5, y=155, width=200, height=50) self.path_label = Label(self.rahmen1, bg="gray65", font="Aral 10 bold", text="DICOM Path") self.path_label.place(x=5, y=52) self.draw_label = Label(self.rahmen2, bg="gray65", font="Aral 10 bold", text="Choose Drawing Tools") self.art_label = Label(self.rahmen2, bg="gray65", font="Aral 10 bold", text="Choose artefact type") self.draw_label.place(x=5, y=5) self.art_label.place(x=5, y=80) def onClick(i): old_button = self.activated_button self.activated_button = i if self.activated_button == 0: toggle_selector.ES.set_active(False) toggle_selector.RS.set_active(False) toggle_selector.LS.set_active(False) self.button1_activated = True if self.activated_button == 2: toggle_selector.ES.set_active(True) toggle_selector.RS.set_active(False) toggle_selector.LS.set_active(False) self.button1_activated = False if self.activated_button == 1: toggle_selector.ES.set_active(False) toggle_selector.RS.set_active(True) toggle_selector.LS.set_active(False) self.button1_activated = False if self.activated_button == 3: toggle_selector.ES.set_active(False) toggle_selector.RS.set_active(False) toggle_selector.LS.set_active(True) self.button1_activated = False if old_button == i: pass else: self.tool_buttons[old_button].configure(relief=RAISED) self.tool_buttons[self.activated_button].configure(relief=SUNKEN) return column = 5 for i in range(0, len(self.list_of_images), 1): image = Image.open(self.list_of_images[i]) img_tool = ImageTk.PhotoImage(image) label = Label(image=img_tool) label.image = img_tool b = Button(self.rahmen2, image=img_tool, bg="gray56", borderwidth=2, command=lambda i=i: onClick(i)) if i == 5: row = 45 column = 5 else: row = 30 b.place(x=column, y=row) column += 40 self.tool_buttons.append(b) self.tool_buttons[self.activated_button].configure(relief=SUNKEN) self.chooseArtefact = StringVar(self.root) self.chooseArtefact.set(self.artefact_list[0]) self.chooseArtefact_option = OptionMenu(self.rahmen2, self.chooseArtefact, *self.artefact_list) self.chooseArtefact_option.config(bg="gray56") self.chooseArtefact_option.place(x=5, y=105, width=200, height=50) self.panel = Label(self.p1, bg="black") self.panel2 = Label(self.p1, bg="LightSteelBlue4") self.panel.place(x=225, y=5, width=1204, height=764) self.panel2.place(x=225, y=5, width=1204, height=50) self.art_mod_label = Label(self.p1, bg="LightSteelBlue4", fg="white", font="Aral 12 bold") self.number_mrt_label = Label(self.p1, bg="LightSteelBlue4", fg="white", font="Aral 12 bold") self.v_min_label = Label(self.p1, bg="LightSteelBlue4", fg="white", font="Aral 9 bold") self.v_max_label = Label(self.p1, bg="LightSteelBlue4", fg="white", font="Aral 9 bold") self.fig = plt.figure(dpi=50) # self.fig.patch.set_facecolor('black') self.ax = plt.gca() self.pltc = None # self.ax.set_axis_bgcolor('black') self.ax.text(0.5, 0.5, 'To label MRT-Artefacts load MRT-Layer', horizontalalignment='center', verticalalignment='center', color='white', fontsize=20, transform=self.ax.transAxes) self.canvas = FigureCanvasTkAgg(self.fig, master=self.p1) self.canvas.show() self.canvas.get_tk_widget().place(x=600, y=250) # expand=1 def lasso_onselect(verts): print (verts) p = path.Path(verts) current_mrt_layer = self.get_currentLayerNumber() proband = self.mrt_layer_set[current_mrt_layer].get_proband() model = self.mrt_layer_set[current_mrt_layer].get_model() print(proband) print(model) saveFile = shelve.open(self.Path_markings + proband + ".slv", writeback=True) print(saveFile) patch = None col_str = None if self.chooseArtefact.get() == self.artefact_list[0]: col_str = "31" patch = patches.PathPatch(p, fill=False, edgecolor='red', lw=2) elif self.chooseArtefact.get() == self.artefact_list[1]: col_str = "32" patch = patches.PathPatch(p, fill=False, edgecolor='green', lw=2) elif self.chooseArtefact.get() == self.artefact_list[2]: col_str = "33" patch = patches.PathPatch(p, fill=False, edgecolor='blue', lw=2) self.ax.add_patch(patch) layer_name = model if saveFile.has_key(layer_name): number_str = str(self.mrt_layer_set[current_mrt_layer].get_current_Number()) + "_" + col_str + "_" + str(len(self.ax.patches) - 1) saveFile[layer_name].update({number_str: p}) else: number_str = str( self.mrt_layer_set[current_mrt_layer].get_current_Number()) + "_" + col_str + "_" + str( len(self.ax.patches) - 1) saveFile[layer_name] = {number_str: p} saveFile.close() self.fig.canvas.draw_idle() def ronselect(eclick, erelease): col_str = None rect = None ell = None x1, y1 = eclick.xdata, eclick.ydata x2, y2 = erelease.xdata, erelease.ydata current_mrt_layer = self.get_currentLayerNumber() proband = self.mrt_layer_set[current_mrt_layer].get_proband() model = self.mrt_layer_set[current_mrt_layer].get_model() print(proband) print(model) saveFile = shelve.open(self.Path_markings + proband +".slv", writeback=True) p = np.array(([x1,y1,x2,y2])) layer_name = model if toggle_selector.RS.active and not toggle_selector.ES.active: if self.chooseArtefact.get() == self.artefact_list[0]: col_str = "11" rect = plt.Rectangle((min(x1, x2), min(y1, y2)), np.abs(x1 - x2), np.abs(y1 - y2), fill=False, edgecolor="red", lw=2) elif self.chooseArtefact.get() == self.artefact_list[1]: col_str = "12" rect = plt.Rectangle((min(x1, x2), min(y1, y2)), np.abs(x1 - x2), np.abs(y1 - y2), fill=False, edgecolor="green", lw=2) elif self.chooseArtefact.get() == self.artefact_list[2]: col_str = "13" rect = plt.Rectangle((min(x1, x2), min(y1, y2)), np.abs(x1 - x2), np.abs(y1 - y2), fill=False, edgecolor="blue", lw=2) self.ax.add_patch(rect) elif toggle_selector.ES.active and not toggle_selector.RS.active: if self.chooseArtefact.get() == self.artefact_list[0]: col_str = "21" ell = Ellipse(xy=(min(x1, x2) + np.abs(x1 - x2) / 2, min(y1, y2) + np.abs(y1 - y2) / 2), width=np.abs(x1 - x2), height=np.abs(y1 - y2), edgecolor="red", fc='None', lw=2) elif self.chooseArtefact.get() == self.artefact_list[1]: col_str = "22" ell = Ellipse(xy=(min(x1, x2) + np.abs(x1 - x2) / 2, min(y1, y2) + np.abs(y1 - y2) / 2), width=np.abs(x1 - x2), height=np.abs(y1 - y2), edgecolor="green", fc='None', lw=2) elif self.chooseArtefact.get() == self.artefact_list[2]: col_str = "23" ell = Ellipse(xy=(min(x1, x2) + np.abs(x1 - x2) / 2, min(y1, y2) + np.abs(y1 - y2) / 2), width=np.abs(x1 - x2), height=np.abs(y1 - y2), edgecolor="blue", fc='None', lw=2) self.ax.add_patch(ell) if saveFile.has_key(layer_name): number_str = str(self.mrt_layer_set[current_mrt_layer].get_current_Number()) + "_" + col_str + "_" + str(len(self.ax.patches) - 1) saveFile[layer_name].update({number_str: p}) else: number_str = str( self.mrt_layer_set[current_mrt_layer].get_current_Number()) + "_" + col_str + "_" + str( len(self.ax.patches) - 1) saveFile[layer_name] = {number_str: p} saveFile.close() print(' startposition : (%f, %f)' % (eclick.xdata, eclick.ydata)) print(' endposition : (%f, %f)' % (erelease.xdata, erelease.ydata)) print(' used button : ', eclick.button) def toggle_selector(event): print(' Key pressed.') if self.activated_button == 2 and not toggle_selector.ES.active and ( toggle_selector.LS.active or toggle_selector.RS.active): toggle_selector.ES.set_active(True) toggle_selector.RS.set_active(False) toggle_selector.LS.set_active(False) if self.activated_button == 1 and not toggle_selector.RS.active and ( toggle_selector.LS.active or toggle_selector.ES.active): toggle_selector.ES.set_active(False) toggle_selector.RS.set_active(True) toggle_selector.LS.set_active(False) if self.activated_button == 3 and ( toggle_selector.ES.active or toggle_selector.RS.active) and not toggle_selector.LS.active: toggle_selector.ES.set_active(False) toggle_selector.RS.set_active(False) toggle_selector.LS.set_active(True) toggle_selector.RS = RectangleSelector(self.ax, ronselect, button=[1]) #drawtype='box', useblit=False, button=[1], minspanx=5, minspany=5, spancoords='pixels', interactive=True toggle_selector.ES = EllipseSelector(self.ax, ronselect, drawtype='line', button=[1], minspanx=5, minspany=5, spancoords='pixels', interactive=True) #drawtype='line', minspanx=5, minspany=5, spancoords='pixels', interactive=True toggle_selector.LS = LassoSelector(self.ax, lasso_onselect, button=[1]) toggle_selector.ES.set_active(False) toggle_selector.RS.set_active(False) toggle_selector.LS.set_active(False) self.fig.canvas.mpl_connect('key_press_event', self.click) self.fig.canvas.mpl_connect('button_press_event', self.mouse_clicked) self.fig.canvas.mpl_connect('motion_notify_event', self.mouse_move) self.fig.canvas.mpl_connect('button_release_event', self.mouse_release) # GUI second tab: Data Preprocessing ############################################################################################################################################################################# self.list_var = [] self.list_varl = [] self.list_proband = [] self.list_modell = [] self.tab2_rahmen1 = Frame(self.p2, bg="gray55", bd=3, relief="sunken") self.tab2_rahmen1.place(x=5, y=20, width=400, height=600) self.tab2_rahmen2 = Frame(self.p2, bg="gray55", bd=3, relief="sunken") self.tab2_rahmen2.place(x=450, y=20, width=540, height=600) self.lf_result = LabelFrame(self.p2, text='Patching-Results', font="Aral 12 bold") self.lf_result.place(x=1000, y=20, width=400, height=600) self.start_pre_button = Button(self.p2, text="Start Data Preprocessing", font=('Arial', 11, 'bold'), bg="gray56", activeforeground='grey', borderwidth=4, compound=LEFT, command=self.fData_Preprocessing) self.start_pre_button.place(x=1200, y=680, width=200, height=40) self.progress_label = Label(self.p2, font="Aral 10 bold", text="RigidPatching...") self.progress_label.place(x=5, y=655) self.progress = ttk.Progressbar(self.p2, orient="horizontal", length=600, mode="determinate") self.progress.place(x=5, y=680, width=1190, height=40) self.lf_proband = LabelFrame(self.tab2_rahmen1, text='Proband', bg="gray55", font="Aral 12 bold") self.lf_proband.place(x=20, y=10, width=360, height=200) self.lf_model = LabelFrame(self.tab2_rahmen1, text='Model', bg="gray55", font="Aral 12 bold") self.lf_model.place(x=20, y=220, width=360, height=350) col = 1 row = 1 for prob in range(0, len(self.proband), 1): var = IntVar() self.list_var.append(var) chk = Checkbutton(self.lf_proband, bg="gray55", text=self.proband[prob], font=('Arial', 11, 'bold'), variable=self.list_var[prob]) # tab2_rahmen1 chk.grid(row=row + 1, column=col + 1, sticky=W) self.list_proband.append(chk) if col == 5: col = 1 row += 1 else: col += 1 for mod in range(0, len(self.model), 1): var1 = IntVar() self.list_varl.append(var1) if self.model[mod] == "FastView_0001": chk = Checkbutton(self.lf_model, bg="gray55", text=self.model[mod], font=('Arial', 10, 'bold'), variable=self.list_varl[mod], state=DISABLED) # state = DISABLED # chk.state(['!selected']) chk.grid(row=mod + 1, column=1, sticky=W) self.list_modell.append(chk) else: chk = Checkbutton(self.lf_model, bg="gray55", text=self.model[mod], font=('Arial', 10, 'bold'), variable=self.list_varl[mod]) # chk.state(['!selected']) chk.grid(row=mod + 1, column=1, sticky=W) self.list_modell.append(chk) self.ch_patching_process = ["Rigid-Patching", "Adaptive-Splitting"] self.ch_patch_size = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] self.ch_patch_overlap = [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9] self.ch_data_splitting = ["normal", "normal_rand", "crossvalidation_data", "crossvalidation_patient"] self.ch_dimension = ["2D", "3D"] self.lf_patching = LabelFrame(self.tab2_rahmen2, text='Patching', bg="gray55", font="Aral 12 bold") self.lf_patching.place(x=20, y=10, width=500, height=200) self.lf_data_split = LabelFrame(self.tab2_rahmen2, text='Data Splitting', bg="gray55", font="Aral 12 bold") self.lf_data_split.place(x=20, y=220, width=500, height=350) # heading_frame1 = Label(tab2_rahmen2, text="Data Preprocessing", bg="gray55", font="Aral 14 bold") # heading_frame1.place(x=55, y=2) self.Patching_process = Label(self.lf_patching, text="Choose Patching-Process", bg="gray55", font="Aral 10 bold") self.Patching_process.place(x=5, y=5) self.patching_process = StringVar(self.root) self.patching_process.set(self.ch_patching_process[0]) self.patching_process_option = OptionMenu(self.lf_patching, self.patching_process, *self.ch_patching_process) self.patching_process_option.place(x=15, y=30, width=200, height=40) self.patch_size = Label(self.lf_patching, text="Choose Patch-Size (2D or 3D)", bg="gray55", font="Aral 10 bold") self.patch_size.place(x=5, y=80) self.patchsize1 = StringVar(self.root) self.patchsize1.set(self.ch_patch_size[3]) self.patchsize1_option = OptionMenu(self.lf_patching, self.patchsize1, *self.ch_patch_size) self.patchsize1_option.place(x=15, y=105, width=50, height=40) self.patchsize2 = StringVar(self.root) self.patchsize2.set(self.ch_patch_size[3]) self.patchsize2_option = OptionMenu(self.lf_patching, self.patchsize2, *self.ch_patch_size) self.patchsize2_option.place(x=90, y=105, width=50, height=40) self.patchsize3 = StringVar(self.root) self.patchsize3.set(self.ch_patch_size[3]) self.patchsize3_option = OptionMenu(self.lf_patching, self.patchsize3, *self.ch_patch_size) self.patchsize3_option.place(x=165, y=105, width=50, height=40) self.patch_overlap = Label(self.lf_patching, text="Choose Patch-Overlap", bg="gray55", font="Aral 10 bold") self.patch_overlap.place(x=270, y=5) self.patchOver = StringVar(self.root) self.patchOver.set(self.ch_patch_overlap[5]) self.patchOver_option = OptionMenu(self.lf_patching, self.patchOver, *self.ch_patch_overlap) self.patchOver_option.place(x=285, y=30, width=200, height=40) self.path_result_button = Button(self.lf_data_split, text="Choose Path", font=('Arial', 9, 'bold'), bg="gray56", activeforeground='grey', borderwidth=4, compound=LEFT, command=self.open_explorer) self.path_result_button.place(x=390, y=20, width=100, height=25) self.path_result_entry = Entry(self.lf_data_split) self.path_result_entry.place(x=10, y=20, width=370, height=25) self.split_data = Label(self.lf_data_split, text="Data-Splitting", bg="gray55", font="Aral 10 bold") self.split_data.place(x=5, y=65) self.data_split = StringVar(self.root) self.data_split.set(self.ch_data_splitting[0]) self.data_split_option = OptionMenu(self.lf_data_split, self.data_split, *self.ch_data_splitting) self.data_split_option.place(x=15, y=90, width=200, height=40) self.split_val = Label(self.lf_data_split, text="Split-Ratio", bg="gray55", font="Aral 10 bold") self.split_val.place(x=5, y=140) self.split_rat = StringVar(self.root) self.split_rat.set(self.ch_patch_overlap[1]) self.split_rat_option = OptionMenu(self.lf_data_split, self.split_rat, *self.ch_patch_overlap) self.split_rat_option.place(x=15, y=165, width=200, height=40) self.split_val_lab = Label(self.lf_data_split, text="Split-Ratio for Labeling", bg="gray55", font="Aral 10 bold") self.split_val_lab.place(x=5, y=215) self.split_rat_lab = StringVar(self.root) self.split_rat_lab.set(self.ch_patch_overlap[0]) self.split_rat_lab_option = OptionMenu(self.lf_data_split, self.split_rat_lab, *self.ch_patch_overlap) self.split_rat_lab_option.place(x=15, y=240, width=200, height=40) self.dim_lab = Label(self.lf_patching, text="Dimension", bg="gray55", font="Aral 10 bold") self.dim_lab.place(x=270, y=80) self.dim_rat_lab = StringVar(self.root) self.dim_rat_lab.set(self.ch_dimension[0]) self.dim_rat_lab_option = OptionMenu(self.lf_patching, self.dim_rat_lab, *self.ch_dimension) self.dim_rat_lab_option.place(x=285, y=105, width=200, height=40) # GUI tab3: CNN ##################################################################################################################################################### self.ch_cnn_model = ["motion_head", "motion_abd", "motion_all", "shim", "noise", "allData", "3D"] self.ch_parameter_optim = ["none", "grid"] self.ch_batchSize = [32, 64, 128] self.ch_learning_rate = [0.1, 0.01, 0.05, 0.005, 0.001] self.ch_epoch = [100, 200, 300, 400, 500, 600, 700, 800, 900, 1000] self.cnn_method = ["Training", "Prediction"] self.rahmen1_p3 = Frame(self.p3, bg="gray55", bd=3, relief="sunken") self.rahmen1_p3.place(x=5, y=5, width=400, height=600) self.lf_cnn = LabelFrame(self.rahmen1_p3, text='Parameter for CNN', bg="gray55", font="Aral 12 bold") self.lf_cnn.place(x=20, y=20, width=360, height=560) self.path_cnn_button = Button(self.lf_cnn, text="Choose Path", font=('Arial', 9, 'bold'), bg="gray56", activeforeground='grey', borderwidth=4, compound=LEFT, command=self.open_explorer) self.path_cnn_button.place(x=240, y=20, width=100, height=25) self.path_cnn_entry = Entry(self.lf_cnn) self.path_cnn_entry.place(x=10, y=20, width=220, height=25) self.Cnn_model = Label(self.lf_cnn, text="CNN-Model", bg="gray55", font="Aral 10 bold") self.Cnn_model.place(x=5, y=60) self.cnn_model = StringVar(self.root) self.cnn_model.set(self.ch_cnn_model[0]) self.cnn_model_option = OptionMenu(self.lf_cnn, self.cnn_model, *self.ch_cnn_model) self.cnn_model_option.place(x=80, y=85, width=200, height=40) self.para_optim = Label(self.lf_cnn, text="Parameter-Optimization", bg="gray55", font="Aral 10 bold") self.para_optim.place(x=5, y=135) self.para_opt = StringVar(self.root) self.para_opt.set(self.ch_parameter_optim[0]) self.para_opt_option = OptionMenu(self.lf_cnn, self.para_opt, *self.ch_parameter_optim) self.para_opt_option.place(x=80, y=160, width=200, height=40) self.batch = Label(self.lf_cnn, text="Batch-Size", bg="gray55", font="Aral 10 bold") self.batch.place(x=5, y=210) self.batch_opt = StringVar(self.root) self.batch_opt.set(self.ch_batchSize[1]) self.batch_opt_option = OptionMenu(self.lf_cnn, self.batch_opt, *self.ch_batchSize) self.batch_opt_option.place(x=80, y=235, width=200, height=40) self.learn = Label(self.lf_cnn, text="Learning-Rate", bg="gray55", font="Aral 10 bold") self.learn.place(x=5, y=285) self.learn_opt = StringVar(self.root) self.learn_opt.set(self.ch_learning_rate[1]) self.learn_opt_option = OptionMenu(self.lf_cnn, self.learn_opt, *self.ch_learning_rate) self.learn_opt_option.place(x=80, y=310, width=200, height=40) self.epoch = Label(self.lf_cnn, text="Epoche", bg="gray55", font="Aral 10 bold") self.epoch.place(x=5, y=360) self.epoch_opt = StringVar(self.root) self.epoch_opt.set(self.ch_epoch[2]) self.epoch_opt_option = OptionMenu(self.lf_cnn, self.epoch_opt, *self.ch_epoch) self.epoch_opt_option.place(x=80, y=385, width=200, height=40) self.method = Label(self.lf_cnn, text="CNN-Method", bg="gray55", font="Aral 10 bold") self.method.place(x=5, y=435) self.method_opt = StringVar(self.root) self.method_opt.set(self.cnn_method[0]) self.method_opt_option = OptionMenu(self.lf_cnn, self.method_opt, *self.cnn_method) self.method_opt_option.place(x=80, y=460, width=200, height=40) self.start_button_frame2 = Button(self.p3, text="Start Training CNN", font=('Arial', 11, 'bold'), bg="gray56", activeforeground='grey', borderwidth=4, compound=LEFT, command = self.start_cnn) self.start_button_frame2.place(x=1200, y=680, width=200, height=40) self.progress_label_p3 = Label(self.p3, font="Aral 10 bold", text="Training...") self.progress_label_p3.place(x=5, y=655) self.progress_p3 = ttk.Progressbar(self.p3, orient="horizontal", length=600, mode="determinate") self.progress_p3.place(x=5, y=680, width=1190, height=40) ####################################################################################################################################################### # GUI tab4: Visualize Results self.rahmen1_p4 = Frame(self.p4, bg="gray65", bd=3, relief="sunken") self.rahmen1_p4.place(x=5, y=5, width=215, height=250) self.rahmen2_p4 = Frame(self.p4, bg="gray65", bd=3, relief="sunken") self.rahmen2_p4.place(x=5, y=260, width=215, height=200) self.panel_p4 = Label(self.p4, bg="gray55") self.panel2_p4 = Label(self.p4, bg="LightSteelBlue4") self.panel_p4.place(x=225, y=5, width=1204, height=764) self.panel2_p4.place(x=225, y=5, width=1204, height=50) self.art_mod_label_p4 = Label(self.p4, bg="LightSteelBlue4", fg="white", font="Aral 12 bold", text="Proband: 01_ab, Model: t1_tse_tra_Kopf_0002") self.number_mrt_label_p4 = Label(self.p4, bg="LightSteelBlue4", fg="white", font="Aral 12 bold", text="1/40") self.art_mod_label_p4.place(x=227, y=7) self.number_mrt_label_p4.place(x=1350, y=7) self.root.mainloop() def load_MRT(self): mrt_layer_name = str(self.proband_str.get()) + "_" + str(self.artefact_str.get()) filenames_list = [] if mrt_layer_name in self.mrt_layer_names: pass else: self.mrt_layer_names.append(mrt_layer_name) PathDicom = self.sFolder + "/" + self.proband_str.get() + "/dicom_sorted/" + self.artefact_str.get() + "/" #load Dicom_Array files = sorted([os.path.join(PathDicom, file) for file in os.listdir(PathDicom)], key=os.path.getctime) datasets = [dicom.read_file(f) \ for f in files] print(datasets) try: voxel_ndarray, pixel_space = dicom_numpy.combine_slices(datasets) print(voxel_ndarray.shape) except dicom_numpy.DicomImportException: # invalid DICOM data raise dx, dy, dz = 1.0, 1.0, pixel_space[2][2] #pixel_space[0][0], pixel_space[1][1], pixel_space[2][2] pixel_array = voxel_ndarray[:, :, 0] x_1d = dx * np.arange(voxel_ndarray.shape[0]) y_1d = dy * np.arange(voxel_ndarray.shape[1]) z_1d = dz * np.arange(voxel_ndarray.shape[2]) model = self.artefact_str.get() proband = self.proband_str.get() mrt_layer = MRT_Layer(voxel_ndarray.shape[0], voxel_ndarray.shape[1], voxel_ndarray.shape[2], proband, model, x_1d,y_1d, z_1d, 0, 2000, voxel_ndarray, mrt_layer_name) self.mrt_layer_set.append(mrt_layer) self.optionlist.append("(" + str(len(self.mrt_layer_set)) + ") " + mrt_layer_name + ": " + str( voxel_ndarray.shape[0]) + " x " + str( voxel_ndarray.shape[1])) self.refresh_option(self.optionlist) self.number_mrt_label.config(text="1/" + str(mrt_layer.get_number_mrt())) self.art_mod_label.config(text = "Proband: " + str(self.proband_str.get()) + ", Model: " + str(self.artefact_str.get())) #text="Proband: 01_ab, Model: t1_tse_tra_Kopf_0002" self.v_min_label.config(text = "0") self.v_max_label.config(text = "2000") self.art_mod_label.place(x=227, y=7) self.number_mrt_label.place(x=1350, y=7) self.v_min_label.place(x=240, y=30) self.v_max_label.place(x=1330, y=30) plt.cla() plt.gca().set_aspect('equal') # plt.axes().set_aspect('equal') plt.xlim(0, voxel_ndarray.shape[0]*dx) plt.ylim(voxel_ndarray.shape[1]*dy, 0) plt.set_cmap(plt.gray()) self.pltc = plt.pcolormesh(x_1d, y_1d, np.swapaxes(pixel_array, 0, 1), vmin=0, vmax=2094) # load File_Path = self.Path_markings + self.proband_str.get() +".slv" loadFile = shelve.open(File_Path) number_Patch = 0 cur_no = "0" if loadFile.has_key(self.artefact_str.get()): layer = loadFile[self.artefact_str.get()] while layer.has_key(cur_no + "_11_" + str(number_Patch)) or layer.has_key(cur_no + "_12_" + str(number_Patch)) or layer.has_key(cur_no + "_13_" + str(number_Patch)) or layer.has_key(cur_no + "_21_" + str(number_Patch)) or layer.has_key(cur_no + "_22_" + str(number_Patch)) or layer.has_key(cur_no + "_23_" + str(number_Patch)) or layer.has_key(cur_no + "_31_" + str(number_Patch)) or layer.has_key(cur_no + "_32_" + str(number_Patch)) or layer.has_key(cur_no + "_33_" + str(number_Patch)): patch = None if layer.has_key(cur_no + "_11_" + str(number_Patch)): p = layer[cur_no + "_11_" + str(number_Patch)] patch = plt.Rectangle((min(p[0], p[2]), min(p[1], p[3])), np.abs(p[0] - p[2]), np.abs(p[1] - p[3]), fill=False, edgecolor="red", lw=2) elif layer.has_key(cur_no + "_12_" + str(number_Patch)): p = layer[cur_no + "_12_" + str(number_Patch)] patch = plt.Rectangle((min(p[0], p[2]), min(p[1], p[3])), np.abs(p[0] - p[2]), np.abs(p[1] - p[3]), fill=False, edgecolor="green", lw=2) elif layer.has_key(cur_no + "_13_" + str(number_Patch)): p = layer[cur_no + "_13_" + str(number_Patch)] patch = plt.Rectangle((min(p[0], p[2]), min(p[1], p[3])), np.abs(p[0] - p[2]), np.abs(p[1] - p[3]), fill=False, edgecolor="blue", lw=2) elif layer.has_key(cur_no + "_21_" + str(number_Patch)): p = layer[cur_no + "_21_" + str(number_Patch)] patch = Ellipse( xy=(min(p[0], p[2]) + np.abs(p[0] - p[2]) / 2, min(p[1], p[3]) + np.abs(p[1] - p[3]) / 2), width=np.abs(p[0] - p[2]), height=np.abs(p[1] - p[3]), edgecolor="red", fc='None', lw=2) elif layer.has_key(cur_no + "_22_" + str(number_Patch)): p = layer[cur_no + "_22_" + str(number_Patch)] patch = Ellipse( xy=(min(p[0], p[2]) + np.abs(p[0] - p[2]) / 2, min(p[1], p[3]) + np.abs(p[1] - p[3]) / 2), width=np.abs(p[0] - p[2]), height=np.abs(p[1] - p[3]), edgecolor="green", fc='None', lw=2) elif layer.has_key(cur_no + "_23_" + str(number_Patch)): p = layer[cur_no + "_23_" + str(number_Patch)] patch = Ellipse( xy=(min(p[0], p[2]) + np.abs(p[0] - p[2]) / 2, min(p[1], p[3]) + np.abs(p[1] - p[3]) / 2), width=np.abs(p[0] - p[2]), height=np.abs(p[1] - p[3]), edgecolor="blue", fc='None', lw=2) elif layer.has_key(cur_no + "_31_" + str(number_Patch)): p = layer[cur_no + "_31_" + str(number_Patch)] patch = patches.PathPatch(p, fill=False, edgecolor='red', lw=2) elif layer.has_key(cur_no + "_32_" + str(number_Patch)): p = layer[cur_no + "_32_" + str(number_Patch)] patch = patches.PathPatch(p, fill=False, edgecolor='green', lw=2) elif layer.has_key(cur_no + "_33_" + str(number_Patch)): p = layer[cur_no + "_33_" + str(number_Patch)] patch = patches.PathPatch(p, fill=False, edgecolor='blue', lw=2) self.ax.add_patch(patch) number_Patch += 1 self.fig.canvas.draw() def click(self, event): current_mrt_layer = self.get_currentLayerNumber() if event.key == 'right': if self.mrt_layer_set[current_mrt_layer].get_current_Number() < self.mrt_layer_set[ current_mrt_layer].get_number_mrt() - 1: self.mrt_layer_set[current_mrt_layer].increase_current_Number() plt.cla() plt.xlim(0, self.mrt_layer_set[current_mrt_layer].get_mrt_width()) plt.ylim(self.mrt_layer_set[current_mrt_layer].get_mrt_height(), 0) v_min = self.mrt_layer_set[current_mrt_layer].get_v_min() v_max = self.mrt_layer_set[current_mrt_layer].get_v_max() self.pltc = plt.pcolormesh(self.mrt_layer_set[current_mrt_layer].get_x_arange(), self.mrt_layer_set[current_mrt_layer].get_y_arange(), np.swapaxes(self.mrt_layer_set[current_mrt_layer].get_current_Slice(), 0, 1), vmin=v_min, vmax=v_max) self.number_mrt_label.config( text=str(self.mrt_layer_set[current_mrt_layer].get_current_Number() + 1) + "/" + str( self.mrt_layer_set[current_mrt_layer].get_number_mrt())) self.loadMark() self.fig.canvas.draw_idle() elif event.key == 'left': if self.mrt_layer_set[current_mrt_layer].get_current_Number() > 0: self.mrt_layer_set[current_mrt_layer].decrease_current_Number() plt.cla() plt.xlim(0, self.mrt_layer_set[current_mrt_layer].get_mrt_width()) plt.ylim(self.mrt_layer_set[current_mrt_layer].get_mrt_height(), 0) v_min = self.mrt_layer_set[current_mrt_layer].get_v_min() v_max = self.mrt_layer_set[current_mrt_layer].get_v_max() self.pltc = plt.pcolormesh(self.mrt_layer_set[current_mrt_layer].get_x_arange(), self.mrt_layer_set[current_mrt_layer].get_y_arange(), np.swapaxes(self.mrt_layer_set[current_mrt_layer].get_current_Slice(), 0, 1), vmin=v_min, vmax=v_max) self.number_mrt_label.config( text=str(self.mrt_layer_set[current_mrt_layer].get_current_Number() + 1) + "/" + str( self.mrt_layer_set[current_mrt_layer].get_number_mrt())) self.loadMark() self.fig.canvas.draw_idle() def mouse_clicked(self, event): if event.button == 2 and self.button1_activated: self.x_clicked = event.xdata self.y_clicked = event.ydata self.mouse_second_clicked = True elif event.button==3: current_mrt_layer = self.get_currentLayerNumber() art_mod = self.layer.get() proband = self.mrt_layer_set[current_mrt_layer].get_proband() model = self.mrt_layer_set[current_mrt_layer].get_model() print(proband) print(model) deleteMark = shelve.open(self.Path_markings + proband +".slv", writeback=True) layer = deleteMark[model] cur_no = str(self.mrt_layer_set[current_mrt_layer].get_current_Number()) cur_pa = str(len(self.ax.patches)-1) if layer.has_key(cur_no + "_11_" + cur_pa): del deleteMark[model][cur_no + "_11_" + cur_pa] elif layer.has_key(cur_no + "_12_" + cur_pa): del deleteMark[model][cur_no + "_12_" + cur_pa] elif layer.has_key(cur_no + "_13_" + cur_pa): del deleteMark[model][cur_no + "_13_" + cur_pa] elif layer.has_key(cur_no + "_21_" + cur_pa): del deleteMark[model][cur_no + "_21_" + cur_pa] elif layer.has_key(cur_no + "_22_" + cur_pa): del deleteMark[model][cur_no + "_22_" + cur_pa] elif layer.has_key(cur_no + "_23_" + cur_pa): del deleteMark[model][cur_no + "_23_" + cur_pa] elif layer.has_key(cur_no + "_31_" + cur_pa): del deleteMark[model][cur_no + "_31_" + cur_pa] elif layer.has_key(cur_no + "_32_" + cur_pa): del deleteMark[model][cur_no + "_32_" + cur_pa] elif layer.has_key(cur_no + "_33_" + cur_pa): del deleteMark[model][cur_no + "_33_" + cur_pa] deleteMark.close() plt.cla() plt.xlim(0, self.mrt_layer_set[current_mrt_layer].get_mrt_width()) plt.ylim(self.mrt_layer_set[current_mrt_layer].get_mrt_height(), 0) v_min = self.mrt_layer_set[current_mrt_layer].get_v_min() v_max = self.mrt_layer_set[current_mrt_layer].get_v_max() self.pltc = plt.pcolormesh(self.mrt_layer_set[current_mrt_layer].get_x_arange(), self.mrt_layer_set[current_mrt_layer].get_y_arange(), np.swapaxes(self.mrt_layer_set[current_mrt_layer].get_current_Slice(), 0, 1), vmin=v_min, vmax=v_max) self.loadMark() self.fig.canvas.draw_idle() def mouse_move(self, event): if self.button1_activated and self.mouse_second_clicked: factor = 10 __x = event.xdata - self.x_clicked __y = event.ydata - self.y_clicked print(__x) print(__y) v_min, v_max = self.pltc.get_clim() print(v_min, v_max) if __x >= 0 and __y >= 0: print("h") __vmin = np.abs(__x) * factor + np.abs(__y) * factor __vmax = np.abs(__x) * factor - np.abs(__y) * factor elif __x < 0 and __y >= 0: print("h") __vmin = -np.abs(__x) * factor + np.abs(__y) * factor __vmax = -np.abs(__x) * factor - np.abs(__y) * factor elif __x < 0 and __y < 0: print("h") __vmin = -np.abs(__x) * factor - np.abs(__y) * factor __vmax = -np.abs(__x) * factor + np.abs(__y) * factor else: print("h") __vmin = np.abs(__x) * factor - np.abs(__y) * factor __vmax = np.abs(__x) * factor + np.abs(__y) * factor v_min += __vmin v_max += __vmax print(v_min, v_max) self.v_min_label.config(text=str(v_min)) self.v_max_label.config(text=str(v_max)) self.pltc.set_clim(vmin=v_min, vmax=v_max) self.fig.canvas.draw() def mouse_release(self, event): current_mrt_layer = self.get_currentLayerNumber() self.mrt_layer_set[current_mrt_layer].set_v_min(int(self.v_min_label['text'])) self.mrt_layer_set[current_mrt_layer].set_v_max(int(self.v_max_label['text'])) if event.button == 2: self.mouse_second_clicked = False def loadMark(self): current_mrt_layer = self.get_currentLayerNumber() proband = self.mrt_layer_set[current_mrt_layer].get_proband() model = self.mrt_layer_set[current_mrt_layer].get_model() print(proband) print(model) loadFile = shelve.open(self.Path_markings + proband +".slv") number_Patch = 0 if loadFile.has_key(model): layer_name = model layer = loadFile[layer_name] cur_no = str(self.mrt_layer_set[current_mrt_layer].get_current_Number()) while layer.has_key(cur_no + "_11_" + str(number_Patch)) or layer.has_key( cur_no + "_12_" + str(number_Patch)) or layer.has_key( cur_no + "_13_" + str(number_Patch)) or layer.has_key( cur_no + "_21_" + str(number_Patch)) or layer.has_key( cur_no + "_22_" + str(number_Patch)) or layer.has_key( cur_no + "_23_" + str(number_Patch)) or layer.has_key( cur_no + "_31_" + str(number_Patch)) or layer.has_key( cur_no + "_32_" + str(number_Patch)) or layer.has_key( cur_no + "_33_" + str(number_Patch)): patch = None if layer.has_key(cur_no+ "_11_" + str(number_Patch)): p = layer[cur_no+ "_11_" + str(number_Patch)] print(p) patch = plt.Rectangle((min(p[0], p[2]), min(p[1], p[3])), np.abs(p[0] - p[2]), np.abs(p[1] - p[3]), fill=False, edgecolor="red", lw=2) elif layer.has_key(cur_no+ "_12_" + str(number_Patch)): p = layer[cur_no+ "_12_" + str(number_Patch)] patch = plt.Rectangle((min(p[0], p[2]), min(p[1], p[3])), np.abs(p[0] - p[2]), np.abs(p[1] - p[3]), fill=False, edgecolor="green", lw=2) elif layer.has_key(cur_no+ "_13_" + str(number_Patch)): p = layer[cur_no+ "_13_" + str(number_Patch)] patch = plt.Rectangle((min(p[0], p[2]), min(p[1], p[3])), np.abs(p[0] - p[2]), np.abs(p[1] - p[3]), fill=False, edgecolor="blue", lw=2) elif layer.has_key(cur_no + "_21_" + str(number_Patch)): p = layer[cur_no + "_21_" + str(number_Patch)] patch = Ellipse(xy=(min(p[0], p[2]) + np.abs(p[0] - p[2]) / 2, min(p[1], p[3]) + np.abs(p[1] - p[3]) / 2), width=np.abs(p[0] - p[2]), height=np.abs(p[1] - p[3]), edgecolor="red", fc='None', lw=2) elif layer.has_key(cur_no + "_22_" + str(number_Patch)): p = layer[cur_no + "_22_" + str(number_Patch)] patch = Ellipse(xy=(min(p[0], p[2]) + np.abs(p[0] - p[2]) / 2, min(p[1], p[3]) + np.abs(p[1] - p[3]) / 2), width=np.abs(p[0] - p[2]), height=np.abs(p[1] - p[3]), edgecolor="green", fc='None', lw=2) elif layer.has_key(cur_no + "_23_" + str(number_Patch)): p = layer[cur_no + "_23_" + str(number_Patch)] patch = Ellipse(xy=(min(p[0], p[2]) + np.abs(p[0] - p[2]) / 2, min(p[1], p[3]) + np.abs(p[1] - p[3]) / 2), width=np.abs(p[0] - p[2]), height=np.abs(p[1] - p[3]), edgecolor="blue", fc='None', lw=2) elif layer.has_key(cur_no + "_31_" + str(number_Patch)): p = layer[cur_no + "_31_" + str(number_Patch)] patch = patches.PathPatch(p, fill=False, edgecolor='red', lw=2) elif layer.has_key(cur_no + "_32_" + str(number_Patch)): p = layer[cur_no + "_32_" + str(number_Patch)] patch = patches.PathPatch(p, fill=False, edgecolor='green', lw=2) elif layer.has_key(cur_no + "_33_" + str(number_Patch)): p = layer[cur_no + "_33_" + str(number_Patch)] patch = patches.PathPatch(p, fill=False, edgecolor='blue', lw=2) self.ax.add_patch(patch) number_Patch += 1 def refresh_option(self, new_list): self.layer.set(new_list[len(new_list) - 1]) self.option_layers['menu'].delete(0, 'end') for choice in new_list: self.option_layers['menu'].add_command(label=choice, command=lambda value=choice: self.layer.set(value)) def get_currentLayerNumber(self): num = int(self.layer.get().find(")")) current_mrt_layer = 0 if num == 2: current_mrt_layer = int(self.layer.get()[1:2]) - 1 elif num == 3: current_mrt_layer = int(self.layer.get()[1:3]) - 1 return current_mrt_layer def open_explorer(self): name = askopenfilename() self.path_cnn_entry.insert(0, name) print(self.path_cnn_entry.get()) def fData_Preprocessing(self): allPatchesList = [] allLabelsList = [] proband_list = [] model_list = [] nbAllPatches = 0 if self.dim_rat_lab.get() == '2D': patch_Size = np.array(([int(self.patchsize1.get()), int(self.patchsize2.get())])) # dType = float else: patch_Size = np.array(([int(self.patchsize1.get()), int(self.patchsize2.get()), int(self.patchsize3.get())])) patch_overlap = float(self.patchOver.get()) for pnd in range(0, len(self.proband), 1): if self.list_var[pnd].get() == 1: for mod in range(0, len(self.model), 1): if self.list_varl[mod].get() == 1: proband = self.list_proband[pnd]['text'] proband_list.append(proband) model = self.list_modell[mod]['text'] model_list.append(model) print(proband, model) dPatches, dLabel, nbPatches = fPreprocessData(self.Path_markings, self.sFolder, proband, model, patch_Size, patch_overlap, float(self.split_rat_lab.get()), self.dim_rat_lab.get()) nbAllPatches = nbAllPatches + nbPatches allPatchesList.append(dPatches) allLabelsList.append(dLabel) if self.dim_rat_lab.get() == '2D': allPatches = np.zeros((patch_Size[0], patch_Size[1], nbAllPatches), dtype=float) else: allPatches = np.zeros((patch_Size[0], patch_Size[1], patch_Size[2], nbAllPatches), dtype=float) allLabels = np.zeros((nbAllPatches), dtype=float) firstIndex = 0 for iIndex in range(0, len(allPatchesList),1): if self.dim_rat_lab.get() == '2D': allPatches[:, :, firstIndex:firstIndex + allPatchesList[iIndex].shape[2]] = allPatchesList[iIndex] allLabels[firstIndex:firstIndex + allPatchesList[iIndex].shape[2]] = allLabelsList[iIndex] firstIndex = firstIndex + allPatchesList[iIndex].shape[2] else: allPatches[:, :, :, firstIndex:firstIndex + allPatchesList[iIndex].shape[3]] = allPatchesList[iIndex] allLabels[firstIndex:firstIndex + allPatchesList[iIndex].shape[3]] = allLabelsList[iIndex] firstIndex = firstIndex + allPatchesList[iIndex].shape[3] #allPatches[:,:,firstIndex:firstIndex+allPatchesList[iIndex].shape[2]]= allPatchesList[iIndex] #allLabels[firstIndex:firstIndex+allPatchesList[iIndex].shape[2]] = allLabelsList[iIndex] #firstIndex = firstIndex + allPatchesList[iIndex].shape[2] Path = "C:/Users/<NAME>/Pictures/Universitaet/Masterarbeit/Labels_Konfusion/Kopft1_mitLabel_2D.h5" with h5py.File(Path, 'w') as hf: # hf.create_dataset('AllPatches', data=allPatches) hf.create_dataset('AllLabels', data=allLabels) #print(allLabels) #label_name = "AllLabels" #patches_name = "AllPatches" #matFile = {label_name: allLabels,patches_name: allPatches} #scipy.io.savemat("Dicom_mask.mat", matFile) print("Rigid3D Done") # Data Splitting #if self.dim_rat_lab.get() == '2D': # fSplitDataset(self.Path_data, proband_list, model_list, allPatches, allLabels, self.data_split.get(), # patch_Size, patch_overlap, float(self.split_rat.get())) #else: # fSplitDataset3D(self.Path_data, proband_list, model_list, allPatches, allLabels, self.data_split.get(), # patch_Size, patch_overlap, float(self.split_rat.get())) def start_cnn(self): sPathOut = self.Path_train_results model = self.cnn_model.get() batchSize = int(self.batch_opt.get()) learn_rate = float(self.learn_opt.get()) epoch = int(self.epoch_opt.get()) CNN_execute(self.path_cnn_entry.get(), sPathOut, batchSize, learn_rate, epoch, model) if __name__ == "__main__": m = MainGUI()
[ "matplotlib.pyplot.gray", "numpy.abs", "matplotlib.widgets.LassoSelector", "matplotlib.pyplot.figure", "numpy.arange", "matplotlib.pyplot.gca", "ttk.Progressbar", "os.path.join", "matplotlib.pyplot.cla", "numpy.swapaxes", "matplotlib.patches.PathPatch", "tkFileDialog.askopenfilename", "h5py....
[((1433, 1449), 'Pmw.initialise', 'Pmw.initialise', ([], {}), '()\n', (1447, 1449), False, 'import Pmw\n'), ((1964, 1987), 'Pmw.NoteBook', 'Pmw.NoteBook', (['self.root'], {}), '(self.root)\n', (1976, 1987), False, 'import Pmw\n'), ((2532, 2556), 'os.listdir', 'os.listdir', (['self.sFolder'], {}), '(self.sFolder)\n', (2542, 2556), False, 'import os\n'), ((2579, 2645), 'os.listdir', 'os.listdir', (["(self.sFolder + '/' + self.proband[0] + '/dicom_sorted')"], {}), "(self.sFolder + '/' + self.proband[0] + '/dicom_sorted')\n", (2589, 2645), False, 'import os\n'), ((2941, 2963), 'PIL.Image.open', 'Image.open', (['"""open.png"""'], {}), "('open.png')\n", (2951, 2963), False, 'from PIL import Image, ImageTk\n'), ((2984, 3009), 'PIL.ImageTk.PhotoImage', 'ImageTk.PhotoImage', (['image'], {}), '(image)\n', (3002, 3009), False, 'from PIL import Image, ImageTk\n'), ((8234, 8252), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'dpi': '(50)'}), '(dpi=50)\n', (8244, 8252), True, 'from matplotlib import pyplot as plt\n'), ((8321, 8330), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (8328, 8330), True, 'from matplotlib import pyplot as plt\n'), ((8637, 8680), 'matplotlib.backends.backend_tkagg.FigureCanvasTkAgg', 'FigureCanvasTkAgg', (['self.fig'], {'master': 'self.p1'}), '(self.fig, master=self.p1)\n', (8654, 8680), False, 'from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg\n'), ((15163, 15212), 'matplotlib.widgets.RectangleSelector', 'RectangleSelector', (['self.ax', 'ronselect'], {'button': '[1]'}), '(self.ax, ronselect, button=[1])\n', (15180, 15212), False, 'from matplotlib.widgets import LassoSelector, RectangleSelector, EllipseSelector\n'), ((15351, 15482), 'matplotlib.widgets.EllipseSelector', 'EllipseSelector', (['self.ax', 'ronselect'], {'drawtype': '"""line"""', 'button': '[1]', 'minspanx': '(5)', 'minspany': '(5)', 'spancoords': '"""pixels"""', 'interactive': '(True)'}), "(self.ax, ronselect, drawtype='line', button=[1], minspanx=5,\n minspany=5, spancoords='pixels', interactive=True)\n", (15366, 15482), False, 'from matplotlib.widgets import LassoSelector, RectangleSelector, EllipseSelector\n'), ((15640, 15690), 'matplotlib.widgets.LassoSelector', 'LassoSelector', (['self.ax', 'lasso_onselect'], {'button': '[1]'}), '(self.ax, lasso_onselect, button=[1])\n', (15653, 15690), False, 'from matplotlib.widgets import LassoSelector, RectangleSelector, EllipseSelector\n'), ((17478, 17555), 'ttk.Progressbar', 'ttk.Progressbar', (['self.p2'], {'orient': '"""horizontal"""', 'length': '(600)', 'mode': '"""determinate"""'}), "(self.p2, orient='horizontal', length=600, mode='determinate')\n", (17493, 17555), False, 'import ttk\n'), ((28847, 28924), 'ttk.Progressbar', 'ttk.Progressbar', (['self.p3'], {'orient': '"""horizontal"""', 'length': '(600)', 'mode': '"""determinate"""'}), "(self.p3, orient='horizontal', length=600, mode='determinate')\n", (28862, 28924), False, 'import ttk\n'), ((49334, 49351), 'tkFileDialog.askopenfilename', 'askopenfilename', ([], {}), '()\n', (49349, 49351), False, 'from tkFileDialog import askopenfilename\n'), ((51194, 51229), 'numpy.zeros', 'np.zeros', (['nbAllPatches'], {'dtype': 'float'}), '(nbAllPatches, dtype=float)\n', (51202, 51229), True, 'import numpy as np\n'), ((6646, 6680), 'PIL.Image.open', 'Image.open', (['self.list_of_images[i]'], {}), '(self.list_of_images[i])\n', (6656, 6680), False, 'from PIL import Image, ImageTk\n'), ((6705, 6730), 'PIL.ImageTk.PhotoImage', 'ImageTk.PhotoImage', (['image'], {}), '(image)\n', (6723, 6730), False, 'from PIL import Image, ImageTk\n'), ((8860, 8876), 'matplotlib.path.Path', 'path.Path', (['verts'], {}), '(verts)\n', (8869, 8876), False, 'from matplotlib import path\n'), ((11123, 11149), 'numpy.array', 'np.array', (['[x1, y1, x2, y2]'], {}), '([x1, y1, x2, y2])\n', (11131, 11149), True, 'import numpy as np\n'), ((32704, 32713), 'matplotlib.pyplot.cla', 'plt.cla', ([], {}), '()\n', (32711, 32713), True, 'from matplotlib import pyplot as plt\n'), ((32804, 32844), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(0)', '(voxel_ndarray.shape[0] * dx)'], {}), '(0, voxel_ndarray.shape[0] * dx)\n', (32812, 32844), True, 'from matplotlib import pyplot as plt\n'), ((32856, 32896), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(voxel_ndarray.shape[1] * dy)', '(0)'], {}), '(voxel_ndarray.shape[1] * dy, 0)\n', (32864, 32896), True, 'from matplotlib import pyplot as plt\n'), ((50978, 51045), 'numpy.zeros', 'np.zeros', (['(patch_Size[0], patch_Size[1], nbAllPatches)'], {'dtype': 'float'}), '((patch_Size[0], patch_Size[1], nbAllPatches), dtype=float)\n', (50986, 51045), True, 'import numpy as np\n'), ((51087, 51174), 'numpy.zeros', 'np.zeros', (['(patch_Size[0], patch_Size[1], patch_Size[2], nbAllPatches)'], {'dtype': 'float'}), '((patch_Size[0], patch_Size[1], patch_Size[2], nbAllPatches), dtype\n =float)\n', (51095, 51174), True, 'import numpy as np\n'), ((52387, 52407), 'h5py.File', 'h5py.File', (['Path', '"""w"""'], {}), "(Path, 'w')\n", (52396, 52407), False, 'import h5py\n'), ((9439, 9494), 'matplotlib.patches.PathPatch', 'patches.PathPatch', (['p'], {'fill': '(False)', 'edgecolor': '"""red"""', 'lw': '(2)'}), "(p, fill=False, edgecolor='red', lw=2)\n", (9456, 9494), True, 'import matplotlib.patches as patches\n'), ((31301, 31334), 'numpy.arange', 'np.arange', (['voxel_ndarray.shape[0]'], {}), '(voxel_ndarray.shape[0])\n', (31310, 31334), True, 'import numpy as np\n'), ((31360, 31393), 'numpy.arange', 'np.arange', (['voxel_ndarray.shape[1]'], {}), '(voxel_ndarray.shape[1])\n', (31369, 31393), True, 'import numpy as np\n'), ((31419, 31452), 'numpy.arange', 'np.arange', (['voxel_ndarray.shape[2]'], {}), '(voxel_ndarray.shape[2])\n', (31428, 31452), True, 'import numpy as np\n'), ((32921, 32931), 'matplotlib.pyplot.gray', 'plt.gray', ([], {}), '()\n', (32929, 32931), True, 'from matplotlib import pyplot as plt\n'), ((32985, 33015), 'numpy.swapaxes', 'np.swapaxes', (['pixel_array', '(0)', '(1)'], {}), '(pixel_array, 0, 1)\n', (32996, 33015), True, 'import numpy as np\n'), ((37623, 37632), 'matplotlib.pyplot.cla', 'plt.cla', ([], {}), '()\n', (37630, 37632), True, 'from matplotlib import pyplot as plt\n'), ((41728, 41737), 'matplotlib.pyplot.cla', 'plt.cla', ([], {}), '()\n', (41735, 41737), True, 'from matplotlib import pyplot as plt\n'), ((9622, 9679), 'matplotlib.patches.PathPatch', 'patches.PathPatch', (['p'], {'fill': '(False)', 'edgecolor': '"""green"""', 'lw': '(2)'}), "(p, fill=False, edgecolor='green', lw=2)\n", (9639, 9679), True, 'import matplotlib.patches as patches\n'), ((30647, 30676), 'os.path.join', 'os.path.join', (['PathDicom', 'file'], {}), '(PathDicom, file)\n', (30659, 30676), False, 'import os\n'), ((32727, 32736), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (32734, 32736), True, 'from matplotlib import pyplot as plt\n'), ((38735, 38744), 'matplotlib.pyplot.cla', 'plt.cla', ([], {}), '()\n', (38742, 38744), True, 'from matplotlib import pyplot as plt\n'), ((9807, 9863), 'matplotlib.patches.PathPatch', 'patches.PathPatch', (['p'], {'fill': '(False)', 'edgecolor': '"""blue"""', 'lw': '(2)'}), "(p, fill=False, edgecolor='blue', lw=2)\n", (9824, 9863), True, 'import matplotlib.patches as patches\n'), ((11441, 11456), 'numpy.abs', 'np.abs', (['(x1 - x2)'], {}), '(x1 - x2)\n', (11447, 11456), True, 'import numpy as np\n'), ((11458, 11473), 'numpy.abs', 'np.abs', (['(y1 - y2)'], {}), '(y1 - y2)\n', (11464, 11473), True, 'import numpy as np\n'), ((30689, 30710), 'os.listdir', 'os.listdir', (['PathDicom'], {}), '(PathDicom)\n', (30699, 30710), False, 'import os\n'), ((42891, 42902), 'numpy.abs', 'np.abs', (['__x'], {}), '(__x)\n', (42897, 42902), True, 'import numpy as np\n'), ((42914, 42925), 'numpy.abs', 'np.abs', (['__y'], {}), '(__y)\n', (42920, 42925), True, 'import numpy as np\n'), ((42961, 42972), 'numpy.abs', 'np.abs', (['__x'], {}), '(__x)\n', (42967, 42972), True, 'import numpy as np\n'), ((42984, 42995), 'numpy.abs', 'np.abs', (['__y'], {}), '(__y)\n', (42990, 42995), True, 'import numpy as np\n'), ((45909, 45928), 'numpy.abs', 'np.abs', (['(p[0] - p[2])'], {}), '(p[0] - p[2])\n', (45915, 45928), True, 'import numpy as np\n'), ((45930, 45949), 'numpy.abs', 'np.abs', (['(p[1] - p[3])'], {}), '(p[1] - p[3])\n', (45936, 45949), True, 'import numpy as np\n'), ((11732, 11747), 'numpy.abs', 'np.abs', (['(x1 - x2)'], {}), '(x1 - x2)\n', (11738, 11747), True, 'import numpy as np\n'), ((11749, 11764), 'numpy.abs', 'np.abs', (['(y1 - y2)'], {}), '(y1 - y2)\n', (11755, 11764), True, 'import numpy as np\n'), ((34128, 34147), 'numpy.abs', 'np.abs', (['(p[0] - p[2])'], {}), '(p[0] - p[2])\n', (34134, 34147), True, 'import numpy as np\n'), ((34196, 34215), 'numpy.abs', 'np.abs', (['(p[1] - p[3])'], {}), '(p[1] - p[3])\n', (34202, 34215), True, 'import numpy as np\n'), ((43123, 43134), 'numpy.abs', 'np.abs', (['__y'], {}), '(__y)\n', (43129, 43134), True, 'import numpy as np\n'), ((43194, 43205), 'numpy.abs', 'np.abs', (['__y'], {}), '(__y)\n', (43200, 43205), True, 'import numpy as np\n'), ((46247, 46266), 'numpy.abs', 'np.abs', (['(p[0] - p[2])'], {}), '(p[0] - p[2])\n', (46253, 46266), True, 'import numpy as np\n'), ((46268, 46287), 'numpy.abs', 'np.abs', (['(p[1] - p[3])'], {}), '(p[1] - p[3])\n', (46274, 46287), True, 'import numpy as np\n'), ((12025, 12040), 'numpy.abs', 'np.abs', (['(x1 - x2)'], {}), '(x1 - x2)\n', (12031, 12040), True, 'import numpy as np\n'), ((12042, 12057), 'numpy.abs', 'np.abs', (['(y1 - y2)'], {}), '(y1 - y2)\n', (12048, 12057), True, 'import numpy as np\n'), ((12516, 12531), 'numpy.abs', 'np.abs', (['(x1 - x2)'], {}), '(x1 - x2)\n', (12522, 12531), True, 'import numpy as np\n'), ((12540, 12555), 'numpy.abs', 'np.abs', (['(y1 - y2)'], {}), '(y1 - y2)\n', (12546, 12555), True, 'import numpy as np\n'), ((34532, 34551), 'numpy.abs', 'np.abs', (['(p[0] - p[2])'], {}), '(p[0] - p[2])\n', (34538, 34551), True, 'import numpy as np\n'), ((34600, 34619), 'numpy.abs', 'np.abs', (['(p[1] - p[3])'], {}), '(p[1] - p[3])\n', (34606, 34619), True, 'import numpy as np\n'), ((43100, 43111), 'numpy.abs', 'np.abs', (['__x'], {}), '(__x)\n', (43106, 43111), True, 'import numpy as np\n'), ((43171, 43182), 'numpy.abs', 'np.abs', (['__x'], {}), '(__x)\n', (43177, 43182), True, 'import numpy as np\n'), ((43334, 43345), 'numpy.abs', 'np.abs', (['__y'], {}), '(__y)\n', (43340, 43345), True, 'import numpy as np\n'), ((43405, 43416), 'numpy.abs', 'np.abs', (['__y'], {}), '(__y)\n', (43411, 43416), True, 'import numpy as np\n'), ((43501, 43512), 'numpy.abs', 'np.abs', (['__x'], {}), '(__x)\n', (43507, 43512), True, 'import numpy as np\n'), ((43524, 43535), 'numpy.abs', 'np.abs', (['__y'], {}), '(__y)\n', (43530, 43535), True, 'import numpy as np\n'), ((43571, 43582), 'numpy.abs', 'np.abs', (['__x'], {}), '(__x)\n', (43577, 43582), True, 'import numpy as np\n'), ((43594, 43605), 'numpy.abs', 'np.abs', (['__y'], {}), '(__y)\n', (43600, 43605), True, 'import numpy as np\n'), ((46587, 46606), 'numpy.abs', 'np.abs', (['(p[0] - p[2])'], {}), '(p[0] - p[2])\n', (46593, 46606), True, 'import numpy as np\n'), ((46608, 46627), 'numpy.abs', 'np.abs', (['(p[1] - p[3])'], {}), '(p[1] - p[3])\n', (46614, 46627), True, 'import numpy as np\n'), ((12852, 12867), 'numpy.abs', 'np.abs', (['(x1 - x2)'], {}), '(x1 - x2)\n', (12858, 12867), True, 'import numpy as np\n'), ((12876, 12891), 'numpy.abs', 'np.abs', (['(y1 - y2)'], {}), '(y1 - y2)\n', (12882, 12891), True, 'import numpy as np\n'), ((34938, 34957), 'numpy.abs', 'np.abs', (['(p[0] - p[2])'], {}), '(p[0] - p[2])\n', (34944, 34957), True, 'import numpy as np\n'), ((35006, 35025), 'numpy.abs', 'np.abs', (['(p[1] - p[3])'], {}), '(p[1] - p[3])\n', (35012, 35025), True, 'import numpy as np\n'), ((43311, 43322), 'numpy.abs', 'np.abs', (['__x'], {}), '(__x)\n', (43317, 43322), True, 'import numpy as np\n'), ((43382, 43393), 'numpy.abs', 'np.abs', (['__x'], {}), '(__x)\n', (43388, 43393), True, 'import numpy as np\n'), ((13190, 13205), 'numpy.abs', 'np.abs', (['(x1 - x2)'], {}), '(x1 - x2)\n', (13196, 13205), True, 'import numpy as np\n'), ((13214, 13229), 'numpy.abs', 'np.abs', (['(y1 - y2)'], {}), '(y1 - y2)\n', (13220, 13229), True, 'import numpy as np\n'), ((47018, 47037), 'numpy.abs', 'np.abs', (['(p[0] - p[2])'], {}), '(p[0] - p[2])\n', (47024, 47037), True, 'import numpy as np\n'), ((47046, 47065), 'numpy.abs', 'np.abs', (['(p[1] - p[3])'], {}), '(p[1] - p[3])\n', (47052, 47065), True, 'import numpy as np\n'), ((12418, 12433), 'numpy.abs', 'np.abs', (['(x1 - x2)'], {}), '(x1 - x2)\n', (12424, 12433), True, 'import numpy as np\n'), ((12453, 12468), 'numpy.abs', 'np.abs', (['(y1 - y2)'], {}), '(y1 - y2)\n', (12459, 12468), True, 'import numpy as np\n'), ((35457, 35476), 'numpy.abs', 'np.abs', (['(p[0] - p[2])'], {}), '(p[0] - p[2])\n', (35463, 35476), True, 'import numpy as np\n'), ((35485, 35504), 'numpy.abs', 'np.abs', (['(p[1] - p[3])'], {}), '(p[1] - p[3])\n', (35491, 35504), True, 'import numpy as np\n'), ((47414, 47433), 'numpy.abs', 'np.abs', (['(p[0] - p[2])'], {}), '(p[0] - p[2])\n', (47420, 47433), True, 'import numpy as np\n'), ((47442, 47461), 'numpy.abs', 'np.abs', (['(p[1] - p[3])'], {}), '(p[1] - p[3])\n', (47448, 47461), True, 'import numpy as np\n'), ((48067, 48122), 'matplotlib.patches.PathPatch', 'patches.PathPatch', (['p'], {'fill': '(False)', 'edgecolor': '"""red"""', 'lw': '(2)'}), "(p, fill=False, edgecolor='red', lw=2)\n", (48084, 48122), True, 'import matplotlib.patches as patches\n'), ((12754, 12769), 'numpy.abs', 'np.abs', (['(x1 - x2)'], {}), '(x1 - x2)\n', (12760, 12769), True, 'import numpy as np\n'), ((12789, 12804), 'numpy.abs', 'np.abs', (['(y1 - y2)'], {}), '(y1 - y2)\n', (12795, 12804), True, 'import numpy as np\n'), ((35887, 35906), 'numpy.abs', 'np.abs', (['(p[0] - p[2])'], {}), '(p[0] - p[2])\n', (35893, 35906), True, 'import numpy as np\n'), ((35915, 35934), 'numpy.abs', 'np.abs', (['(p[1] - p[3])'], {}), '(p[1] - p[3])\n', (35921, 35934), True, 'import numpy as np\n'), ((36586, 36641), 'matplotlib.patches.PathPatch', 'patches.PathPatch', (['p'], {'fill': '(False)', 'edgecolor': '"""red"""', 'lw': '(2)'}), "(p, fill=False, edgecolor='red', lw=2)\n", (36603, 36641), True, 'import matplotlib.patches as patches\n'), ((47812, 47831), 'numpy.abs', 'np.abs', (['(p[0] - p[2])'], {}), '(p[0] - p[2])\n', (47818, 47831), True, 'import numpy as np\n'), ((47840, 47859), 'numpy.abs', 'np.abs', (['(p[1] - p[3])'], {}), '(p[1] - p[3])\n', (47846, 47859), True, 'import numpy as np\n'), ((48294, 48351), 'matplotlib.patches.PathPatch', 'patches.PathPatch', (['p'], {'fill': '(False)', 'edgecolor': '"""green"""', 'lw': '(2)'}), "(p, fill=False, edgecolor='green', lw=2)\n", (48311, 48351), True, 'import matplotlib.patches as patches\n'), ((13092, 13107), 'numpy.abs', 'np.abs', (['(x1 - x2)'], {}), '(x1 - x2)\n', (13098, 13107), True, 'import numpy as np\n'), ((13127, 13142), 'numpy.abs', 'np.abs', (['(y1 - y2)'], {}), '(y1 - y2)\n', (13133, 13142), True, 'import numpy as np\n'), ((36319, 36338), 'numpy.abs', 'np.abs', (['(p[0] - p[2])'], {}), '(p[0] - p[2])\n', (36325, 36338), True, 'import numpy as np\n'), ((36347, 36366), 'numpy.abs', 'np.abs', (['(p[1] - p[3])'], {}), '(p[1] - p[3])\n', (36353, 36366), True, 'import numpy as np\n'), ((36825, 36882), 'matplotlib.patches.PathPatch', 'patches.PathPatch', (['p'], {'fill': '(False)', 'edgecolor': '"""green"""', 'lw': '(2)'}), "(p, fill=False, edgecolor='green', lw=2)\n", (36842, 36882), True, 'import matplotlib.patches as patches\n'), ((46908, 46927), 'numpy.abs', 'np.abs', (['(p[0] - p[2])'], {}), '(p[0] - p[2])\n', (46914, 46927), True, 'import numpy as np\n'), ((46951, 46970), 'numpy.abs', 'np.abs', (['(p[1] - p[3])'], {}), '(p[1] - p[3])\n', (46957, 46970), True, 'import numpy as np\n'), ((48523, 48579), 'matplotlib.patches.PathPatch', 'patches.PathPatch', (['p'], {'fill': '(False)', 'edgecolor': '"""blue"""', 'lw': '(2)'}), "(p, fill=False, edgecolor='blue', lw=2)\n", (48540, 48579), True, 'import matplotlib.patches as patches\n'), ((35353, 35372), 'numpy.abs', 'np.abs', (['(p[0] - p[2])'], {}), '(p[0] - p[2])\n', (35359, 35372), True, 'import numpy as np\n'), ((35396, 35415), 'numpy.abs', 'np.abs', (['(p[1] - p[3])'], {}), '(p[1] - p[3])\n', (35402, 35415), True, 'import numpy as np\n'), ((37066, 37122), 'matplotlib.patches.PathPatch', 'patches.PathPatch', (['p'], {'fill': '(False)', 'edgecolor': '"""blue"""', 'lw': '(2)'}), "(p, fill=False, edgecolor='blue', lw=2)\n", (37083, 37122), True, 'import matplotlib.patches as patches\n'), ((47302, 47321), 'numpy.abs', 'np.abs', (['(p[0] - p[2])'], {}), '(p[0] - p[2])\n', (47308, 47321), True, 'import numpy as np\n'), ((47345, 47364), 'numpy.abs', 'np.abs', (['(p[1] - p[3])'], {}), '(p[1] - p[3])\n', (47351, 47364), True, 'import numpy as np\n'), ((35783, 35802), 'numpy.abs', 'np.abs', (['(p[0] - p[2])'], {}), '(p[0] - p[2])\n', (35789, 35802), True, 'import numpy as np\n'), ((35826, 35845), 'numpy.abs', 'np.abs', (['(p[1] - p[3])'], {}), '(p[1] - p[3])\n', (35832, 35845), True, 'import numpy as np\n'), ((47700, 47719), 'numpy.abs', 'np.abs', (['(p[0] - p[2])'], {}), '(p[0] - p[2])\n', (47706, 47719), True, 'import numpy as np\n'), ((47743, 47762), 'numpy.abs', 'np.abs', (['(p[1] - p[3])'], {}), '(p[1] - p[3])\n', (47749, 47762), True, 'import numpy as np\n'), ((36215, 36234), 'numpy.abs', 'np.abs', (['(p[0] - p[2])'], {}), '(p[0] - p[2])\n', (36221, 36234), True, 'import numpy as np\n'), ((36258, 36277), 'numpy.abs', 'np.abs', (['(p[1] - p[3])'], {}), '(p[1] - p[3])\n', (36264, 36277), True, 'import numpy as np\n')]
''' <NAME> TrimmerFun in python This program numerically calculates the equilibrium state and control vectors of an F-16 model given certain parameters. states: controls: x1 = Vt x4 = phi x7 = p x10 = pn u1 = throttle x2 = alpha x5 = theta x8 = q x11 = pe u2 = elevator x3 = beta x6 = psi x9 = r x12 = alt u3 = aileron x13 = pow u4 = rudder ''' from math import sin import numpy as np from scipy.optimize import minimize from clf16 import clf16 from adc import adc def trimmerFun(Xguess, Uguess, orient, inputs, printOn, model='stevens', adjust_cy=True): 'calculate equilibrium state' assert isinstance(Xguess, np.ndarray) assert isinstance(Uguess, np.ndarray) assert isinstance(inputs, np.ndarray) x = Xguess.copy() u = Uguess.copy() if printOn: print("------------------------------------------------------------") print("Running trimmerFun.m") # gamma singam rr pr tr phi cphi sphi thetadot coord stab orient const = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1] rtod = 57.29577951 # orient: 'Wings Level (gamma = 0)','Wings Level (gamma <> 0)','Steady Turn','Steady Pull Up' const[11] = orient # inputs: [Vt, h, gamm, psidot, thetadot] x[0] = inputs[0] x[11] = inputs[1] if orient == 2: gamm = inputs[2] const[0] = gamm/rtod const[1] = sin(const[0]) elif orient == 3: psidot = inputs[3] const[4] = psidot/rtod elif orient == 4: thetadot = inputs[4] const[8] = thetadot/rtod if orient == 3: s = np.zeros(shape=(7,)) s[0] = u[0] s[1] = u[1] s[2] = u[2] s[3] = u[3] s[4] = x[1] s[5] = x[3] s[6] = x[4] else: s = np.zeros(shape=(3,)) s[0] = u[0] s[1] = u[1] s[2] = x[1] maxiter = 1000 tol = 1e-7 minimize_tol = 1e-9 res = minimize(clf16, s, args=(x, u, const, model, adjust_cy), method='Nelder-Mead', tol=minimize_tol, \ options={'maxiter': maxiter}) cost = res.fun if printOn: print("Throttle (percent): {}".format(u[0])) print("Elevator (deg): {}".format(u[1])) print("Ailerons (deg): {}".format(u[2])) print("Rudder (deg): {}".format(u[3])) print("Angle of Attack (deg): {}".format(rtod*x[1])) print("Sideslip Angle (deg): {}".format(rtod*x[2])) print("Pitch Angle (deg): {}".format(rtod*x[4])) print("Bank Angle (deg): {}".format(rtod*x[3])) amach, qbar = adc(x[0], x[11]) print("Dynamic Pressure (psf): {}".format(qbar)) print("Mach Number: {}".format(amach)) print('') print("Cost Function: {}".format(cost)) assert cost < tol, "trimmerFun did not converge" return x, u
[ "adc.adc", "scipy.optimize.minimize", "numpy.zeros", "math.sin" ]
[((2033, 2164), 'scipy.optimize.minimize', 'minimize', (['clf16', 's'], {'args': '(x, u, const, model, adjust_cy)', 'method': '"""Nelder-Mead"""', 'tol': 'minimize_tol', 'options': "{'maxiter': maxiter}"}), "(clf16, s, args=(x, u, const, model, adjust_cy), method=\n 'Nelder-Mead', tol=minimize_tol, options={'maxiter': maxiter})\n", (2041, 2164), False, 'from scipy.optimize import minimize\n'), ((1488, 1501), 'math.sin', 'sin', (['const[0]'], {}), '(const[0])\n', (1491, 1501), False, 'from math import sin\n'), ((1699, 1719), 'numpy.zeros', 'np.zeros', ([], {'shape': '(7,)'}), '(shape=(7,))\n', (1707, 1719), True, 'import numpy as np\n'), ((1882, 1902), 'numpy.zeros', 'np.zeros', ([], {'shape': '(3,)'}), '(shape=(3,))\n', (1890, 1902), True, 'import numpy as np\n'), ((2773, 2789), 'adc.adc', 'adc', (['x[0]', 'x[11]'], {}), '(x[0], x[11])\n', (2776, 2789), False, 'from adc import adc\n')]
import numpy as np import pydensecrf.densecrf as dcrf from pydensecrf.utils import unary_from_labels, unary_from_softmax from pydensecrf.utils import compute_unary, create_pairwise_bilateral, \ create_pairwise_gaussian # Fully connected CRF post processing function def do_crf(im, mask, n_labels, enable_color=False, zero_unsure=True): colors, labels = np.unique(mask, return_inverse=True) image_size = mask.shape[:2] # n_labels = len(set(labels.flat)) d = dcrf.DenseCRF2D(image_size[1], image_size[0], n_labels) # width, height, nlabels U = unary_from_labels(labels, n_labels, gt_prob=.7, zero_unsure=zero_unsure) d.setUnaryEnergy(U) # This adds the color-independent term, features are the locations only. d.addPairwiseGaussian(sxy=(3,3), compat=3) if enable_color: # This adds the color-dependent term, i.e. features are (x,y,r,g,b). # im is an image-array, e.g. im.dtype == np.uint8 and im.shape == (640,480,3) d.addPairwiseBilateral(sxy=80, srgb=13, rgbim=im.astype('uint8'), compat=10) Q = d.inference(5) # 5 - num of iterations MAP = np.argmax(Q, axis=0).reshape(image_size) unique_map = np.unique(MAP) for u in unique_map: # get original labels back np.putmask(MAP, MAP == u, colors[u]) return MAP def post_process_crf(image, final_probabilities, num_cl): softmax = final_probabilities.squeeze() softmax = softmax.transpose((2, 0, 1)) # The input should be the negative of the logarithm of probability values # Look up the definition of the unary_from_softmax for more information unary = unary_from_softmax(softmax, scale=None, clip=1e-5) # The inputs should be C-continious -- we are using Cython wrapper unary = np.ascontiguousarray(unary) d = dcrf.DenseCRF(image.shape[0] * image.shape[1], num_cl) d.setUnaryEnergy(unary) # This potential penalizes small pieces of segmentation that are # spatially isolated -- enforces more spatially consistent segmentations feats = create_pairwise_gaussian(sdims=(10, 10), shape=image.shape[:2]) d.addPairwiseEnergy(feats, compat=3, kernel=dcrf.DIAG_KERNEL, normalization=dcrf.NORMALIZE_SYMMETRIC) # This creates the color-dependent features -- # because the segmentation that we get from CNN are too coarse # and we can use local color features to refine them feats = create_pairwise_bilateral(sdims=(50, 50), schan=(20, 20, 20), img=image, chdim=2) d.addPairwiseEnergy(feats, compat=10, kernel=dcrf.DIAG_KERNEL, normalization=dcrf.NORMALIZE_SYMMETRIC) Q = d.inference(10) res = np.argmax(Q, axis=0).reshape((image.shape[0], image.shape[1])) return res
[ "pydensecrf.utils.create_pairwise_gaussian", "numpy.argmax", "pydensecrf.utils.create_pairwise_bilateral", "numpy.unique", "pydensecrf.densecrf.DenseCRF", "pydensecrf.utils.unary_from_softmax", "pydensecrf.densecrf.DenseCRF2D", "numpy.putmask", "numpy.ascontiguousarray", "pydensecrf.utils.unary_fr...
[((362, 398), 'numpy.unique', 'np.unique', (['mask'], {'return_inverse': '(True)'}), '(mask, return_inverse=True)\n', (371, 398), True, 'import numpy as np\n'), ((478, 533), 'pydensecrf.densecrf.DenseCRF2D', 'dcrf.DenseCRF2D', (['image_size[1]', 'image_size[0]', 'n_labels'], {}), '(image_size[1], image_size[0], n_labels)\n', (493, 533), True, 'import pydensecrf.densecrf as dcrf\n'), ((568, 641), 'pydensecrf.utils.unary_from_labels', 'unary_from_labels', (['labels', 'n_labels'], {'gt_prob': '(0.7)', 'zero_unsure': 'zero_unsure'}), '(labels, n_labels, gt_prob=0.7, zero_unsure=zero_unsure)\n', (585, 641), False, 'from pydensecrf.utils import unary_from_labels, unary_from_softmax\n'), ((1173, 1187), 'numpy.unique', 'np.unique', (['MAP'], {}), '(MAP)\n', (1182, 1187), True, 'import numpy as np\n'), ((1613, 1664), 'pydensecrf.utils.unary_from_softmax', 'unary_from_softmax', (['softmax'], {'scale': 'None', 'clip': '(1e-05)'}), '(softmax, scale=None, clip=1e-05)\n', (1631, 1664), False, 'from pydensecrf.utils import unary_from_labels, unary_from_softmax\n'), ((1748, 1775), 'numpy.ascontiguousarray', 'np.ascontiguousarray', (['unary'], {}), '(unary)\n', (1768, 1775), True, 'import numpy as np\n'), ((1785, 1839), 'pydensecrf.densecrf.DenseCRF', 'dcrf.DenseCRF', (['(image.shape[0] * image.shape[1])', 'num_cl'], {}), '(image.shape[0] * image.shape[1], num_cl)\n', (1798, 1839), True, 'import pydensecrf.densecrf as dcrf\n'), ((2028, 2091), 'pydensecrf.utils.create_pairwise_gaussian', 'create_pairwise_gaussian', ([], {'sdims': '(10, 10)', 'shape': 'image.shape[:2]'}), '(sdims=(10, 10), shape=image.shape[:2])\n', (2052, 2091), False, 'from pydensecrf.utils import compute_unary, create_pairwise_bilateral, create_pairwise_gaussian\n'), ((2435, 2520), 'pydensecrf.utils.create_pairwise_bilateral', 'create_pairwise_bilateral', ([], {'sdims': '(50, 50)', 'schan': '(20, 20, 20)', 'img': 'image', 'chdim': '(2)'}), '(sdims=(50, 50), schan=(20, 20, 20), img=image,\n chdim=2)\n', (2460, 2520), False, 'from pydensecrf.utils import compute_unary, create_pairwise_bilateral, create_pairwise_gaussian\n'), ((1248, 1284), 'numpy.putmask', 'np.putmask', (['MAP', '(MAP == u)', 'colors[u]'], {}), '(MAP, MAP == u, colors[u])\n', (1258, 1284), True, 'import numpy as np\n'), ((1115, 1135), 'numpy.argmax', 'np.argmax', (['Q'], {'axis': '(0)'}), '(Q, axis=0)\n', (1124, 1135), True, 'import numpy as np\n'), ((2743, 2763), 'numpy.argmax', 'np.argmax', (['Q'], {'axis': '(0)'}), '(Q, axis=0)\n', (2752, 2763), True, 'import numpy as np\n')]
import os import threading import matplotlib as mpl mpl.rcParams['pdf.fonttype'] = 42 # Edit plots with Illustrator from matplotlib.figure import Figure from matplotlib.ticker import StrMethodFormatter import numpy as np import pandas as pd import skimage.morphology as skmorph from . import const from .events import Event from .status import DummyStatus from ..io import StackdataIO from ..roi import ContourRoi from ..stack import Stack from ..stack import metastack as ms from ..stack import types as ty from ..tracking import Tracker class SessionModel: #TODO: update this docstring """Session info container. The following structured fields are present: self.channel_selection list of dict The list items correspond to the channels of `self.display_stack` with the same index. The dict holds information of the selection widgets: 'type' str of the channel type; one of: `ty.TYPE_PHASECONTRAST`, `ty.TYPE_FLUORESCENCE` and `ty.TYPE_SEGMENTATION` 'val' boolean; indicates whether this channel is currently displayed (True) or not (False). 'button' tk.Button instance for displaying the channel self.channel_order list of int The list values are indices to `self.channel_selection`. The order of the values is the order in which to display the channel selection buttons. self.traces dict of dict The keys of the outer dict are the trace names (as str), each trace corresponding to one tracked cell. The inner dict holds information of the trace: 'roi' list with frame index as index and corresponding ROI name as value. The ContourRoi instance can be retrieved from `self.rois` using the frame index and the ROI name. 'select' boolean; if True, cell trace is read and displayed. 'highlight' boolean; if True, cell/trace is highlighted in stackviewer and in plot. Only meaningful if the 'select' option is True. 'val' dict of values read for the cell. The dict keys are the name of the quantity, the dict values are the corresponding values of the quantity. For most quantities (currently for all), the values are 1-dim numpy arrays with each element being to the value in the corresponding frame. Cell size is automatically present with the key 'Area'. Integrated fluorescence intensities are read for each fluorescence channel. 'plot' dict of plot objects (e.g. Line2D instance). The dict keys are the plotted quantities (as in 'val'), the values are the plot objects. Useful for plot manipulations like highlighting traces. self.trace_info dict of dict Holds information about the present data. The keys of the outer dict are names of the quantities ('Area' predefined), the inner dict contains: 'label' (optional) str with additional information about the trace, e.g. 'Fluorescence 1' 'channel' int, index of the corresponding channel in `self.stack`. May be None. 'unit' str, unit of the quantity. Used for proper axes labels in the plot, in later versions possibly also for unit conversions. Default: 'a.u.' 'factor' float, factor to multiply values to yield 'unit'. Default: None 'type' str, one of `TYPE_AREA` and `ty.TYPE_FLUORESCENCE`. Indicates the type of quantity of the trace. 'order' int, indicates in which order to display the plots. 'button' tk.Button, the button instance for controlling 'plot' 'var' tk.BooleanVar associated with 'button' 'plot' boolean, indicates whether to plot the quantity or not. 'quantity' str, name of the value used in plot for y-label The outer dict should only be changed using the methods `self.add_trace_info` or `self.clear_trace_info`. self.rois list of dict The list indices are the frame indices of the stack, the dict keys are the labels (as in the labeled image) of the ROIs in the frame (saved as string) and the dict values are the corresponding ContourRoi instances. """ def __init__(self): self.lock = threading.RLock() self.traces = {} self.trace_info = {} self.rois = [] self.init_trace_info() # TODO: abstract this away self.display_stack = None self.stacks = {} self.stack = None self.show_contour = True self.show_untrackable = False self.show_name = True self.frames_per_hour = 6 # TODO: let the user change this self._microscope_name = None self._microscope_resolution = None def init_trace_info(self): self.trace_info = {const.TYPE_AREA: dict(label=None, channel=None, unit="px²", factor=None, type=const.TYPE_AREA, order=0, button=None, var=None, plot=True, quantity="Cell area", )} def clear_trace_info(self): for k in tuple(self.trace_info.keys()): if k != const.TYPE_AREA: del self.trace_info[k] def open_stack(self, fn, status=None): """Open a stack and save it in SessionModel.stacks. Arguments: fn -- str, filename of the stack status -- Status instance for progress display Returns the stack_id (key to the SessionModel.stacks dictionary). """ if status is None: status = DummyStatus() stack_props = {} if fn.endswith('h5'): stack_props['channels'] = 0 stack_id = Event.now() stack = Stack(fn, status=status, **stack_props) stack_dir, stack_name = os.path.split(fn) n_channels = stack.n_channels with self.lock: self.stacks[stack_id] = {'id': stack_id, 'name': stack_name, 'dir': stack_dir, 'stack': stack, 'n_channels': n_channels, } return stack_id def close_stacks(self, *stack_ids, keep_open=()): """Close all stacks held only by this SessionModel""" if not stack_ids: stack_ids = list(self.stacks.keys()) for sid in stack_ids: try: stack = self.stacks[sid] except KeyError: continue if sid not in keep_open: stack['stack'].close() del self.stacks[sid] @property def stack_ids(self): return set(self.stacks.keys()) def get_stack_info(self, stack_id=None): """Get a stack info dict If 'stack_id' is None, return the whole 'stacks' dictionary. Else, return the stack info dict for the given stack ID. Returns None for non-existent stack ID. This method is thread-safe. The returned object must not be altered. """ with self.lock: if stack_id is None: return self.stacks try: return self.stacks[stack_id] except KeyError: return None def get_stack(self, stack_id=None): """Get a stack If 'stack_id' is None, return the whole stack dictionary. Else, return the stack info for the given stack ID. Returns None for non-existent stack ID. This method is thread-safe. The returned object must not be altered. """ with self.lock: if stack_id is None: return None try: return self.get_stack_info(stack_id)['stack'] except KeyError: return None def config(self, chan_info, render_factory, status=None, do_track=True): """Configure the session for display. 'chan_info' is a list holding dictionaries with these fields, defining the channels to be displayed: stack_id -- stack ID, key of `SessionModel.stacks` #DEBUG: Attention, changed behaviour name -- str, name of the stack dir -- str, directory where the stack file is saved i_channel -- int, index of stack to be used label -- str, optional user-defined description type -- str, stack type (phasecontrast, fluorescence, binary) 'render_factory' is a factory function for the display_stack rendering function 'status' is a Status instance for updating the status display. 'do_track' is a flag whether to perform tracking or not. Returns True in case of success, else False. """ # This function corresponds to MainWindow_TK.open_metastack. # The argument 'data' is renamed into 'chan_info' # (and has slightly different syntax, see docstring) if not chan_info: return False if status is None: status = DummyStatus() with self.lock, status("Preparing new session"): # Check image sizes stack_ids_used = set() #TODO: close stacks that are not used height_general = None width_general = None n_frames_general = None height_seg = None width_seg = None n_frames_seg = None for ci in chan_info: stack = self.get_stack(ci['stack_id']) if stack is None: pass elif ci['type'] == ty.TYPE_SEGMENTATION: height_seg = stack.height width_seg = stack.width n_frames_seg = stack.n_frames else: if height_general is None: height_general = stack.height elif stack.height != height_general: raise ValueError(f"Stack '{name}' has height {stack.height}, but height {height_general} is required.") if width_general is None: width_general = stack.width elif stack.width != width_general: raise ValueError(f"Stack '{name}' has width {stack.width}, but width {width_general} is required.") if n_frames_general is None: n_frames_general = stack.n_frames elif stack.n_frames != n_frames_general: raise ValueError(f"Stack '{name}' has {stack.n_frames} frames, but {n_frames_general} frames are required.") pad_y = 0 pad_x = 0 if None not in (height_general, height_seg): if height_seg > height_general: pad_y = height_seg - height_general if width_seg > width_general: pad_x = width_seg - width_general meta = ms.MetaStack() self.clear_trace_info() i_channel = 0 i_channel_fl = 1 close_stacks = set() retain_stacks = set() for ci in chan_info: stack = self.get_stack(ci['stack_id']) if ci['type'] == ty.TYPE_SEGMENTATION: if do_track and stack is not None: if pad_y or pad_x: with status("Cropping segmented stack"): stack.crop(right=pad_x, bottom=pad_y) self.track_stack(stack, channel=ci['i_channel'], status=status) close_stacks.add(stack) meta.add_channel(name='segmented_stack', label=ci['label'], type_=ci['type'], fun=self.render_segmentation, scales=False, ) else: name = stack.path meta.add_stack(stack, name=name) meta.add_channel(name=name, channel=ci['i_channel'], label=ci['label'], type_=ci['type'], ) retain_stacks.add(stack) if ci['type'] == ty.TYPE_FLUORESCENCE: label = f"Fluorescence {i_channel_fl}" name = ci['label'] if not name: name = label label = None self.add_trace_info(name, label=label, channel=i_channel, type_=ci['type'], order=i_channel_fl, plot=True, quantity="Integrated fluorescence", ) i_channel_fl += 1 i_channel += 1 # Close stacks that only contain segmentation close_stacks -= retain_stacks for stack in close_stacks: stack.close() if not meta.check_properties(): meta.set_properties(n_frames=n_frames_seg, width=width_seg, height=height_seg) # Set meta_stack and display_stack self.stack = meta self.display_stack = ms.MetaStack() self.display_stack.set_properties(n_frames=meta.n_frames, width=meta.width, height=meta.height, mode='uint8', ) if self.rois: for fr, rois in enumerate(self.rois): self.display_stack.set_rois(list(rois.values()), frame=fr) self.display_stack.add_channel(fun=render_factory(self.stack, self.render_segmentation), scales=True) # Read traces self.read_traces() def render_segmentation(self, meta, frame, scale=None, rois=None, binary=False): """Dynamically draw segmentation image from ROIs This method is to be called by `MetaStack.get_image`. Arguments: meta -- the calling `MetaStack` instance; ignored frame -- the index of the selected frame scale -- scaling information; ignored rois -- iterable of ROIs to show; if None, show all ROIs in frame binary -- if True, returned array is boolean, else uint8 """ img = np.zeros((meta.height, meta.width), dtype=(np.bool if binary else np.uint8)) if rois is None: if self.rois is None: print("SessionModel.render_segmentation: trying to read non-existent ROIs") #DEBUG return img rois = self.rois[frame].values() elif rois is False: rois = self.deselected_rois(frame) for roi in rois: img[roi.rows, roi.cols] = 255 return img def deselected_rois(self, frame): """Get an iterable of all non-selected ROIs in given frame""" if not self.rois: return () return (roi for roi in self.rois[frame].values() if roi.color not in (const.ROI_COLOR_SELECTED, const.ROI_COLOR_HIGHLIGHT)) def track_stack(self, s, channel=0, status=None): """Perform tracking of a given stack""" if status is None: status = DummyStatus() with self.lock, status("Tracking cells"): tracker = Tracker(segmented_stack=s, segmented_chan=channel, status=status) if s.stacktype == 'hdf5': tracker.preprocessing = self.segmentation_preprocessing tracker.get_traces() self.rois = [] self.traces = {} for fr, props in tracker.props.items(): self.rois.append({l: ContourRoi(regionprop=p, label=l, color=const.ROI_COLOR_UNTRACKABLE, visible=self.show_untrackable, name_visible=False, frame=fr, ) for l, p in props.items()}) for i, trace in enumerate(tracker.traces): name = str(i + 1) is_selected = tracker.traces_selection[i] self.traces[name] = {'roi': trace, 'select': is_selected, 'highlight': False, 'val': {}, 'plot': {}, } for fr, j in enumerate(trace): roi = self.rois[fr][j] roi.name = name roi.color = const.ROI_COLOR_SELECTED if is_selected else const.ROI_COLOR_DESELECTED roi.visible = bool(roi.name) and self.show_contour roi.name_visible = self.show_name def segmentation_preprocessing(self, img): """Preprocessing function for smoothening segmentation Smoothens 2D image `img` using morphological operations. `img` must have values from 0 to 1, indicating the probability that the corresponding pixel belongs to a cell. Returns a binary (boolean) image with same shape as `img`. This function is designed for preparing the Probability obtained from Ilastik for tracking, using the .label.Tracker.preprocessing attribute. """ img = img >= .5 img = skmorph.closing(img, selem=skmorph.disk(5)) img = skmorph.erosion(img, selem=skmorph.disk(1)) img = skmorph.dilation(img, selem=skmorph.disk(3)) #img = skmorph.area_closing(img, area_threshold=100) #img = skmorph.area_opening(img, area_threshold=100) img = skmorph.remove_small_holes(img, area_threshold=150) img = skmorph.remove_small_objects(img, min_size=150) return img def read_traces(self, status=None): """Read out cell traces""" if not self.traces: return if status is None: status = DummyStatus() with self.lock, status("Reading traces"): n_frames = self.stack.n_frames # Get fluorescence channels fl_chans = [] for name, info in self.trace_info.items(): if info['type'] == ty.TYPE_FLUORESCENCE: fl_chans.append({'name': name, 'i_channel': info['channel'], 'img': None, }) fl_chans.sort(key=lambda ch: self.trace_info[ch['name']]['order']) # Get microscope resolution (=area conversion factor) area_factor = self.trace_info[const.TYPE_AREA]['factor'] # Read traces for tr in self.traces.values(): tr['val'].clear() # Area val_area = np.empty(n_frames, dtype=np.float) for fr, i in enumerate(tr['roi']): val_area[fr] = self.rois[fr][i].area if area_factor is not None: val_area *= area_factor tr['val'][const.TYPE_AREA] = val_area # Fluorescence for ch in fl_chans: tr['val'][ch['name']] = np.empty(n_frames, dtype=np.float) for fr in range(n_frames): images = {} for ch in fl_chans: ch['img'] = self.stack.get_image(frame=fr, channel=ch['i_channel']) for tr in self.traces.values(): roi = self.rois[fr][tr['roi'][fr]] for ch in fl_chans: tr['val'][ch['name']][fr] = np.sum(ch['img'][roi.rows, roi.cols]) def add_trace_info(self, name, label=None, channel=None, unit="a.u.", factor=None, type_=None, order=None, plot=False, quantity=None): """Add information about a new category of traces""" with self.lock: self.trace_info[name] = {'label': label, 'channel': channel, 'unit': unit, 'factor': factor, 'type': type_, 'order': order, 'button': None, 'var': None, 'plot': plot, 'quantity': quantity if quantity is not None else type_, } def traces_sorted(self, fr): """Return a list of traces sorted by position fr -- the frame number """ with self.lock: rois = self.rois[fr] traces_pos = {} for name, tr in self.traces.items(): roi = rois[tr['roi'][fr]] traces_pos[name] = (roi.y_min, roi.x_min) return sorted(traces_pos.keys(), key=lambda name: traces_pos[name]) def traces_as_dataframes(self): """Return a dict of DataFrames of the traces""" t = self.to_hours(np.array(range(self.stack.n_frames))) time_vec = pd.DataFrame(t, columns=("Time [h]",)) df_dict = {} for name, tr in self.traces.items(): if not tr['select']: continue for qty, data in tr['val'].items(): try: df_dict[qty][name] = data except KeyError: df_dict[qty] = time_vec.copy() df_dict[qty][name] = data return df_dict def plot_traces(self, fig, is_interactive=False, frame_indicator_list=None, status=None): """Plots the traces. fig -- the Figure instance to plot to is_interactive -- special formatting for interactive plot frame_indicator_list -- list to which to add frame indicators """ if not self.traces: return if status is None: status = DummyStatus() with self.lock, status("Plotting traces …"): # Find data to be plotted and plotting order plot_list = [] for name, info in self.trace_info.items(): if info['plot']: plot_list.append(name) plot_list.sort(key=lambda name: self.trace_info[name]['order']) t_vec = self.to_hours(np.array(range(self.display_stack.n_frames))) axes = fig.subplots(len(plot_list), squeeze=False, sharex=True)[:,0] for qty, ax in zip(plot_list, axes): ax.set_xmargin(.003) ax.yaxis.set_major_formatter(StrMethodFormatter('{x:.4g}')) for name, tr in self.traces.items(): if not tr['select']: continue if tr['highlight']: lw = const.PLOT_WIDTH_HIGHLIGHT alpha = const.PLOT_ALPHA_HIGHLIGHT color = const.PLOT_COLOR_HIGHLIGHT else: lw = const.PLOT_WIDTH alpha = const.PLOT_ALPHA color = const.PLOT_COLOR l = ax.plot(t_vec, tr['val'][qty], color=color, alpha=alpha, lw=lw, label=name, picker=is_interactive, pickradius=3) if is_interactive: tr['plot'][qty] = l xlbl = "Time [h]" ax.set_ylabel("{quantity} [{unit}]".format(**self.trace_info[qty])) ax.set_title(qty, fontweight='bold') if is_interactive: if frame_indicator_list is not None: frame_indicator_list.append(ax.axvline(np.NaN, lw=1.5, color='r')) else: ax.xaxis.set_tick_params(labelbottom=True) if ax.is_last_row(): ax.set_xlabel(xlbl) def to_hours(self, x): """Convert 0-based frame number to hours""" try: with self.lock: return x / self.frames_per_hour except Exception: return np.NaN @property def mic_name(self): with self.lock: return self._microscope_name @property def mic_res(self): with self.lock: return self._microscope_resolution def set_microscope(self, name=None, resolution=None, status=None): """Set a microscope Arguments: name -- str, human-readable microscope/objective name resolution -- float, image resolution in [µm/px] status -- Status, passed on to `SessionModel.read_traces` """ if not resolution: name = None resolution = None elif not name: name = None elif resolution <= 0: raise ValueError(f"Illegal microscope settings: '{name}' with {resolution} µm/px") with self.lock: self._microscope_name = name self._microscope_resolution = resolution if resolution is not None: self.trace_info[const.TYPE_AREA]['unit'] = "µm²" self.trace_info[const.TYPE_AREA]['factor'] = resolution**2 else: self.trace_info[const.TYPE_AREA]['unit'] = "px²" self.trace_info[const.TYPE_AREA]['factor'] = None self.read_traces(status=status) def save_session(self, save_dir, status=None): """Save the session. Arguments: save_dir -- str indicating path of directory to which to save """ if status is None: status = DummyStatus() # Plot the data fig = Figure(figsize=(9,7)) self.plot_traces(fig) fig.savefig(os.path.join(save_dir, "Figure.pdf")) with self.lock, status("Saving session …"): # Save data to Excel file df_dict = self.traces_as_dataframes() with pd.ExcelWriter(os.path.join(save_dir, "Data.xlsx"), engine='xlsxwriter') as writer: for name, df in df_dict.items(): df.to_excel(writer, sheet_name=name, index=False) # Save data to CSV file for name, df in df_dict.items(): df.to_csv(os.path.join(save_dir, f"{name}.csv"), header=False, index=False, float_format='%.5f') # Export ROIs to JSON file sd = StackdataIO(traces=self.traces, rois=self.rois) sd.n_frames = self.stack.n_frames sd.microscope_name = self.mic_name sd.microscope_resolution = self.mic_res for i, ch in enumerate(self.stack.channels): if ch.isVirtual: path = None else: path = self.stack.stack(ch.name).path i_channel = ch.channel type_ = ch.type name = ch.name label = ch.label sd.add_channel(path, type_, i_channel, name, label) sd.dump(save_dir, "session.zip") print(f"Data have been written to '{save_dir}'") #DEBUG def from_stackio(self, fn, status=None): """Load session content from StackdataIO instance. Arguments: fn -- str, filename of the saved session status -- Status object for displaying progress Returns a new SessionModel instance. """ if status is None: status = DummyStatus() # Read session data and load content sd = StackdataIO(status=status) sd.load(fin=fn) self.set_microscope(name=sd.microscope_name, resolution=sd.microscope_resolution) self.rois = sd.rois for trace in sd.traces: name = trace['name'] self.traces[name] = { 'name': name, 'roi': trace['rois'], 'select': trace['select'], 'highlight': False, 'val': {}, 'plot': {}, } # Load stacks chan_info = [] stack_paths = {} for ch in sd.channels: x = {} if ch['file_directory'] is None or ch['file_name'] is None: path = None x['stack_id'] = None else: path = os.path.join(ch['file_directory'], ch['file_name']) try: x['stack_id'] = stack_paths[path] except KeyError: stack_id = self.open_stack(path, status=status) stack_paths[path] = stack_id x['stack_id'] = stack_id x['name'] = ch['name'] x['i_channel'] = ch['i_channel'] x['label'] = ch['label'] x['type'] = ch['type'] chan_info.append(x) return chan_info def binarize_phc_stack(self, *, outfile=None, status=None, return_result=False): from ..tools.binarize import binarize_phasecontrast_stack as tool_bin_phc # Get index of first phase-contrast channel for i, spec in enumerate(self.stack.channels): if spec.type == ty.TYPE_PHASECONTRAST: i_channel = i break else: print("SessionModel.binarize_phc_stack: no phase-contrast channel found.") #DEBUG return spec = self.stack.channels[i_channel] stack = self.stack.stack(spec.name) phc_channel = spec.channel result = tool_bin_phc(stack=stack, i_channel=phc_channel, outfile=outfile, status=status, return_result=return_result, ) return result def background_correction(self, outfile, status=None): from ..tools.bgcorr import perform_background_correction i_chan_fl = None i_chan_bin = None for i, spec in enumerate(self.stack.channels): if spec.type == ty.TYPE_FLUORESCENCE and i_chan_fl is None: i_chan_fl = i elif spec.type == ty.TYPE_SEGMENTATION and i_chan_bin is None: i_chan_bin = i if i_chan_fl is not None and i_chan_bin is not None: break # Get fluorescence channel if i_chan_fl is None: print("SessionModel.background_correction: no fluorescence channel found.") #DEBUG return c_fl0 = self.stack.get_image(channel=i_chan_fl, frame=0) chan_fl = np.empty((self.stack.n_frames, self.stack.height, self.stack.width), dtype=c_fl0.dtype) chan_fl[0, ...] = c_fl0 for t in range(1, self.stack.n_frames): chan_fl[t, ...] = self.stack.get_image(channel=i_chan_fl, frame=t) # Get segmentation channel if i_chan_bin is None: outfile_bin = f"{os.path.splitext(outfile)[0]}_segmented.npz" chan_bin = self.binarize_phc_stack(outfile=outfile_bin, status=status, return_result=True) else: c_bin0 = self.stack.get_image(channel=i_chan_bin, frame=0) chan_bin = np.empty((self.stack.n_frames, self.stack.height, self.stack.width), dtype=c_bin0.dtype) chan_bin[0, ...] = c_bin0 for t in range(1, self.stack.n_frames): chan_bin[t, ...] = self.stack.get_image(channel=i_chan_bin, frame=t) perform_background_correction(chan_fl=chan_fl, chan_bin=chan_bin, outfile=outfile, status=status)
[ "pandas.DataFrame", "numpy.sum", "matplotlib.ticker.StrMethodFormatter", "skimage.morphology.remove_small_holes", "threading.RLock", "numpy.empty", "numpy.zeros", "skimage.morphology.disk", "matplotlib.figure.Figure", "os.path.splitext", "skimage.morphology.remove_small_objects", "os.path.spli...
[((4701, 4718), 'threading.RLock', 'threading.RLock', ([], {}), '()\n', (4716, 4718), False, 'import threading\n'), ((6589, 6606), 'os.path.split', 'os.path.split', (['fn'], {}), '(fn)\n', (6602, 6606), False, 'import os\n'), ((15642, 15716), 'numpy.zeros', 'np.zeros', (['(meta.height, meta.width)'], {'dtype': '(np.bool if binary else np.uint8)'}), '((meta.height, meta.width), dtype=np.bool if binary else np.uint8)\n', (15650, 15716), True, 'import numpy as np\n'), ((19135, 19186), 'skimage.morphology.remove_small_holes', 'skmorph.remove_small_holes', (['img'], {'area_threshold': '(150)'}), '(img, area_threshold=150)\n', (19161, 19186), True, 'import skimage.morphology as skmorph\n'), ((19201, 19248), 'skimage.morphology.remove_small_objects', 'skmorph.remove_small_objects', (['img'], {'min_size': '(150)'}), '(img, min_size=150)\n', (19229, 19248), True, 'import skimage.morphology as skmorph\n'), ((22623, 22661), 'pandas.DataFrame', 'pd.DataFrame', (['t'], {'columns': "('Time [h]',)"}), "(t, columns=('Time [h]',))\n", (22635, 22661), True, 'import pandas as pd\n'), ((27251, 27273), 'matplotlib.figure.Figure', 'Figure', ([], {'figsize': '(9, 7)'}), '(figsize=(9, 7))\n', (27257, 27273), False, 'from matplotlib.figure import Figure\n'), ((32169, 32261), 'numpy.empty', 'np.empty', (['(self.stack.n_frames, self.stack.height, self.stack.width)'], {'dtype': 'c_fl0.dtype'}), '((self.stack.n_frames, self.stack.height, self.stack.width), dtype=\n c_fl0.dtype)\n', (32177, 32261), True, 'import numpy as np\n'), ((27323, 27359), 'os.path.join', 'os.path.join', (['save_dir', '"""Figure.pdf"""'], {}), "(save_dir, 'Figure.pdf')\n", (27335, 27359), False, 'import os\n'), ((32768, 32861), 'numpy.empty', 'np.empty', (['(self.stack.n_frames, self.stack.height, self.stack.width)'], {'dtype': 'c_bin0.dtype'}), '((self.stack.n_frames, self.stack.height, self.stack.width), dtype=\n c_bin0.dtype)\n', (32776, 32861), True, 'import numpy as np\n'), ((18865, 18880), 'skimage.morphology.disk', 'skmorph.disk', (['(5)'], {}), '(5)\n', (18877, 18880), True, 'import skimage.morphology as skmorph\n'), ((18923, 18938), 'skimage.morphology.disk', 'skmorph.disk', (['(1)'], {}), '(1)\n', (18935, 18938), True, 'import skimage.morphology as skmorph\n'), ((18982, 18997), 'skimage.morphology.disk', 'skmorph.disk', (['(3)'], {}), '(3)\n', (18994, 18997), True, 'import skimage.morphology as skmorph\n'), ((20304, 20338), 'numpy.empty', 'np.empty', (['n_frames'], {'dtype': 'np.float'}), '(n_frames, dtype=np.float)\n', (20312, 20338), True, 'import numpy as np\n'), ((29914, 29965), 'os.path.join', 'os.path.join', (["ch['file_directory']", "ch['file_name']"], {}), "(ch['file_directory'], ch['file_name'])\n", (29926, 29965), False, 'import os\n'), ((20701, 20735), 'numpy.empty', 'np.empty', (['n_frames'], {'dtype': 'np.float'}), '(n_frames, dtype=np.float)\n', (20709, 20735), True, 'import numpy as np\n'), ((24120, 24149), 'matplotlib.ticker.StrMethodFormatter', 'StrMethodFormatter', (['"""{x:.4g}"""'], {}), "('{x:.4g}')\n", (24138, 24149), False, 'from matplotlib.ticker import StrMethodFormatter\n'), ((27534, 27569), 'os.path.join', 'os.path.join', (['save_dir', '"""Data.xlsx"""'], {}), "(save_dir, 'Data.xlsx')\n", (27546, 27569), False, 'import os\n'), ((27830, 27867), 'os.path.join', 'os.path.join', (['save_dir', 'f"""{name}.csv"""'], {}), "(save_dir, f'{name}.csv')\n", (27842, 27867), False, 'import os\n'), ((21123, 21160), 'numpy.sum', 'np.sum', (["ch['img'][roi.rows, roi.cols]"], {}), "(ch['img'][roi.rows, roi.cols])\n", (21129, 21160), True, 'import numpy as np\n'), ((32512, 32537), 'os.path.splitext', 'os.path.splitext', (['outfile'], {}), '(outfile)\n', (32528, 32537), False, 'import os\n')]
import torch import torch.nn as nn import torch.nn.functional as F from torch import optim import copy import numpy as np def get_labels_start_end_time(frame_wise_labels, bg_class=["background"]): labels = [] starts = [] ends = [] last_label = frame_wise_labels[0] if frame_wise_labels[0] not in bg_class: labels.append(frame_wise_labels[0]) starts.append(0) for i in range(len(frame_wise_labels)): if frame_wise_labels[i] != last_label: if frame_wise_labels[i] not in bg_class: labels.append(frame_wise_labels[i]) starts.append(i) if last_label not in bg_class: ends.append(i) last_label = frame_wise_labels[i] if last_label not in bg_class: ends.append(i) return labels, starts, ends def levenstein(p, y, norm=False): m_row = len(p) n_col = len(y) D = np.zeros([m_row + 1, n_col + 1], np.float) for i in range(m_row + 1): D[i, 0] = i for i in range(n_col + 1): D[0, i] = i for j in range(1, n_col + 1): for i in range(1, m_row + 1): if y[j - 1] == p[i - 1]: D[i, j] = D[i - 1, j - 1] else: D[i, j] = min(D[i - 1, j] + 1, D[i, j - 1] + 1, D[i - 1, j - 1] + 1) if norm: score = (1 - D[-1, -1] / max(m_row, n_col)) * 100 else: score = D[-1, -1] return score def edit_score(recognized, ground_truth, norm=True, bg_class=["background"]): P, _, _ = get_labels_start_end_time(recognized, bg_class) Y, _, _ = get_labels_start_end_time(ground_truth, bg_class) return levenstein(P, Y, norm) def f_score(recognized, ground_truth, overlap, bg_class=["background"]): p_label, p_start, p_end = get_labels_start_end_time(recognized, bg_class) y_label, y_start, y_end = get_labels_start_end_time(ground_truth, bg_class) tp = 0 fp = 0 hits = np.zeros(len(y_label)) for j in range(len(p_label)): intersection = np.minimum(p_end[j], y_end) - np.maximum(p_start[j], y_start) union = np.maximum(p_end[j], y_end) - np.minimum(p_start[j], y_start) IoU = (1.0 * intersection / union) * ([p_label[j] == y_label[x] for x in range(len(y_label))]) # Get the best scoring segment idx = np.array(IoU).argmax() if IoU[idx] >= overlap and not hits[idx]: tp += 1 hits[idx] = 1 else: fp += 1 fn = len(y_label) - sum(hits) return float(tp), float(fp), float(fn) class MultiStageModel(nn.Module): def __init__(self, num_stages, num_layers, num_f_maps, dim, num_classes): super(MultiStageModel, self).__init__() self.stage1 = SingleStageModel(num_layers, num_f_maps, dim, num_classes) self.stages = nn.ModuleList([copy.deepcopy(SingleStageModel(num_layers, num_f_maps, num_classes, num_classes)) for s in range(num_stages-1)]) def forward(self, x, mask): out = self.stage1(x, mask) outputs = out.unsqueeze(0) for s in self.stages: out = s(F.softmax(out, dim=1) * mask[:, 0:1, :], mask) outputs = torch.cat((outputs, out.unsqueeze(0)), dim=0) return outputs class SingleStageModel(nn.Module): def __init__(self, num_layers, num_f_maps, dim, num_classes): super(SingleStageModel, self).__init__() self.conv_1x1 = nn.Conv1d(dim, num_f_maps, 1) self.layers = nn.ModuleList([copy.deepcopy(DilatedResidualLayer(2 ** i, num_f_maps, num_f_maps)) for i in range(num_layers)]) self.conv_out = nn.Conv1d(num_f_maps, num_classes, 1) def forward(self, x, mask): out = self.conv_1x1(x) for layer in self.layers: out = layer(out, mask) out = self.conv_out(out) * mask[:, 0:1, :] return out class DilatedResidualLayer(nn.Module): def __init__(self, dilation, in_channels, out_channels): super(DilatedResidualLayer, self).__init__() self.conv_dilated = nn.Conv1d(in_channels, out_channels, 3, padding=dilation, dilation=dilation) self.conv_1x1 = nn.Conv1d(out_channels, out_channels, 1) self.dropout = nn.Dropout() def forward(self, x, mask): out = F.relu(self.conv_dilated(x)) out = self.conv_1x1(out) out = self.dropout(out) return (x + out) * mask[:, 0:1, :] class Trainer: def __init__(self, num_blocks, num_layers, num_f_maps, dim, num_classes): self.model = MultiStageModel(num_blocks, num_layers, num_f_maps, dim, num_classes) self.ce = nn.CrossEntropyLoss(ignore_index=-100) self.mse = nn.MSELoss(reduction='none') self.num_classes = num_classes def train(self, save_dir, batch_gen, num_epochs, batch_size, learning_rate, device): self.model.train() self.model.to(device) optimizer = optim.Adam(self.model.parameters(), lr=learning_rate) for epoch in range(num_epochs): epoch_loss = 0 correct = 0 total = 0 while batch_gen.has_next(): batch_input, batch_target, mask = batch_gen.next_batch(batch_size) batch_input, batch_target, mask = batch_input.to(device), batch_target.to(device), mask.to(device) optimizer.zero_grad() predictions = self.model(batch_input, mask) loss = 0 for p in predictions: loss += self.ce(p.transpose(2, 1).contiguous().view(-1, self.num_classes), batch_target.view(-1)) loss += 0.15*torch.mean(torch.clamp(self.mse(F.log_softmax(p[:, :, 1:], dim=1), F.log_softmax(p.detach()[:, :, :-1], dim=1)), min=0, max=16)*mask[:, :, 1:]) epoch_loss += loss.item() loss.backward() optimizer.step() _, predicted = torch.max(predictions[-1].data, 1) correct += ((predicted == batch_target).float()*mask[:, 0, :].squeeze(1)).sum().item() total += torch.sum(mask[:, 0, :]).item() batch_gen.reset() torch.save(self.model.state_dict(), save_dir + "/epoch-" + str(epoch + 1) + ".model") torch.save(optimizer.state_dict(), save_dir + "/epoch-" + str(epoch + 1) + ".opt") print("[epoch %d]: epoch loss = %f, acc = %f" % (epoch + 1, epoch_loss / len(batch_gen.list_of_examples), float(correct)/total)) def predict(self, model_dir, results_dir, features_path, vid_list_file, epoch, actions_dict, device, sample_rate): self.model.eval() with torch.no_grad(): self.model.to(device) self.model.load_state_dict(torch.load(model_dir + "/epoch-" + str(epoch) + ".model")) file_ptr = open(vid_list_file, 'r') list_of_vids = file_ptr.read().split('\n')[:-1] file_ptr.close() for vid in list_of_vids: features = np.load(features_path + vid.split('.')[0] + '.npy') features = features[:, ::sample_rate] input_x = torch.tensor(features, dtype=torch.float) input_x.unsqueeze_(0) input_x = input_x.to(device) predictions = self.model(input_x, torch.ones(input_x.size(), device=device)) _, predicted = torch.max(predictions[-1].data, 1) predicted = predicted.squeeze() recognition = [] for i in range(len(predicted)): recognition = np.concatenate((recognition, [list(actions_dict.keys())[list(actions_dict.values()).index(predicted[i].item())]]*sample_rate)) f_name = vid.split('/')[-1].split('.')[0] f_ptr = open(results_dir + "/" + f_name, "w") f_ptr.write("### Frame level recognition: ###\n") f_ptr.write(' '.join(recognition)) f_ptr.close() # separate the actions count = 0 seg_dict = {} seg_dict['0'] = [] for _, item in enumerate(recognition): seg_dict[str(count)].append(item) if _ != len(recognition) - 1 and item != recognition[_ + 1]: count += 1 seg_dict[str(count)] = [] # print(seg_dict) """ References ------------------------- [1] <NAME> and <NAME>. MS-TCN: Multi-Stage Temporal Convolutional Network for Action Segmentation. In IEEE Conference on Computer Vision and Pattern Recognition (CVPR), 2019 """
[ "torch.nn.Dropout", "torch.nn.MSELoss", "numpy.minimum", "numpy.maximum", "torch.nn.Conv1d", "torch.nn.CrossEntropyLoss", "numpy.zeros", "torch.nn.functional.softmax", "numpy.array", "torch.max", "torch.nn.functional.log_softmax", "torch.no_grad", "torch.sum", "torch.tensor" ]
[((917, 959), 'numpy.zeros', 'np.zeros', (['[m_row + 1, n_col + 1]', 'np.float'], {}), '([m_row + 1, n_col + 1], np.float)\n', (925, 959), True, 'import numpy as np\n'), ((3481, 3510), 'torch.nn.Conv1d', 'nn.Conv1d', (['dim', 'num_f_maps', '(1)'], {}), '(dim, num_f_maps, 1)\n', (3490, 3510), True, 'import torch.nn as nn\n'), ((3669, 3706), 'torch.nn.Conv1d', 'nn.Conv1d', (['num_f_maps', 'num_classes', '(1)'], {}), '(num_f_maps, num_classes, 1)\n', (3678, 3706), True, 'import torch.nn as nn\n'), ((4093, 4169), 'torch.nn.Conv1d', 'nn.Conv1d', (['in_channels', 'out_channels', '(3)'], {'padding': 'dilation', 'dilation': 'dilation'}), '(in_channels, out_channels, 3, padding=dilation, dilation=dilation)\n', (4102, 4169), True, 'import torch.nn as nn\n'), ((4194, 4234), 'torch.nn.Conv1d', 'nn.Conv1d', (['out_channels', 'out_channels', '(1)'], {}), '(out_channels, out_channels, 1)\n', (4203, 4234), True, 'import torch.nn as nn\n'), ((4258, 4270), 'torch.nn.Dropout', 'nn.Dropout', ([], {}), '()\n', (4268, 4270), True, 'import torch.nn as nn\n'), ((4659, 4697), 'torch.nn.CrossEntropyLoss', 'nn.CrossEntropyLoss', ([], {'ignore_index': '(-100)'}), '(ignore_index=-100)\n', (4678, 4697), True, 'import torch.nn as nn\n'), ((4717, 4745), 'torch.nn.MSELoss', 'nn.MSELoss', ([], {'reduction': '"""none"""'}), "(reduction='none')\n", (4727, 4745), True, 'import torch.nn as nn\n'), ((2090, 2117), 'numpy.minimum', 'np.minimum', (['p_end[j]', 'y_end'], {}), '(p_end[j], y_end)\n', (2100, 2117), True, 'import numpy as np\n'), ((2120, 2151), 'numpy.maximum', 'np.maximum', (['p_start[j]', 'y_start'], {}), '(p_start[j], y_start)\n', (2130, 2151), True, 'import numpy as np\n'), ((2168, 2195), 'numpy.maximum', 'np.maximum', (['p_end[j]', 'y_end'], {}), '(p_end[j], y_end)\n', (2178, 2195), True, 'import numpy as np\n'), ((2198, 2229), 'numpy.minimum', 'np.minimum', (['p_start[j]', 'y_start'], {}), '(p_start[j], y_start)\n', (2208, 2229), True, 'import numpy as np\n'), ((6738, 6753), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (6751, 6753), False, 'import torch\n'), ((2386, 2399), 'numpy.array', 'np.array', (['IoU'], {}), '(IoU)\n', (2394, 2399), True, 'import numpy as np\n'), ((5954, 5988), 'torch.max', 'torch.max', (['predictions[-1].data', '(1)'], {}), '(predictions[-1].data, 1)\n', (5963, 5988), False, 'import torch\n'), ((7220, 7261), 'torch.tensor', 'torch.tensor', (['features'], {'dtype': 'torch.float'}), '(features, dtype=torch.float)\n', (7232, 7261), False, 'import torch\n'), ((7469, 7503), 'torch.max', 'torch.max', (['predictions[-1].data', '(1)'], {}), '(predictions[-1].data, 1)\n', (7478, 7503), False, 'import torch\n'), ((3167, 3188), 'torch.nn.functional.softmax', 'F.softmax', (['out'], {'dim': '(1)'}), '(out, dim=1)\n', (3176, 3188), True, 'import torch.nn.functional as F\n'), ((6117, 6141), 'torch.sum', 'torch.sum', (['mask[:, 0, :]'], {}), '(mask[:, 0, :])\n', (6126, 6141), False, 'import torch\n'), ((5702, 5735), 'torch.nn.functional.log_softmax', 'F.log_softmax', (['p[:, :, 1:]'], {'dim': '(1)'}), '(p[:, :, 1:], dim=1)\n', (5715, 5735), True, 'import torch.nn.functional as F\n')]
import os import csv import numpy as np import matplotlib.pyplot as plt from cached_property import cached_property from probez.spike_handling import waveforms, cluster_exceptions, cluster from probez.util import generic_functions from probez.sorting_quality import load_quality_measures from bisect import bisect_left # from analysis.probe.config import FS_probe class SpikeIo(object): """ class for loading and manipulating KiloSort output files and processed data example usage: >>> sp = SpikeIo(root, traces_path, n_chan) # create the SpikeStruct and load all variables >>> good_cluster_ids = sp.get_clusters_in_group('good') # get all the clusters in a specific group >>> depth_ordered_good_clusters = sp.sort_cluster_ids_by_depth(good_cluster_ids, descend=True) # order them """ def __init__(self, root, traces_path, n_chan, quality_path=None): self.n_chan = n_chan self.root = root self.traces_path = traces_path self.quality_path = quality_path load = self.load_data self.all_spike_times = np.array(generic_functions.flatten_list(load('spike_times'))) self.spike_clusters = load('spike_clusters') self.unique_cluster_ids = np.unique(self.spike_clusters) channel_positions = load('channel_positions') self.x_coords = channel_positions[:, 0] self.y_coords = channel_positions[:, 1] self.groups = self.read_groups() if self.read_groups() is not None: self.good_cluster_ids = self.get_clusters_in_group('good') self.MUA_cluster_ids = self.get_clusters_in_group('mua') self.noise_cluster_ids = self.get_clusters_in_group('noise') self.unsorted_cluster_ids = self.get_clusters_in_group('unsorted') if quality_path is not None: self.groups, self.contamination_rates, self.isi_violations, \ self.isolation_distances = load_quality_measures.load_from_matlab(quality_path) def load_data(self, name): path = os.path.join(self.root, name) + '.npy' if not os.path.isfile(path): raise cluster_exceptions.SpikeStructLoadDataError('file: {} does not exist'.format(path)) return np.load(path) @cached_property def traces(self): """ Traces_path should be the path to the raw or processed binary data. This is used primarily for extracting waveforms so it helps if the data are high pass filtered or processed in some way, but it shouldn't be essential :param limit: restrict the size of the data used to improve speed :return shaped_data: """ if not os.path.isfile(self.traces_path): raise cluster_exceptions.SpikeStructLoadDataError('file: {} does not exist'.format(self.traces_path)) data = np.memmap(self.traces_path, dtype=np.int16) if data.shape[0] % self.n_chan != 0: raise cluster_exceptions.IncorrectNchanTracesStructError(data.shape[0], self.n_chan) print('reshaping data... this may take a while') shape = (int(data.shape[0] / self.n_chan), self.n_chan) shaped_data = np.memmap(self.traces_path, shape=shape, dtype=np.int16) print('data reshaping completed! :)') return shaped_data def get_traces_median(self, n_samples=1500000): return np.median(self.traces[0:n_samples, :], axis=0) def read_groups(self): """ manual sorting output (from e.g. phy) is stored as cluster_groups.csv :return dictionary manually_labelled_cluster_groups: a dictionary of group_ids for every cluster """ cgrp_file, path = ['cluster_group.tsv', 'cluster_groups.csv'], None for cg_file in cgrp_file: path_nw = os.path.join(self.root, cg_file) if os.path.isfile(path_nw): path = path_nw break if path is None: print('no cluster groups file') return None with open(path, 'rt') as f: reader = csv.reader(f) manually_labelled_cluster_groups = {} for i, row in enumerate(reader): if i != 0: # skip first row (headers) cluster_id = row[0].split()[0] cluster_group = row[0].split()[1] manually_labelled_cluster_groups.setdefault(int(cluster_id), cluster_group) return manually_labelled_cluster_groups def get_clusters_in_group(self, group): """ :param group: the group that the user wants clusters from :return clusters: a list of all cluster_ids classified to a user defined group: """ if self.groups is None: return return [key for key in self.groups.keys() if self.groups[key] == group] def get_cluster_group_mask(self, group): # ? clusters = self.get_clusters_in_group(group) return [cid in clusters for cid in self.spike_clusters] def get_spike_times_in_interval(self, start_t, end_t, spike_times=None): """ :param start_t: start point (n_samples) :param end_t: end point (n_samples) :param spike_times: the set of spikes from which to get subset from :return spike_times: all spike times within a user specified interval """ if spike_times is None: spike_times = self.all_spike_times start_idx = bisect_left(spike_times, start_t) end_idx = bisect_left(spike_times, end_t) return spike_times[start_idx:end_idx] def get_spike_cluster_ids_in_interval(self, start_t, end_t, spike_times=None, spike_clusters=None): """ :param start_t: start point (n_samples) :param end_t: end point (n_samples) :param spike_clusters: the set of spikes from which to get subset from :param spike_times: :return spike_clusters: all cluster ids within a user specified interval """ if spike_times is None: spike_times = self.all_spike_times if spike_clusters is None: spike_clusters = self.spike_clusters start_idx = bisect_left(spike_times, start_t) end_idx = bisect_left(spike_times, end_t) return spike_clusters[start_idx:end_idx] def get_spike_times_in_cluster(self, cluster_id): """ :param int cluster_id: :return spike times: an array of all spike times within a user specified cluster """ return self.all_spike_times[self.spikes_in_cluster_mask(cluster_id)] def spikes_in_cluster_mask(self, cluster_id): """ a boolean mask of all indices of spikes that belong to a group of user defined clusters :param int cluster_id: :return: """ return self.spike_clusters == cluster_id def cluster_spike_times_in_interval(self, cluster_id, start, end, spike_times=None, spike_clusters=None): if spike_times is None: spike_times = self.all_spike_times spike_clusters = self.spike_clusters spike_times_in_interval = self.get_spike_times_in_interval(start, end, spike_times) cluster_ids_in_interval = self.get_spike_cluster_ids_in_interval(start, end, spike_times, spike_clusters) spikes_in_cluster_and_interval = spike_times_in_interval[cluster_ids_in_interval == cluster_id] return spikes_in_cluster_and_interval # def cluster_spike_times_in_interval_time(self, cluster_id, start, end, spike_times=None, spike_clusters=None): # return self.cluster_spike_times_in_interval(cluster_id, start, end, spike_times, spike_clusters) / FS_probe def sort_cluster_ids_by_depth(self, cluster_ids=None, cluster_depths=None, descend=True): """ :param cluster_ids: :param cluster_depths: :param descend: if descending order is required then set this to true :return: """ if cluster_ids is None: cluster_ids = self.good_cluster_ids if cluster_depths is None: cluster_depths = self.get_cluster_depths sorted_cluster_ids, cluster_depths = generic_functions.sort_by(cluster_ids, cluster_depths, descend=descend) return sorted_cluster_ids, cluster_depths def plot_probe_as_image(self, start, end): plt.imshow(self.traces[start:end, :].T, aspect='auto', origin=0) def get_channel_spike_counts(self, cluster_ids, start, end): """ clusters are allocated to their 'best channel' using the average waveforms of their spikes the number of spikes in each channel is then computed and returned :param cluster_ids: :param start: the start of the window in which you want to count spikes :param end: the end of the window in which you want to count spikes :return spike_counts: the number of spikes in the window for each cluster in each channel on the probe """ spike_counts = np.zeros(self.n_chan) for cluster_id in cluster_ids: depth = self.get_cluster_channel_from_avg_waveforms(cluster_id) cluster_spikes = self.cluster_spike_times_in_interval(cluster_id, start, end) spike_counts[depth] += len(cluster_spikes) return spike_counts def clusters_in_depth_range(self, lower, upper, cluster_ids=None): if cluster_ids is None: cluster_ids = self.good_cluster_ids cluster_ids = np.array(cluster_ids) clusters = [cluster.Cluster(cid) for cid in cluster_ids] cluster_channels = np.array([c.best_channel for c in clusters]) return self.good_cluster_ids[np.logical_and(cluster_channels > lower, cluster_channels < upper)] def get_clusters_in_depth_range(self, cluster_ids, lower, upper): """ :param cluster_ids: :param lower: the lower layer (channel) bound :param upper: the upper layer (channel) bound :return cluster_ids: a list of clusters within the two bounds """ cluster_depths = self.get_cluster_depths(cluster_ids) clusters_in_depth_range = [idx for idx, depth in zip(cluster_ids, cluster_depths) if lower < depth < upper] return clusters_in_depth_range def get_cluster_depths(self, cluster_ids): cluster_depths = [] for cluster_id in cluster_ids: cluster_depth = self.get_cluster_channel_from_avg_waveforms([cluster_id]) cluster_depths.append(cluster_depth) return cluster_depths def get_cluster_channel_from_avg_waveforms(self, cluster_id, n_spikes=100): """ :param cluster_id: :param n_spikes: number of spikes used to form average waveform :return: """ spike_times = self.get_spike_times_in_cluster(cluster_id) cluster_channel = waveforms.get_channel_of_max_amplitude_avg_waveform(spike_times[:n_spikes], self.traces, self.n_chan) return cluster_channel
[ "numpy.load", "csv.reader", "os.path.join", "probez.sorting_quality.load_quality_measures.load_from_matlab", "probez.spike_handling.cluster_exceptions.IncorrectNchanTracesStructError", "numpy.median", "matplotlib.pyplot.imshow", "probez.spike_handling.cluster.Cluster", "numpy.logical_and", "numpy....
[((1242, 1272), 'numpy.unique', 'np.unique', (['self.spike_clusters'], {}), '(self.spike_clusters)\n', (1251, 1272), True, 'import numpy as np\n'), ((2258, 2271), 'numpy.load', 'np.load', (['path'], {}), '(path)\n', (2265, 2271), True, 'import numpy as np\n'), ((2856, 2899), 'numpy.memmap', 'np.memmap', (['self.traces_path'], {'dtype': 'np.int16'}), '(self.traces_path, dtype=np.int16)\n', (2865, 2899), True, 'import numpy as np\n'), ((3185, 3241), 'numpy.memmap', 'np.memmap', (['self.traces_path'], {'shape': 'shape', 'dtype': 'np.int16'}), '(self.traces_path, shape=shape, dtype=np.int16)\n', (3194, 3241), True, 'import numpy as np\n'), ((3383, 3429), 'numpy.median', 'np.median', (['self.traces[0:n_samples, :]'], {'axis': '(0)'}), '(self.traces[0:n_samples, :], axis=0)\n', (3392, 3429), True, 'import numpy as np\n'), ((5459, 5492), 'bisect.bisect_left', 'bisect_left', (['spike_times', 'start_t'], {}), '(spike_times, start_t)\n', (5470, 5492), False, 'from bisect import bisect_left\n'), ((5511, 5542), 'bisect.bisect_left', 'bisect_left', (['spike_times', 'end_t'], {}), '(spike_times, end_t)\n', (5522, 5542), False, 'from bisect import bisect_left\n'), ((6182, 6215), 'bisect.bisect_left', 'bisect_left', (['spike_times', 'start_t'], {}), '(spike_times, start_t)\n', (6193, 6215), False, 'from bisect import bisect_left\n'), ((6234, 6265), 'bisect.bisect_left', 'bisect_left', (['spike_times', 'end_t'], {}), '(spike_times, end_t)\n', (6245, 6265), False, 'from bisect import bisect_left\n'), ((8182, 8253), 'probez.util.generic_functions.sort_by', 'generic_functions.sort_by', (['cluster_ids', 'cluster_depths'], {'descend': 'descend'}), '(cluster_ids, cluster_depths, descend=descend)\n', (8207, 8253), False, 'from probez.util import generic_functions\n'), ((8360, 8424), 'matplotlib.pyplot.imshow', 'plt.imshow', (['self.traces[start:end, :].T'], {'aspect': '"""auto"""', 'origin': '(0)'}), "(self.traces[start:end, :].T, aspect='auto', origin=0)\n", (8370, 8424), True, 'import matplotlib.pyplot as plt\n'), ((9008, 9029), 'numpy.zeros', 'np.zeros', (['self.n_chan'], {}), '(self.n_chan)\n', (9016, 9029), True, 'import numpy as np\n'), ((9495, 9516), 'numpy.array', 'np.array', (['cluster_ids'], {}), '(cluster_ids)\n', (9503, 9516), True, 'import numpy as np\n'), ((9609, 9653), 'numpy.array', 'np.array', (['[c.best_channel for c in clusters]'], {}), '([c.best_channel for c in clusters])\n', (9617, 9653), True, 'import numpy as np\n'), ((10871, 10976), 'probez.spike_handling.waveforms.get_channel_of_max_amplitude_avg_waveform', 'waveforms.get_channel_of_max_amplitude_avg_waveform', (['spike_times[:n_spikes]', 'self.traces', 'self.n_chan'], {}), '(spike_times[:n_spikes],\n self.traces, self.n_chan)\n', (10922, 10976), False, 'from probez.spike_handling import waveforms, cluster_exceptions, cluster\n'), ((1965, 2017), 'probez.sorting_quality.load_quality_measures.load_from_matlab', 'load_quality_measures.load_from_matlab', (['quality_path'], {}), '(quality_path)\n', (2003, 2017), False, 'from probez.sorting_quality import load_quality_measures\n'), ((2065, 2094), 'os.path.join', 'os.path.join', (['self.root', 'name'], {}), '(self.root, name)\n', (2077, 2094), False, 'import os\n'), ((2119, 2139), 'os.path.isfile', 'os.path.isfile', (['path'], {}), '(path)\n', (2133, 2139), False, 'import os\n'), ((2693, 2725), 'os.path.isfile', 'os.path.isfile', (['self.traces_path'], {}), '(self.traces_path)\n', (2707, 2725), False, 'import os\n'), ((2963, 3041), 'probez.spike_handling.cluster_exceptions.IncorrectNchanTracesStructError', 'cluster_exceptions.IncorrectNchanTracesStructError', (['data.shape[0]', 'self.n_chan'], {}), '(data.shape[0], self.n_chan)\n', (3013, 3041), False, 'from probez.spike_handling import waveforms, cluster_exceptions, cluster\n'), ((3799, 3831), 'os.path.join', 'os.path.join', (['self.root', 'cg_file'], {}), '(self.root, cg_file)\n', (3811, 3831), False, 'import os\n'), ((3847, 3870), 'os.path.isfile', 'os.path.isfile', (['path_nw'], {}), '(path_nw)\n', (3861, 3870), False, 'import os\n'), ((4076, 4089), 'csv.reader', 'csv.reader', (['f'], {}), '(f)\n', (4086, 4089), False, 'import csv\n'), ((9537, 9557), 'probez.spike_handling.cluster.Cluster', 'cluster.Cluster', (['cid'], {}), '(cid)\n', (9552, 9557), False, 'from probez.spike_handling import waveforms, cluster_exceptions, cluster\n'), ((9692, 9758), 'numpy.logical_and', 'np.logical_and', (['(cluster_channels > lower)', '(cluster_channels < upper)'], {}), '(cluster_channels > lower, cluster_channels < upper)\n', (9706, 9758), True, 'import numpy as np\n')]
"""Anglit distribution.""" import numpy from ..baseclass import Dist from ..operators.addition import Add class anglit(Dist): """Anglit distribution.""" def __init__(self): Dist.__init__(self) def _pdf(self, x): return numpy.cos(2*x) def _cdf(self, x): return numpy.sin(x+numpy.pi/4)**2.0 def _ppf(self, q): return (numpy.arcsin(numpy.sqrt(q))-numpy.pi/4) def _lower(self): return -numpy.pi/4 def _upper(self): return numpy.pi/4 class Anglit(Add): """ Anglit distribution. Args: loc (float, Dist): Location parameter scale (float, Dist): Scaling parameter Examples: >>> distribution = chaospy.Anglit(2, 4) >>> distribution Anglit(loc=2, scale=4) >>> q = numpy.linspace(0, 1, 5) >>> distribution.inv(q).round(4) array([-1.1416, 0.9528, 2. , 3.0472, 5.1416]) >>> distribution.fwd(distribution.inv(q)).round(4) array([0. , 0.25, 0.5 , 0.75, 1. ]) >>> distribution.pdf(distribution.inv(q)).round(4) array([0. , 0.2165, 0.25 , 0.2165, 0. ]) >>> distribution.sample(4).round(4) array([2.6245, 0.2424, 4.2421, 1.9288]) >>> distribution.mom([1, 2, 3]).round(4) array([ 2. , 5.8696, 19.2176]) """ def __init__(self, loc=0, scale=1): self._repr = {"scale": scale, "loc": loc} Add.__init__(self, left=anglit()*scale, right=loc)
[ "numpy.sin", "numpy.cos", "numpy.sqrt" ]
[((252, 268), 'numpy.cos', 'numpy.cos', (['(2 * x)'], {}), '(2 * x)\n', (261, 268), False, 'import numpy\n'), ((306, 333), 'numpy.sin', 'numpy.sin', (['(x + numpy.pi / 4)'], {}), '(x + numpy.pi / 4)\n', (315, 333), False, 'import numpy\n'), ((388, 401), 'numpy.sqrt', 'numpy.sqrt', (['q'], {}), '(q)\n', (398, 401), False, 'import numpy\n')]
#!\usr\bin\python # coding=utf-8 # Author: youngfeng # Update: 07/17/2018 """ This code is used to find the lowest rank in validation pool (top-10) by using flash method """ import sys sys.path.append("../") import os from Flash import find_lowest_rank from Flash import predict_by_flash from Flash import split_data_by_fraction import numpy as np if __name__ == "__main__": projs = ["../data/"+name for name in os.listdir("../data") if ".csv" in name] ave_rank_lst = [] for proj in projs: print(proj) ave_top_10_act_rank = [] for round in range(50): # print(">> Using FLASH Method to Predict the Validation Pool\n") # select 80% data dataset = split_data_by_fraction(proj, 0.8) # print("### initialzation") # for i in dataset: # print(str(i.index), ",", end="") # print("\n-------------") data = predict_by_flash(dataset) # print("### finally split") train_set = data[0] uneval_set = data[1] # for i in train_set: # print(str(i.index), ",", end="") # print("\n-------------") # for i in uneval_set: # print(str(i.index), ",", end="") # print("\n-------------") lowest_rank = find_lowest_rank(train_set, uneval_set) ave_top_10_act_rank.append(lowest_rank) print("[mini rank]: ", ave_top_10_act_rank) minest_rank = np.mean(ave_top_10_act_rank) print("[mean rank]: ", minest_rank, "\n") ave_rank_lst.append(minest_rank) print("-------------------------------") print(ave_rank_lst)
[ "sys.path.append", "Flash.predict_by_flash", "numpy.mean", "Flash.find_lowest_rank", "Flash.split_data_by_fraction", "os.listdir" ]
[((187, 209), 'sys.path.append', 'sys.path.append', (['"""../"""'], {}), "('../')\n", (202, 209), False, 'import sys\n'), ((1302, 1330), 'numpy.mean', 'np.mean', (['ave_top_10_act_rank'], {}), '(ave_top_10_act_rank)\n', (1309, 1330), True, 'import numpy as np\n'), ((417, 438), 'os.listdir', 'os.listdir', (['"""../data"""'], {}), "('../data')\n", (427, 438), False, 'import os\n'), ((674, 707), 'Flash.split_data_by_fraction', 'split_data_by_fraction', (['proj', '(0.8)'], {}), '(proj, 0.8)\n', (696, 707), False, 'from Flash import split_data_by_fraction\n'), ((842, 867), 'Flash.predict_by_flash', 'predict_by_flash', (['dataset'], {}), '(dataset)\n', (858, 867), False, 'from Flash import predict_by_flash\n'), ((1155, 1194), 'Flash.find_lowest_rank', 'find_lowest_rank', (['train_set', 'uneval_set'], {}), '(train_set, uneval_set)\n', (1171, 1194), False, 'from Flash import find_lowest_rank\n')]
""".. Copyright (c) 2014-2017, Magni developers. All rights reserved. See LICENSE.rst for further information. Module for wrapping the Magni IPython Notebook examples. **This module is based on the "ipnbdoctest.py" script by <NAME> (MinRK)**, source: https://gist.github.com/minrk/2620735. This assumes comparison of IPython Notebooks in nbformat.v3 """ from __future__ import division, print_function import base64 from datetime import datetime import os import platform import shutil import subprocess import sys import unittest import types import warnings try: from Queue import Empty # Python 2 except ImportError: from queue import Empty # Python 3 try: from StringIO import StringIO as BytesIO # Python 2 except ImportError: from io import BytesIO # Python 3 import numpy as np from pkg_resources import parse_version import scipy.misc import magni # The great "support IPython 2, 3, 4" strat begins import IPython try: import jupyter except ImportError: jupyter_era = False else: jupyter_era = True if jupyter_era: # Jupyter / IPython 4.x from jupyter_client import KernelManager from nbformat import reads, NotebookNode def mod_reads(file_): return reads(file_, 3) # Read notebooks as v3 else: from IPython.kernel import KernelManager with warnings.catch_warnings(): warnings.simplefilter('error') try: # IPython 2.x from IPython.nbformat.current import reads, NotebookNode def mod_reads(file_): return reads(file_, 'json') except UserWarning: # IPython 3.x from IPython.nbformat import reads, NotebookNode def mod_reads(file_): return reads(file_, 3) # Read notebooks as v3 # End of the great "support IPython 2, 3, 4" strat # Test for freetype library version try: if parse_version( subprocess.check_output( ['freetype-config', '--ftversion']).decode().strip() ) <= parse_version('2.5.2'): _skip_display_data_tests = False else: _skip_display_data_tests = True except OSError: _skip_display_data_tests = True if _skip_display_data_tests: warnings.warn('Skipping display data ipynb tests.', RuntimeWarning) class _Meta(type): """ Identification of IPython Notebook examples and construction of test class. """ def __new__(class_, name, bases, attrs): path = magni.__path__[0].rsplit(os.sep, 1)[0] path = path + os.path.sep + 'examples' + os.path.sep for filename in os.listdir(path): if (platform.system() == 'Darwin' and sys.version_info.major == 3 and sys.version_info.minor == 3 and filename == 'utils-multiprocessing.ipynb'): # Skip the broken multiprocessing on OSX Python 3.3 since case warnings.warn( 'Skipping multiprocessing ipynb test.', RuntimeWarning) continue if filename[-6:] == '.ipynb': name = 'test_' + filename[:-6].replace('-', '_') func = attrs['_run_example'] func = types.FunctionType(func.__code__, func.__globals__, name, (path + filename,)) func.__doc__ = func.__doc__.format(filename) attrs[name] = func return type.__new__(class_, name, bases, attrs) # For python 2 and 3 compatibility class _Hack(_Meta): def __new__(class_, name, bases, attrs): return _Meta(name, (unittest.TestCase,), attrs) _TestCase = type.__new__(_Hack, 'temp', (), {}) @unittest.skipIf( parse_version(IPython.__version__) <= parse_version('3.0') and sys.version_info.major == 2 and platform.system() == 'Darwin', 'Due to a problem in IPython, the Magni ' + 'Notebook example tests stall on Mac OSX with IPython 2 and Python 2.') class TestIPythonExamples(_TestCase): """ Test of Ipython Notebook examples for equality of output to reference. """ def setUp(self): """ Identify IPython Notebook examples to run. """ path = magni.__path__[0].rsplit(os.sep, 1)[0] path = path + os.path.sep + 'examples' + os.path.sep files_to_copy = ['example.mi', 'data.hdf5', 'display.py'] for cfile in files_to_copy: shutil.copy(os.path.join(path, cfile), '.') def _run_example(self, ipynb): """ Test of {} Magni IPython Notebook example. """ with open(ipynb) as f_ipynb: notebook = mod_reads(f_ipynb.read()) notebook_result = _check_ipynb(notebook) passed, successes, failures, errors, report = notebook_result self.assertTrue(passed, msg=report) error_msg = ('Magni IPython Notebook example status:\n' + 'Successes: {}, Failures: {}, Errors: {}').format( successes, failures, errors) self.assertEqual(errors + failures, 0, msg=error_msg) def _check_ipynb(notebook): """ Check an IPython Notebook for matching input and output. Each cell input in the `notebook` is executed and the result is compared to the cell output saved in the `notebook`. Parameters ---------- notebook : IPython.nbformat.current.NotebookNode The notebook to check for matching input and output. Returns ------- passed : Bool The indicator of a successful check (or not). sucessess : int The number of cell outputs that matched. failures : int The number of cell outputs that failed to match. errors : int The number of cell executions that resulted in errors. report : str The report detailing possible failures and errors. """ kernel_manager = KernelManager() kernel_manager.start_kernel() kernel_client = kernel_manager.client() kernel_client.start_channels() try: # IPython 3.x kernel_client.wait_for_ready() iopub = kernel_client shell = kernel_client except AttributeError: # Ipython 2.x # Based on https://github.com/paulgb/runipy/pull/49/files iopub = kernel_client.iopub_channel shell = kernel_client.shell_channel shell.get_shell_msg = shell.get_msg iopub.get_iopub_msg = iopub.get_msg successes = 0 failures = 0 errors = 0 report = '' for worksheet in notebook.worksheets: for cell in worksheet.cells: if cell.cell_type == 'code': try: test_results = _execute_cell(cell, shell, iopub) except RuntimeError as e: report += ('{!s} in cell number: {}' .format(e, cell.prompt_number)) errors += 1 break identical_output = all( [_compare_cell_output(test_result, reference) for test_result, reference in zip(test_results, cell.outputs)]) if identical_output: successes += 1 else: failures += 1 try: str_test_results = [ '(for out {})\n'.format(k) + '\n'.join( [' : '.join([str(key), str(val)]) for key, val in t.items() if key not in ('metadata', 'png')] ) for k, t in enumerate(test_results)] str_cell_outputs = [ '(for out {})\n'.format(k) + '\n'.join( [' : '.join([str(key), str(val)]) for key, val in t.items() if key not in ('metadata', 'png')] ) for k, t in enumerate(cell.outputs)] except TypeError as e: report += 'TypeError in ipynb_examples test\n\n' for entry in cell.outputs: if 'traceback' in entry.keys(): for item in entry['traceback']: report += str(item) + '\n' else: report += '\n' * 2 + '~' * 40 report += ( '\nFailure in {}:{}\nGot: {}\n\n\nExpected: {}' ).format(notebook.metadata.name, cell.prompt_number, '\n'.join(str_test_results), '\n'.join(str_cell_outputs)) kernel_client.stop_channels() kernel_manager.shutdown_kernel() passed = not (failures or errors) return passed, successes, failures, errors, report def _compare_cell_output(test_result, reference): """ Compare a cell test output to a reference output. Parameters ---------- test_results : IPython.nbformat.current.NotebookNode The cell test result that must be compared to the reference. reference : IPython.nbformat.current.NotebookNode The reference cell output to compare to. Returns ------- comparison_result : bool The indicator of equality between the test output and the reference. """ skip_compare = ['traceback', 'latex', 'prompt_number'] if _skip_display_data_tests: # Skip graphics comparison skip_compare.append('png') if test_result['output_type'] == 'display_data': # Prevent comparison of matplotlib figure instance memory addresses skip_compare.append('text') skip_compare.append('metadata') for key in reference: if key not in test_result: raise Exception(str(reference) + '!!!!!' + str(test_result)) return False elif key not in skip_compare: if key == 'text': if test_result[key].strip() != reference[key].strip(): return False elif key == 'png': reference_img = reference[key] test_img = test_result[key] if not _compare_images(reference_img, test_img): return False else: if test_result[key] != reference[key]: return False return True def _compare_images(reference_img, test_img): """ Compare reference and test image to determine if they depict the same. Two images are considered to depict the same unless: - The image shapes differ - The number of differences in non-transparant pixel values which are not (likely to be) part of the image border exceeds 2. Parameters ---------- reference_img : str The base64 encoded reference image. test_img : str The base64 encoded test image. Returns ------- comparison_result : bool The idenfifier of a positive match, i.e. True if images are the same. """ ref_png = base64.b64decode(reference_img) ref_ndarray = scipy.misc.imread(BytesIO(ref_png)) cmp_png = base64.b64decode(test_img) cmp_ndarray = scipy.misc.imread(BytesIO(cmp_png)) # check shape of images if cmp_ndarray.shape != ref_ndarray.shape: print('Image shapes differ') return False # mask of channels in pixels with different values diff = cmp_ndarray != ref_ndarray # mask of pixels with different values diff = np.any(diff, axis=2) # mask of non-transparent pixels with different values diff = diff * np.bool_(ref_ndarray[:, :, 3]) # check if all non-transparent pixels match if diff.sum() == 0: # Accept difference in tranparent pixels return True # The rest is all about checking if (it is likely to be) only the image # border that has changed. The border may render differently across # matplotlib versions. # mask of black pixels mask = ((ref_ndarray[:, :, 0] == 0) * (ref_ndarray[:, :, 1] == 0) * (ref_ndarray[:, :, 2] == 0) * (ref_ndarray[:, :, 3] == 255)) # lookup table of the top most connected black pixel of the # looked up pixel C_N = np.zeros(mask.shape, dtype=np.int16) for i in range(0, mask.shape[0] - 1): C_N[i + 1, :] = np.logical_not(mask[i, :]) * i + mask[i, :] * C_N[i, :] # lookup table of the right most connected black pixel of the # looked up pixel C_E = np.zeros(mask.shape, dtype=np.int16) for i in range(mask.shape[1] - 1, 0, -1): C_E[:, i - 1] = np.logical_not(mask[:, i]) * i + mask[:, i] * C_E[:, i] # lookup table of the bottom most connected black pixel of the # looked up pixel C_S = np.zeros(mask.shape, dtype=np.int16) for i in range(mask.shape[0] - 1, 0, -1): C_S[i - 1, :] = np.logical_not(mask[i, :]) * i + mask[i, :] * C_S[i, :] # lookup table of the left most connected black pixel of the # looked up pixel C_W = np.zeros(mask.shape, dtype=np.int16) for i in range(0, mask.shape[1] - 1): C_W[:, i + 1] = np.logical_not(mask[:, i]) * i + mask[:, i] * C_W[:, i] # coordinates of non-transparent pixels with different values points = np.nonzero(diff) points = np.int32(points + (np.zeros(points[0].shape),)).T # loop over non-transparent pixels with different values for i, point in enumerate(points): y, x = point[:2] # find other non-transparent pixels with different values # ... with the same y-coordinate matches_y = np.nonzero(points[:, 0] == y)[0] # ... with an x-coordinate at least 10 pixels away matches_y = matches_y[np.abs(points[matches_y, 1] - x) > 10] # ... which is connected by black pixels matches_y = matches_y[ (points[matches_y, 1] >= C_W[y, x]) * (points[matches_y, 1] <= C_E[y, x])] # find other non-transparent pixels with different values # ... with the same x-coordinate matches_x = np.nonzero(points[:, 1] == x)[0] # ... with a y-coordinate at least 10 pixels away matches_x = matches_x[np.abs(points[matches_x, 0] - y) > 10] # ... which is connected by black pixels matches_x = matches_x[ (points[matches_x, 0] >= C_N[y, x]) * (points[matches_x, 0] <= C_S[y, x])] if len(matches_y) + len(matches_x) == 0: # this pixel cannot be the corner of a box break for j in matches_y: for k in matches_x: # loop over combinations of possible boxes y_test = points[k, 0] x_test = points[j, 1] if not C_W[y_test, x] <= x_test <= C_E[y_test, x]: # one horizontal line of the box isn't black continue if not C_N[y, x_test] <= y_test <= C_S[y, x_test]: # one vertical line of the box isn't black continue # the box is a box and the corners are flagged points[i, 2] = points[j, 2] = points[k, 2] = 1 if points.shape[0] - np.sum(points[:, 2]) > 2: print('The images differ by {} pixels'.format( points.shape[0] - np.sum(points[:, 2]))) # Save images and their difference for visual inspection fail_txt = 'Notebook test fail ' utcnow = datetime.utcnow scipy.misc.imsave(fail_txt + str(utcnow()) + 'r' + '.png', ref_ndarray) scipy.misc.imsave(fail_txt + str(utcnow()) + 't' + '.png', cmp_ndarray) img_diff = cmp_ndarray - ref_ndarray scipy.misc.imsave(fail_txt + str(utcnow()) + 'd' + '.png', img_diff) return False return True def _execute_cell(cell, shell, iopub, timeout=300): """ Execute an IPython Notebook Cell and return the cell output. Parameters ---------- cell : IPython.nbformat.current.NotebookNode The IPython Notebook cell to execute. shell : IPython.kernel.blocking.channels.BlockingShellChannel The shell channel which the cell is submitted to for execution. iopub : IPython.kernel.blocking.channels.BlockingIOPubChannel The iopub channel used to retrieve the result of the execution. timeout : int The number of seconds to wait for the execution to finish before giving up. Returns ------- cell_outputs : list The list of NotebookNodes holding the result of the execution. """ # Execute input shell.execute(cell.input) exe_result = shell.get_shell_msg(timeout=timeout) if exe_result['content']['status'] == 'error': raise RuntimeError('Failed to execute cell due to error: {!r}'.format( str(exe_result['content']['evalue']))) cell_outputs = list() # Poll for iopub messages until no more messages are available while True: try: msg = iopub.get_iopub_msg(timeout=0.5) except Empty: break msg_type = msg['msg_type'] if msg_type in ('status', 'pyin', 'execute_input', 'execute_result'): continue content = msg['content'] node = NotebookNode(output_type=msg_type) if msg_type == 'stream': node.stream = content['name'] if 'text' in content: # v4 notebook format node.text = content['text'] else: # v3 notebook format node.text = content['data'] bug_text = 'Using Anaconda Cloud api site https://api.anaconda.org' if bug_text in node.text: # Ignore conda (spam) messages/warnings continue elif msg_type in ('display_data', 'pyout'): node['metadata'] = content['metadata'] for mime, data in content['data'].items(): attr = mime.split('/')[-1].lower() attr = attr.replace('+xml', '').replace('plain', 'text') setattr(node, attr, data) if msg_type == 'pyout': node.prompt_number = content['execution_count'] elif msg_type == 'pyerr': node.ename = content['ename'] node.evalue = content['evalue'] node.traceback = content['traceback'] else: raise RuntimeError('Unhandled iopub message of type: {}'.format( msg_type)) cell_outputs.append(node) return cell_outputs
[ "numpy.bool_", "numpy.sum", "numpy.abs", "base64.b64decode", "os.path.join", "IPython.nbformat.NotebookNode", "warnings.simplefilter", "numpy.logical_not", "warnings.catch_warnings", "io.BytesIO", "subprocess.check_output", "IPython.nbformat.reads", "platform.system", "os.listdir", "pkg_...
[((2244, 2311), 'warnings.warn', 'warnings.warn', (['"""Skipping display data ipynb tests."""', 'RuntimeWarning'], {}), "('Skipping display data ipynb tests.', RuntimeWarning)\n", (2257, 2311), False, 'import warnings\n'), ((5917, 5932), 'IPython.kernel.KernelManager', 'KernelManager', ([], {}), '()\n', (5930, 5932), False, 'from IPython.kernel import KernelManager\n'), ((11255, 11286), 'base64.b64decode', 'base64.b64decode', (['reference_img'], {}), '(reference_img)\n', (11271, 11286), False, 'import base64\n'), ((11355, 11381), 'base64.b64decode', 'base64.b64decode', (['test_img'], {}), '(test_img)\n', (11371, 11381), False, 'import base64\n'), ((11718, 11738), 'numpy.any', 'np.any', (['diff'], {'axis': '(2)'}), '(diff, axis=2)\n', (11724, 11738), True, 'import numpy as np\n'), ((12459, 12495), 'numpy.zeros', 'np.zeros', (['mask.shape'], {'dtype': 'np.int16'}), '(mask.shape, dtype=np.int16)\n', (12467, 12495), True, 'import numpy as np\n'), ((12718, 12754), 'numpy.zeros', 'np.zeros', (['mask.shape'], {'dtype': 'np.int16'}), '(mask.shape, dtype=np.int16)\n', (12726, 12754), True, 'import numpy as np\n'), ((12982, 13018), 'numpy.zeros', 'np.zeros', (['mask.shape'], {'dtype': 'np.int16'}), '(mask.shape, dtype=np.int16)\n', (12990, 13018), True, 'import numpy as np\n'), ((13244, 13280), 'numpy.zeros', 'np.zeros', (['mask.shape'], {'dtype': 'np.int16'}), '(mask.shape, dtype=np.int16)\n', (13252, 13280), True, 'import numpy as np\n'), ((13484, 13500), 'numpy.nonzero', 'np.nonzero', (['diff'], {}), '(diff)\n', (13494, 13500), True, 'import numpy as np\n'), ((1236, 1251), 'IPython.nbformat.reads', 'reads', (['file_', '(3)'], {}), '(file_, 3)\n', (1241, 1251), False, 'from IPython.nbformat import reads, NotebookNode\n'), ((1337, 1362), 'warnings.catch_warnings', 'warnings.catch_warnings', ([], {}), '()\n', (1360, 1362), False, 'import warnings\n'), ((1372, 1402), 'warnings.simplefilter', 'warnings.simplefilter', (['"""error"""'], {}), "('error')\n", (1393, 1402), False, 'import warnings\n'), ((2043, 2065), 'pkg_resources.parse_version', 'parse_version', (['"""2.5.2"""'], {}), "('2.5.2')\n", (2056, 2065), False, 'from pkg_resources import parse_version\n'), ((2616, 2632), 'os.listdir', 'os.listdir', (['path'], {}), '(path)\n', (2626, 2632), False, 'import os\n'), ((11323, 11339), 'io.BytesIO', 'BytesIO', (['ref_png'], {}), '(ref_png)\n', (11330, 11339), False, 'from io import BytesIO\n'), ((11418, 11434), 'io.BytesIO', 'BytesIO', (['cmp_png'], {}), '(cmp_png)\n', (11425, 11434), False, 'from io import BytesIO\n'), ((11816, 11846), 'numpy.bool_', 'np.bool_', (['ref_ndarray[:, :, 3]'], {}), '(ref_ndarray[:, :, 3])\n', (11824, 11846), True, 'import numpy as np\n'), ((17467, 17501), 'IPython.nbformat.NotebookNode', 'NotebookNode', ([], {'output_type': 'msg_type'}), '(output_type=msg_type)\n', (17479, 17501), False, 'from IPython.nbformat import reads, NotebookNode\n'), ((3743, 3777), 'pkg_resources.parse_version', 'parse_version', (['IPython.__version__'], {}), '(IPython.__version__)\n', (3756, 3777), False, 'from pkg_resources import parse_version\n'), ((3781, 3801), 'pkg_resources.parse_version', 'parse_version', (['"""3.0"""'], {}), "('3.0')\n", (3794, 3801), False, 'from pkg_resources import parse_version\n'), ((3846, 3863), 'platform.system', 'platform.system', ([], {}), '()\n', (3861, 3863), False, 'import platform\n'), ((13818, 13847), 'numpy.nonzero', 'np.nonzero', (['(points[:, 0] == y)'], {}), '(points[:, 0] == y)\n', (13828, 13847), True, 'import numpy as np\n'), ((14286, 14315), 'numpy.nonzero', 'np.nonzero', (['(points[:, 1] == x)'], {}), '(points[:, 1] == x)\n', (14296, 14315), True, 'import numpy as np\n'), ((15419, 15439), 'numpy.sum', 'np.sum', (['points[:, 2]'], {}), '(points[:, 2])\n', (15425, 15439), True, 'import numpy as np\n'), ((1569, 1589), 'IPython.nbformat.reads', 'reads', (['file_', '"""json"""'], {}), "(file_, 'json')\n", (1574, 1589), False, 'from IPython.nbformat import reads, NotebookNode\n'), ((2947, 3016), 'warnings.warn', 'warnings.warn', (['"""Skipping multiprocessing ipynb test."""', 'RuntimeWarning'], {}), "('Skipping multiprocessing ipynb test.', RuntimeWarning)\n", (2960, 3016), False, 'import warnings\n'), ((3238, 3315), 'types.FunctionType', 'types.FunctionType', (['func.__code__', 'func.__globals__', 'name', '(path + filename,)'], {}), '(func.__code__, func.__globals__, name, (path + filename,))\n', (3256, 3315), False, 'import types\n'), ((4468, 4493), 'os.path.join', 'os.path.join', (['path', 'cfile'], {}), '(path, cfile)\n', (4480, 4493), False, 'import os\n'), ((12563, 12589), 'numpy.logical_not', 'np.logical_not', (['mask[i, :]'], {}), '(mask[i, :])\n', (12577, 12589), True, 'import numpy as np\n'), ((12826, 12852), 'numpy.logical_not', 'np.logical_not', (['mask[:, i]'], {}), '(mask[:, i])\n', (12840, 12852), True, 'import numpy as np\n'), ((13090, 13116), 'numpy.logical_not', 'np.logical_not', (['mask[i, :]'], {}), '(mask[i, :])\n', (13104, 13116), True, 'import numpy as np\n'), ((13348, 13374), 'numpy.logical_not', 'np.logical_not', (['mask[:, i]'], {}), '(mask[:, i])\n', (13362, 13374), True, 'import numpy as np\n'), ((13940, 13972), 'numpy.abs', 'np.abs', (['(points[matches_y, 1] - x)'], {}), '(points[matches_y, 1] - x)\n', (13946, 13972), True, 'import numpy as np\n'), ((14407, 14439), 'numpy.abs', 'np.abs', (['(points[matches_x, 0] - y)'], {}), '(points[matches_x, 0] - y)\n', (14413, 14439), True, 'import numpy as np\n'), ((1764, 1779), 'IPython.nbformat.reads', 'reads', (['file_', '(3)'], {}), '(file_, 3)\n', (1769, 1779), False, 'from IPython.nbformat import reads, NotebookNode\n'), ((2650, 2667), 'platform.system', 'platform.system', ([], {}), '()\n', (2665, 2667), False, 'import platform\n'), ((13533, 13558), 'numpy.zeros', 'np.zeros', (['points[0].shape'], {}), '(points[0].shape)\n', (13541, 13558), True, 'import numpy as np\n'), ((15530, 15550), 'numpy.sum', 'np.sum', (['points[:, 2]'], {}), '(points[:, 2])\n', (15536, 15550), True, 'import numpy as np\n'), ((1932, 1991), 'subprocess.check_output', 'subprocess.check_output', (["['freetype-config', '--ftversion']"], {}), "(['freetype-config', '--ftversion'])\n", (1955, 1991), False, 'import subprocess\n')]
from __future__ import print_function, division import numpy as np import six from astropy import units as u from ..util.integrate import integrate from ..util.validator import validate_scalar, validate_array class Filter(object): """ A 'filter', in the general sense of a spectral transmission curve. The filter should be specified as an absolute transmission between 0 and 100% as a function of frequency. This will then be used to compute a total energy in ergs/s or ergs/s/cm^2. It is left to the user to decide how to convert this to a monochromatic frequency. Parameters ---------- name : str The name of the filter. spectral_coord : :class:`~astropy.units.quantity.Quantity` The spectral coordinates (e.g. wavelength, frequency, photon energy) at which the transmissions are defined. transmission : `numpy.ndarray` The spectral transmission as a function of spectral coordinate. """ def __init__(self, name=None, spectral_coord=None, transmission=None): self.name = name self.spectral_coord = spectral_coord self.transmission = transmission self._alpha = None self._beta = None self.central_spectral_coord = None @property def name(self): """ The name of the filter. """ return self._name @name.setter def name(self, value): if value is None or isinstance(value, six.string_types): self._name = value else: raise TypeError("name should be given as a string") @property def spectral_coord(self): """ The spectral coordinates (e.g. wavelength, frequency, photon energy) at which the filter is defined. """ return self._spectral_coord @spectral_coord.setter def spectral_coord(self, value): if value is None: self._spectral_coord = None else: self._spectral_coord = validate_array('spectral_coord', value, domain='strictly-positive', ndim=1, physical_type=('frequency', 'length', 'energy')) @property def transmission(self): """ The filter transmission. """ return self._transmission @transmission.setter def transmission(self, value): if value is None: self._transmission = None else: self._transmission = validate_array('r', value, domain='positive', ndim=1, shape=None if self.spectral_coord is None else (len(self.spectral_coord),), physical_type=('dimensionless')) def check_all_set(self): for attr in ['spectral_coord', 'transmission', 'name', 'alpha', 'detector_type', 'central_spectral_coord']: if getattr(self, attr) is None: raise ValueError("{0} has not been set".format(attr)) def to_hdf5_group(self, group, name): self.check_all_set() # Get spectral coordinate in Hz and transmision in fractional terms nu = self.spectral_coord.to(u.Hz, equivalencies=u.spectral()).value tr = self.transmission.to(u.one).value # Sort in order of increasing Hz order = np.argsort(nu) nu = nu[order] tr = tr[order] # Get other parameters for the normalization nu0 = self.central_spectral_coord.to(u.Hz, equivalencies=u.spectral()).value alpha = self.alpha beta = self._beta # Here we normalize the filter before passing it to Hyperion tr_norm = (tr / nu ** (1 + beta) / nu0 ** alpha / integrate(nu, tr / nu ** (1. + alpha + beta))) # Now multiply by nu so that Hyperion returns nu * Fnu tr_norm *= nu dset = group.create_dataset(name, data=np.array(list(zip(nu, tr, tr_norm)), dtype=[('nu', float), ('tr', float), ('tn', float)])) dset.attrs['name'] = np.string_(self.name) dset.attrs['alpha'] = self.alpha dset.attrs['beta'] = self._beta dset.attrs['nu0'] = self.central_spectral_coord.to(u.Hz, equivalencies=u.spectral()).value @classmethod def from_hdf5_group(cls, group, name): self = cls() self.spectral_coord = group[name]['nu'] * u.Hz self.transmission = group[name]['tr'] * u.one self.name = group[name].attrs['name'].decode('utf-8') self.alpha = group[name].attrs['alpha'] self._beta = group[name].attrs['beta'] self.central_spectral_coords = group[name].attrs['nu0'] * u.Hz return self @property def detector_type(self): return "energy" if self._beta == -1 else "photons" @detector_type.setter def detector_type(self, value): if value == 'energy': self._beta = -1 elif value == 'photons': self._beta = 0 else: raise ValueError("detector_type should be one of energy/photons") @property def alpha(self): return self._alpha @alpha.setter def alpha(self, value): self._alpha = value @property def central_spectral_coord(self): """ The central spectral coordinate (e.g. wavelength, frequency, photon energy) at which the monochromatic flux should be measured. """ return self._central_spectral_coord @central_spectral_coord.setter def central_spectral_coord(self, value): if value is None: self._central_spectral_coord = None else: self._central_spectral_coord = validate_scalar('spectral_coord', value, domain='strictly-positive', physical_type=('frequency', 'length', 'energy'))
[ "numpy.argsort", "astropy.units.spectral", "numpy.string_" ]
[((3350, 3364), 'numpy.argsort', 'np.argsort', (['nu'], {}), '(nu)\n', (3360, 3364), True, 'import numpy as np\n'), ((4253, 4274), 'numpy.string_', 'np.string_', (['self.name'], {}), '(self.name)\n', (4263, 4274), True, 'import numpy as np\n'), ((3225, 3237), 'astropy.units.spectral', 'u.spectral', ([], {}), '()\n', (3235, 3237), True, 'from astropy import units as u\n'), ((3530, 3542), 'astropy.units.spectral', 'u.spectral', ([], {}), '()\n', (3540, 3542), True, 'from astropy import units as u\n'), ((4436, 4448), 'astropy.units.spectral', 'u.spectral', ([], {}), '()\n', (4446, 4448), True, 'from astropy import units as u\n')]
#Reader for the coco panoptic data set for pointer based image segmentation import numpy as np import os import scipy.misc as misc import random import cv2 import json import threading ############################################################################################################ def rgb2id(color): # Convert annotation map from 3 channel RGB to instance if isinstance(color, np.ndarray) and len(color.shape) == 3: if color.dtype == np.uint8: color = color.astype(np.uint32) return color[:, :, 0] + 256 * color[:, :, 1] + 256 * 256 * color[:, :, 2] return color[0] + 256 * color[1] + 256 * 256 * color[2] ######################################################################################################################### ######################################################################################################################### class Generator: # Initiate reader and define the main parameters for the data reader def __init__(self, ImageDir,AnnotationDir,OutDir, DataFile, AnnotationFileType="png", ImageFileType="jpg",UnlabeledTag=0): self.ImageDir=ImageDir # Image dir self.AnnotationDir=AnnotationDir # File containing image annotation self.AnnotationFileType=AnnotationFileType # What is the the type (ending) of the annotation files self.ImageFileType=ImageFileType # What is the the type (ending) of the image files self.DataFile=DataFile # Json File that contain data on the annotation of each image self.UnlabeledTag=UnlabeledTag # Value of unlabled region in the annotation map (usually 0) self.ReadStuff = True # Read things that are not instace object (like sky or grass) self.SplitThings = False#True # Split instance of things (object) to connected component region and use each connected region as an instance self.SplitStuff = True # Split instance of things (object) to connected component region and use each connected region as instance self.SplitCrowd = True # Split areas marked as Crowds using connected componennt self.IgnoreCrowds = False # Ignore areas marked as crowd self.Outdir=OutDir self.OutDirByClass=OutDir+"/Class/" self.OutDirAll = OutDir + "/All/" self.SegMapDir = OutDir + "/SegMapDir/" self.MinSegSize = 400 if not os.path.exists(OutDir): os.mkdir(OutDir) if not os.path.exists(self.OutDirByClass): os.mkdir(self.OutDirByClass) if not os.path.exists(self.OutDirAll): os.mkdir(self.OutDirAll) if not os.path.exists(self.SegMapDir): os.mkdir(self.SegMapDir) # self.PickBySize = False # Pick instances of with probablity proportional to their sizes if false all segments are picked with equal probablity #........................Read data file................................................................................................................ with open(DataFile) as json_file: self.AnnData=json.load(json_file) #-------------------Get All files in folder-------------------------------------------------------------------------------------- self.FileList=[] for FileName in os.listdir(AnnotationDir): if AnnotationFileType in FileName: self.FileList.append(FileName) # if self.suffle: # random.shuffle(self.FileList) # if TrainingMode: self.StartLoadBatch() ############################################################################################################################################## #Get annotation data for specific nmage from the json file def GetAnnnotationData(self, AnnFileName): for item in self.AnnData['annotations']: # Get Annotation Data if (item["file_name"] == AnnFileName): return(item['segments_info']) ############################################################################################################################################ #Get information for specific catagory/Class id def GetCategoryData(self,ID): for item in self.AnnData['categories']: if item["id"]==ID: return item["name"],item["isthing"] ##########################################################################################################################################3333 #Split binary mask correspond to a singele segment into connected components def GetConnectedSegment(self, Seg): [NumCCmp, CCmpMask, CCompBB, CCmpCntr] = cv2.connectedComponentsWithStats(Seg.astype(np.uint8)) # apply connected component Mask=np.zeros([NumCCmp,Seg.shape[0],Seg.shape[1]],dtype=bool) BBox=np.zeros([NumCCmp,4]) Sz=np.zeros([NumCCmp],np.uint32) for i in range(1,NumCCmp): Mask[i-1] = (CCmpMask == i) BBox[i-1] = CCompBB[i][:4] Sz[i-1] = CCompBB[i][4] #segment Size return Mask,BBox,Sz,NumCCmp-1 ################################################################################################################################################# ############################################################################################################################# ############################################################################################################################ #Pick random point from segment given as a binary mask def PickRandomPointInSegment(self,Seg,ErodeMask=9): x0 = int(np.floor(Seg["BBox"][0])) # Bounding box x position Wbox = int(np.floor(Seg["BBox"][2])) # Bounding box width y0 = int(np.floor(Seg["BBox"][1])) # Bounding box y position Hbox = int(np.floor(Seg["BBox"][3])) # Bounding box height if ErodeMask: Msk = cv2.erode(Seg["Mask"].astype(np.uint8), np.ones((3, 3), np.uint8), iterations=ErodeMask) if Msk.sum()==0: Msk=Seg["Mask"] else: Msk = Seg["Mask"] while(True): x = np.random.randint(Wbox) + x0 y = np.random.randint(Hbox) + y0 if (Msk[y,x])==1: return x,y ###################################################################################################### #Generate list of all segments in the image # Given the annotation map a json data file create list of all segments and instance with info on each segment #--------------------------Generate list of all segments-------------------------------------------------------------------------------- def GeneratListOfAllSegments(self,Ann,Ann_name,AddUnLabeled=False,IgnoreSmallSeg=True): AnnList = self.GetAnnnotationData(Ann_name) Sgs = [] # List of segments and their info SumAreas=0 # Sum areas of all segments up to image for an in AnnList: an["name"], an["isthing"] = self.GetCategoryData(an["category_id"]) if (an["iscrowd"] and self.IgnoreCrowds) or (not an["isthing"] and not self.ReadStuff): Ann[Ann == an['id']] = self.UnlabeledTag continue if (an["isthing"] and self.SplitThings) or (an["isthing"]==False and self.SplitStuff) or (an["iscrowd"] and self.SplitCrowd): #Things are objects that have instances TMask, TBBox, TSz, TNm = self.GetConnectedSegment(Ann == an['id']) # Split to connected components for i in range(TNm): seg={} seg["Mask"]=TMask[i] seg["BBox"]=TBBox[i] seg["Area"]=TSz[i] if seg["Area"] < self.MinSegSize and IgnoreSmallSeg: Ann[Ann == an['id']] = self.UnlabeledTag continue seg["NumParts"] =TNm seg["IsSplit"]=TNm>1 seg["IsThing"]=an["isthing"] seg["Name"]=an["name"] seg["IsCrowd"]=an["iscrowd"] seg["CatId"]=an["category_id"] seg["IsLabeled"] = True SumAreas+=seg["Area"] Sgs.append(seg) else: # none object classes such as sky seg = {} seg["Mask"] = (Ann == an['id']) seg["BBox"] = an["bbox"] seg["Area"] = an["area"] if seg["Area"] < self.MinSegSize and IgnoreSmallSeg: # Ignore very small segments Ann[Ann == an['id']] = self.UnlabeledTag continue seg["NumParts"] = 1 seg["IsSplit"] = False seg["IsThing"] = an["isthing"] seg["Name"] = an["name"] seg["IsCrowd"] = an["iscrowd"] seg["CatId"] = an["category_id"] seg["IsLabeled"]=True SumAreas += seg["Area"] Sgs.append(seg) if AddUnLabeled: #Add unlabeled region as additional segments TMask, TBBox, TSz, TNm = self.GetConnectedSegment(Ann == self.UnlabeledTag) # Split to connected components for i in range(TNm): seg = {} seg["Mask"] = TMask[i] seg["BBox"] = TBBox[i] seg["Area"] = TSz[i] seg["NumParts"] = TNm seg["Name"] ="unlabeled" seg["CatId"] = self.UnlabeledTag seg["IsLabeled"] = False seg["IsCrowd"] = False Sgs.append(seg) return Sgs,SumAreas ################################################################################################################################################## def Generate(self): ErrorCount=0 for f,Ann_name in enumerate(self.FileList): # Get label image name if os.path.exists(self.SegMapDir + "/" + Ann_name): continue print(str(f)+")"+Ann_name) Ann = cv2.imread(self.AnnotationDir + "/" + Ann_name) # Load Annotation Img0 = cv2.imread(self.ImageDir + "/" + Ann_name.replace(".png",".jpg")) Ann = Ann[..., :: -1] self.AnnColor=Ann Ann=rgb2id(Ann) # misc.imshow((Ann==0).astype(float)) # misc.imshow(Img) H,W=Ann.shape Sgs, SumAreas = self.GeneratListOfAllSegments(Ann, Ann_name,AddUnLabeled=True,IgnoreSmallSeg=True) SgMap=np.zeros([H,W],np.uint8) for ii,seg in enumerate(Sgs): SgMap[seg["Mask"]>0]=ii if not seg["IsCrowd"] and seg["IsLabeled"]: Name=Ann_name.replace(".","__")+"##Class##"+str(seg["CatId"])+"##IsThing##"+str(seg["IsThing"])+"IDNum"+str(ii)+".png" ClassDir=self.OutDirByClass+"/"+str(seg["CatId"])+"/" if not os.path.exists(ClassDir): os.mkdir(ClassDir) if os.path.exists(self.OutDirAll + "/" + Name) or os.path.exists(ClassDir + "/" + Name): print("Err "+Name) ErrorCount+=1 cv2.imwrite(ClassDir+"/"+Name,seg["Mask"].astype(np.uint8)) cv2.imwrite(self.OutDirAll + "/" + Name, seg["Mask"].astype(np.uint8)) # print((cv2.imread(ClassDir+"/"+Name, 0) - seg["Mask"].astype(np.uint8)).sum()) # Img=Img0.copy() # Img[:, :, 1] *= 1 - seg["Mask"].astype(np.uint8) # Img[:,:,0]*=1-seg["Mask"].astype(np.uint8) # print( self.GetCategoryData(seg["CatId"])) # misc.imshow(Img) if ii > 255: print("more then 255 Segs") ErrorCount += 1 cv2.imwrite(self.SegMapDir + "/" + Ann_name, SgMap.astype(np.uint8)) print("Num Errors "+str(ErrorCount)) # # print((cv2.imread(self.SegMapDir + "/" + Ann_name,0)-SgMap.astype(np.uint8)).sum()) # misc.imshow(SgMap * 10)
[ "os.mkdir", "json.load", "numpy.floor", "numpy.zeros", "os.path.exists", "numpy.ones", "cv2.imread", "numpy.random.randint", "os.listdir" ]
[((3205, 3230), 'os.listdir', 'os.listdir', (['AnnotationDir'], {}), '(AnnotationDir)\n', (3215, 3230), False, 'import os\n'), ((4667, 4726), 'numpy.zeros', 'np.zeros', (['[NumCCmp, Seg.shape[0], Seg.shape[1]]'], {'dtype': 'bool'}), '([NumCCmp, Seg.shape[0], Seg.shape[1]], dtype=bool)\n', (4675, 4726), True, 'import numpy as np\n'), ((4741, 4763), 'numpy.zeros', 'np.zeros', (['[NumCCmp, 4]'], {}), '([NumCCmp, 4])\n', (4749, 4763), True, 'import numpy as np\n'), ((4778, 4808), 'numpy.zeros', 'np.zeros', (['[NumCCmp]', 'np.uint32'], {}), '([NumCCmp], np.uint32)\n', (4786, 4808), True, 'import numpy as np\n'), ((2365, 2387), 'os.path.exists', 'os.path.exists', (['OutDir'], {}), '(OutDir)\n', (2379, 2387), False, 'import os\n'), ((2389, 2405), 'os.mkdir', 'os.mkdir', (['OutDir'], {}), '(OutDir)\n', (2397, 2405), False, 'import os\n'), ((2421, 2455), 'os.path.exists', 'os.path.exists', (['self.OutDirByClass'], {}), '(self.OutDirByClass)\n', (2435, 2455), False, 'import os\n'), ((2457, 2485), 'os.mkdir', 'os.mkdir', (['self.OutDirByClass'], {}), '(self.OutDirByClass)\n', (2465, 2485), False, 'import os\n'), ((2501, 2531), 'os.path.exists', 'os.path.exists', (['self.OutDirAll'], {}), '(self.OutDirAll)\n', (2515, 2531), False, 'import os\n'), ((2533, 2557), 'os.mkdir', 'os.mkdir', (['self.OutDirAll'], {}), '(self.OutDirAll)\n', (2541, 2557), False, 'import os\n'), ((2573, 2603), 'os.path.exists', 'os.path.exists', (['self.SegMapDir'], {}), '(self.SegMapDir)\n', (2587, 2603), False, 'import os\n'), ((2605, 2629), 'os.mkdir', 'os.mkdir', (['self.SegMapDir'], {}), '(self.SegMapDir)\n', (2613, 2629), False, 'import os\n'), ((3004, 3024), 'json.load', 'json.load', (['json_file'], {}), '(json_file)\n', (3013, 3024), False, 'import json\n'), ((5560, 5584), 'numpy.floor', 'np.floor', (["Seg['BBox'][0]"], {}), "(Seg['BBox'][0])\n", (5568, 5584), True, 'import numpy as np\n'), ((5636, 5660), 'numpy.floor', 'np.floor', (["Seg['BBox'][2]"], {}), "(Seg['BBox'][2])\n", (5644, 5660), True, 'import numpy as np\n'), ((5705, 5729), 'numpy.floor', 'np.floor', (["Seg['BBox'][1]"], {}), "(Seg['BBox'][1])\n", (5713, 5729), True, 'import numpy as np\n'), ((5781, 5805), 'numpy.floor', 'np.floor', (["Seg['BBox'][3]"], {}), "(Seg['BBox'][3])\n", (5789, 5805), True, 'import numpy as np\n'), ((9998, 10045), 'os.path.exists', 'os.path.exists', (["(self.SegMapDir + '/' + Ann_name)"], {}), "(self.SegMapDir + '/' + Ann_name)\n", (10012, 10045), False, 'import os\n'), ((10121, 10168), 'cv2.imread', 'cv2.imread', (["(self.AnnotationDir + '/' + Ann_name)"], {}), "(self.AnnotationDir + '/' + Ann_name)\n", (10131, 10168), False, 'import cv2\n'), ((10638, 10664), 'numpy.zeros', 'np.zeros', (['[H, W]', 'np.uint8'], {}), '([H, W], np.uint8)\n', (10646, 10664), True, 'import numpy as np\n'), ((5918, 5943), 'numpy.ones', 'np.ones', (['(3, 3)', 'np.uint8'], {}), '((3, 3), np.uint8)\n', (5925, 5943), True, 'import numpy as np\n'), ((6114, 6137), 'numpy.random.randint', 'np.random.randint', (['Wbox'], {}), '(Wbox)\n', (6131, 6137), True, 'import numpy as np\n'), ((6163, 6186), 'numpy.random.randint', 'np.random.randint', (['Hbox'], {}), '(Hbox)\n', (6180, 6186), True, 'import numpy as np\n'), ((11072, 11096), 'os.path.exists', 'os.path.exists', (['ClassDir'], {}), '(ClassDir)\n', (11086, 11096), False, 'import os\n'), ((11098, 11116), 'os.mkdir', 'os.mkdir', (['ClassDir'], {}), '(ClassDir)\n', (11106, 11116), False, 'import os\n'), ((11146, 11189), 'os.path.exists', 'os.path.exists', (["(self.OutDirAll + '/' + Name)"], {}), "(self.OutDirAll + '/' + Name)\n", (11160, 11189), False, 'import os\n'), ((11194, 11231), 'os.path.exists', 'os.path.exists', (["(ClassDir + '/' + Name)"], {}), "(ClassDir + '/' + Name)\n", (11208, 11231), False, 'import os\n')]
"""Tests for reading data from MCD.""" from datetime import datetime from pathlib import Path import numpy as np import pytest from mars_mcd_helper.read_mars_data import parse_body, parse_header, parse_number, read_ascii_data cases = [["12", 12], ["12.0008", 12.0008], ["----", None], ["1e78", 1e78]] @pytest.mark.parametrize(("numstr", "res"), cases) def test_parse_number(numstr, res): """Test parsing numstrings to numbers. Args: numstr (str): str to parse. res: desired result. """ assert parse_number(numstr) == res def test_parse_body(): """Test parsing body.""" body = """---- || -9.00000e+01 -8.61702e+01 -8.23404e+01 -7.85106e+01 -7.46809e+01 -7.08511e+01 -6.70213e+01 -6.31915e+01 -5.93617e+01 -5.55319e+01 -5.17021e+01 -4.78723e+01 -4.40426e+01 -4.02128e+01 -3.63830e+01 -3.25532e+01 -2.87234e+01 -2.48936e+01 -2.10638e+01 -1.72340e+01 -1.34043e+01 -9.57447e+00 -5.74468e+00 -1.91489e+00 1.91489e+00 5.74468e+00 9.57447e+00 1.34043e+01 1.72340e+01 2.10638e+01 2.48936e+01 2.87234e+01 3.25532e+01 3.63830e+01 4.02128e+01 4.40426e+01 4.78723e+01 5.17021e+01 5.55319e+01 5.93617e+01 6.31915e+01 6.70213e+01 7.08511e+01 7.46809e+01 7.85106e+01 8.23404e+01 8.61702e+01 9.00000e+01 ----------------------------------- -180 || 3.85941e-07 3.54776e-07 3.12143e-07 3.26378e-07 4.40781e-07 6.51328e-07 9.64859e-07 1.58060e-06 3.46786e-06 1.03584e-05 3.59026e-05 1.14634e-04 3.10848e-04 6.85023e-04 1.28657e-03 1.96361e-03 2.84410e-03 3.58751e-03 3.96411e-03 4.58151e-03 6.70365e-03 7.33091e-03 8.40377e-03 1.01448e-02 1.17229e-02 1.28424e-02 1.37919e-02 1.40092e-02 1.55745e-02 1.68401e-02 1.80063e-02 2.04580e-02 2.46005e-02 2.97717e-02 3.41619e-02 3.71240e-02 3.91904e-02 4.19624e-02 4.46246e-02 4.73612e-02 5.17239e-02 5.51091e-02 5.86257e-02 6.15134e-02 6.02517e-02 4.47480e-02 2.85537e-02 1.91096e-02""" body = body.split("\n") resp = parse_body(body) xlabels = [ -9.00000e1, -8.61702e1, -8.23404e1, -7.85106e1, -7.46809e1, -7.08511e1, -6.70213e1, -6.31915e1, -5.93617e1, -5.55319e1, -5.17021e1, -4.78723e1, -4.40426e1, -4.02128e1, -3.63830e1, -3.25532e1, -2.87234e1, -2.48936e1, -2.10638e1, -1.72340e1, -1.34043e1, -9.57447e0, -5.74468e0, -1.91489e0, 1.91489e0, 5.74468e0, 9.57447e0, 1.34043e1, 1.72340e1, 2.10638e1, 2.48936e1, 2.87234e1, 3.25532e1, 3.63830e1, 4.02128e1, 4.40426e1, 4.78723e1, 5.17021e1, 5.55319e1, 5.93617e1, 6.31915e1, 6.70213e1, 7.08511e1, 7.46809e1, 7.85106e1, 8.23404e1, 8.61702e1, 9.00000e1, ] data = np.array( [ [ "3.85941e-07", "3.54776e-07", "3.12143e-07", "3.26378e-07", "4.40781e-07", "6.51328e-07", "9.64859e-07", "1.58060e-06", "3.46786e-06", "1.03584e-05", "3.59026e-05", "1.14634e-04", "3.10848e-04", "6.85023e-04", "1.28657e-03", "1.96361e-03", "2.84410e-03", "3.58751e-03", "3.96411e-03", "4.58151e-03", "6.70365e-03", "7.33091e-03", "8.40377e-03", "1.01448e-02", "1.17229e-02", "1.28424e-02", "1.37919e-02", "1.40092e-02", "1.55745e-02", "1.68401e-02", "1.80063e-02", "2.04580e-02", "2.46005e-02", "2.97717e-02", "3.41619e-02", "3.71240e-02", "3.91904e-02", "4.19624e-02", "4.46246e-02", "4.73612e-02", "5.17239e-02", "5.51091e-02", "5.86257e-02", "6.15134e-02", "6.02517e-02", "4.47480e-02", "2.85537e-02", "1.91096e-02", ] ], dtype="float", ) assert len(resp.xlabels) == len(xlabels) assert resp.xlabels == pytest.approx(xlabels) assert resp.ylabels == [-180] assert (resp.data == np.rot90(data)).all() def test_parse_header(): """Test parsing header.""" data = """########################################################################################## ### MCD_v5.3 with climatology average solar scenario. ### Ls 85.3deg. Altitude 10.0 m ALS Local time 0.0h (at longitude 0) ### -------------------------------------------------------------------------------------- ### Column 1 is East longitude (degrees) ### Columns 2+ are Water vapor column (kg/m2) ### Line 1 is North latitude (degrees) ### -------------------------------------------------------------------------------------- ### Retrieved on: 2021-08-14T16:27:39.703997 ### Mars Climate Database (c) LMD/OU/IAA/ESA/CNES ##########################################################################################""" data = data.split("\n") resp = parse_header(data[1:]) assert resp["mcd_version"] == "v5.3" assert resp["model"] == "climatology average solar scenario" assert resp["ls"] == "85.3deg" assert resp["altitude"] == "10.0 m" assert resp["local_time"] == "0.0h (at longitude 0)" assert resp["column_1"] == "East longitude (degrees)" assert resp["variable"] == "Water vapor column (kg/m2)" assert resp["keys"] == "North latitude (degrees)" assert resp["retrieval_date"] == datetime(2021, 8, 14, 16, 27, 39, 703997) def test_parse_file(): """Test parsing file.""" testf = Path("tests/data.txt") sections = read_ascii_data(testf) assert list(sections.keys()) == [ "Water vapor column (kg/m2)", "Temperature (K)", "Pressure (Pa)", ] for _, v in sections.items(): assert len(v["data"].data) == 48
[ "mars_mcd_helper.read_mars_data.read_ascii_data", "pytest.approx", "datetime.datetime", "mars_mcd_helper.read_mars_data.parse_header", "pathlib.Path", "numpy.array", "numpy.rot90", "pytest.mark.parametrize", "mars_mcd_helper.read_mars_data.parse_body", "mars_mcd_helper.read_mars_data.parse_number"...
[((307, 356), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (["('numstr', 'res')", 'cases'], {}), "(('numstr', 'res'), cases)\n", (330, 356), False, 'import pytest\n'), ((2161, 2177), 'mars_mcd_helper.read_mars_data.parse_body', 'parse_body', (['body'], {}), '(body)\n', (2171, 2177), False, 'from mars_mcd_helper.read_mars_data import parse_body, parse_header, parse_number, read_ascii_data\n'), ((3147, 3943), 'numpy.array', 'np.array', (["[['3.85941e-07', '3.54776e-07', '3.12143e-07', '3.26378e-07', '4.40781e-07',\n '6.51328e-07', '9.64859e-07', '1.58060e-06', '3.46786e-06',\n '1.03584e-05', '3.59026e-05', '1.14634e-04', '3.10848e-04',\n '6.85023e-04', '1.28657e-03', '1.96361e-03', '2.84410e-03',\n '3.58751e-03', '3.96411e-03', '4.58151e-03', '6.70365e-03',\n '7.33091e-03', '8.40377e-03', '1.01448e-02', '1.17229e-02',\n '1.28424e-02', '1.37919e-02', '1.40092e-02', '1.55745e-02',\n '1.68401e-02', '1.80063e-02', '2.04580e-02', '2.46005e-02',\n '2.97717e-02', '3.41619e-02', '3.71240e-02', '3.91904e-02',\n '4.19624e-02', '4.46246e-02', '4.73612e-02', '5.17239e-02',\n '5.51091e-02', '5.86257e-02', '6.15134e-02', '6.02517e-02',\n '4.47480e-02', '2.85537e-02', '1.91096e-02']]"], {'dtype': '"""float"""'}), "([['3.85941e-07', '3.54776e-07', '3.12143e-07', '3.26378e-07',\n '4.40781e-07', '6.51328e-07', '9.64859e-07', '1.58060e-06',\n '3.46786e-06', '1.03584e-05', '3.59026e-05', '1.14634e-04',\n '3.10848e-04', '6.85023e-04', '1.28657e-03', '1.96361e-03',\n '2.84410e-03', '3.58751e-03', '3.96411e-03', '4.58151e-03',\n '6.70365e-03', '7.33091e-03', '8.40377e-03', '1.01448e-02',\n '1.17229e-02', '1.28424e-02', '1.37919e-02', '1.40092e-02',\n '1.55745e-02', '1.68401e-02', '1.80063e-02', '2.04580e-02',\n '2.46005e-02', '2.97717e-02', '3.41619e-02', '3.71240e-02',\n '3.91904e-02', '4.19624e-02', '4.46246e-02', '4.73612e-02',\n '5.17239e-02', '5.51091e-02', '5.86257e-02', '6.15134e-02',\n '6.02517e-02', '4.47480e-02', '2.85537e-02', '1.91096e-02']], dtype='float'\n )\n", (3155, 3943), True, 'import numpy as np\n'), ((5721, 5743), 'mars_mcd_helper.read_mars_data.parse_header', 'parse_header', (['data[1:]'], {}), '(data[1:])\n', (5733, 5743), False, 'from mars_mcd_helper.read_mars_data import parse_body, parse_header, parse_number, read_ascii_data\n'), ((6299, 6321), 'pathlib.Path', 'Path', (['"""tests/data.txt"""'], {}), "('tests/data.txt')\n", (6303, 6321), False, 'from pathlib import Path\n'), ((6337, 6359), 'mars_mcd_helper.read_mars_data.read_ascii_data', 'read_ascii_data', (['testf'], {}), '(testf)\n', (6352, 6359), False, 'from mars_mcd_helper.read_mars_data import parse_body, parse_header, parse_number, read_ascii_data\n'), ((531, 551), 'mars_mcd_helper.read_mars_data.parse_number', 'parse_number', (['numstr'], {}), '(numstr)\n', (543, 551), False, 'from mars_mcd_helper.read_mars_data import parse_body, parse_header, parse_number, read_ascii_data\n'), ((4795, 4817), 'pytest.approx', 'pytest.approx', (['xlabels'], {}), '(xlabels)\n', (4808, 4817), False, 'import pytest\n'), ((6191, 6232), 'datetime.datetime', 'datetime', (['(2021)', '(8)', '(14)', '(16)', '(27)', '(39)', '(703997)'], {}), '(2021, 8, 14, 16, 27, 39, 703997)\n', (6199, 6232), False, 'from datetime import datetime\n'), ((4877, 4891), 'numpy.rot90', 'np.rot90', (['data'], {}), '(data)\n', (4885, 4891), True, 'import numpy as np\n')]
import numpy as np from vaex.dataset import DatasetArrays class DatasetTap(DatasetArrays): class TapColumn(object): def __init__(self, tap_dataset, column_name, column_type, ucd): self.tap_dataset = tap_dataset self.column_name = column_name self.column_type = column_type self.ucd = ucd self.alpha_min = 0 length = len(tap_dataset) steps = length/1e6 # try to do it in chunks self.alpha_step = 360/steps self.alpha_max = self.alpha_min + self.alpha_step logger.debug("stepping in alpha %f" % self.alpha_step) self.data = [] self.offset = 0 self.shape = (length,) self.dtype = DatasetTap.type_map[self.column_type]().dtype self.left_over_chunk = None self.rows_left = length import tempfile self.download_file = tempfile.mktemp(".vot") def __getitem__(self, slice): start, stop, step = slice.start, slice.stop, slice.step required_length = stop - start assert start >= self.offset chunk_data = self.left_over_chunk enough = False if chunk_data is None else len(chunk_data) >= required_length if chunk_data is not None: logger.debug("start %s offset %s chunk length %s", start, self.offset, len(chunk_data)) #assert len(chunk_data) == start - self.offset if enough: logger.debug("we can skip the query, already have results from previous query") while not enough: adql_query = "SELECT {column_name} FROM {table_name} WHERE alpha >= {alpha_min} AND alpha < {alpha_max} ORDER BY alpha ASC"\ .format(column_name=self.column_name, table_name=self.tap_dataset.table_name, alpha_min=self.alpha_min, alpha_max=self.alpha_max) logger.debug("executing: %s" % adql_query) logger.debug("executing: %s" % adql_query.replace(" ", "+")) url = self.tap_dataset.tap_url + "/sync?REQUEST=doQuery&LANG=ADQL&MAXREC=10000000&FORMAT=votable&QUERY=" +adql_query.replace(" ", "+") import urllib2 response = urllib2.urlopen(url) with open(self.download_file, "w") as f: f.write(response.read()) votable = astropy.io.votable.parse(self.download_file) data = votable.get_first_table().array[self.column_name].data # TODO: respect masked array #table = astropy.table.Table.read(url, format="votable") #, show_progress=False) #data = table[self.column_name].data.data.data logger.debug("new chunk is of lenght %d", len(data)) self.rows_left -= len(data) logger.debug("rows left %d", self.rows_left) if chunk_data is None: chunk_data = data else: chunk_data = np.concatenate([chunk_data, data]) if len(chunk_data) >= required_length: enough = True logger.debug("total chunk is of lenght %d, enough: %s", len(chunk_data), enough) self.alpha_min += self.alpha_step self.alpha_max += self.alpha_step result, self.left_over_chunk = chunk_data[:required_length], chunk_data[required_length:] #print(result) logger.debug("left over is of length %d", len(self.left_over_chunk)) return result #np.zeros(N, dtype=self.dtype) type_map = { 'REAL':np.float32, 'SMALLINT':np.int32, 'DOUBLE':np.float64, 'BIGINT':np.int64, 'INTEGER':np.int32, 'BOOLEAN':np.bool8 } #not supported types yet 'VARCHAR',', u'BOOLEAN', u'INTEGER', u'CHAR def __init__(self, tap_url="http://gaia.esac.esa.int/tap-server/tap/g10_smc", table_name=None): logger.debug("tap url: %r", tap_url) self.tap_url = tap_url self.table_name = table_name if table_name is None: # let us try to infer the table name if tap_url.endswith("tap") or tap_url.endswith("tap/"): pass # this mean we really didn't provide one else: index = tap_url.rfind("tap/") if index != -1: self.tap_url, self.table_name = tap_url[:index+4], self.tap_url[index+4:] logger.debug("inferred url is %s, and table name is %s", self.tap_url, self.table_name) if self.tap_url.startswith("tap+"): # remove tap+ part from tap+http(s), only keep http(s) part self.tap_url = self.tap_url[len("tap+"):] import requests super(DatasetTap, self).__init__(self.table_name) self.req = requests.request("get", self.tap_url+"/tables/") self.path = "tap+" +self.tap_url + "/" + table_name #print dir(self.req) from bs4 import BeautifulSoup #self.soup = BeautifulSoup(req.response) tables = BeautifulSoup(self.req.content, 'xml') self.tap_tables = collections.OrderedDict() for table in tables.find_all("table"): #print table.find("name").string, table.description.string, table["gaiatap:size"] table_name = unicode(table.find("name").string) table_size = int(table["esatapplus:size"]) #print table_name, table_size logger.debug("tap table %r ", table_name) columns = [] for column in table.find_all("column"): column_name = unicode(column.find("name").string) column_type = unicode(column.dataType.string) ucd = column.ucd.string if column.ucd else None unit = column.unit.string if column.unit else None description = column.description.string if column.description else None #print "\t", column_name, column_type, ucd #types.add() columns.append((column_name, column_type, ucd, unit, description)) self.tap_tables[table_name] = (table_size, columns) if not self.tap_tables: raise ValueError("no tables or wrong url") for name, (table_size, columns) in self.tap_tables.items(): logger.debug("table %s has length %d", name, table_size) self._full_length, self._tap_columns = self.tap_tables[self.table_name] self._length = self._full_length logger.debug("selected table table %s has length %d", self.table_name, self._full_length) #self.column_names = [] #self.columns = collections.OrderedDict() for column_name, column_type, ucd, unit, description in self._tap_columns: logger.debug(" column %s has type %s and ucd %s, unit %s and description %s", column_name, column_type, ucd, unit, description) if column_type in self.type_map.keys(): self.column_names.append(column_name) if ucd: self.ucds[column_name] = ucd if unit: self.units[column_name] = unit if description: self.descriptions[column_name] = description self.columns[column_name] = self.TapColumn(self, column_name, column_type, ucd) else: logger.warning(" type of column %s is not supported, it will be skipped", column_name) @classmethod def open(cls, path, *args, **kwargs): return cls(path, *args, **kwargs) @classmethod def quick_test(cls, path, *args, **kwargs): return False @classmethod def can_open(cls, path, *args, **kwargs): can_open = False url = None try: url = urlparse(path) except: return False if url.scheme: if url.scheme.startswith("tap+http"): # will also catch https can_open = True logger.debug("%r can open: %r" %(cls.__name__, can_open)) return can_open
[ "requests.request", "bs4.BeautifulSoup", "tempfile.mktemp", "urllib2.urlopen", "numpy.concatenate" ]
[((4894, 4944), 'requests.request', 'requests.request', (['"""get"""', "(self.tap_url + '/tables/')"], {}), "('get', self.tap_url + '/tables/')\n", (4910, 4944), False, 'import requests\n'), ((5141, 5179), 'bs4.BeautifulSoup', 'BeautifulSoup', (['self.req.content', '"""xml"""'], {}), "(self.req.content, 'xml')\n", (5154, 5179), False, 'from bs4 import BeautifulSoup\n'), ((944, 967), 'tempfile.mktemp', 'tempfile.mktemp', (['""".vot"""'], {}), "('.vot')\n", (959, 967), False, 'import tempfile\n'), ((2286, 2306), 'urllib2.urlopen', 'urllib2.urlopen', (['url'], {}), '(url)\n', (2301, 2306), False, 'import urllib2\n'), ((3069, 3103), 'numpy.concatenate', 'np.concatenate', (['[chunk_data, data]'], {}), '([chunk_data, data])\n', (3083, 3103), True, 'import numpy as np\n')]
import cv2 import numpy as np import glob import random import mediapipe as mp import matplotlib.pyplot as plt import time import math def getObjectsFromImages(img): # Load Yolo net = cv2.dnn.readNet("Utilities/yolov3_training_last.weights", "Utilities/yolov3_testing.cfg") # Name custom object classes = ["bidon"] # Images path #images_path = ["bid.png","example.png"] layer_names = net.getLayerNames() output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()] colors = np.random.uniform(0, 255, size=(len(classes), 3)) # Insert here the path of your images # loop through all the images # Loading image height, width, channels = img.shape # Detecting objects blob = cv2.dnn.blobFromImage(img, 0.00392, (416, 416), (0, 0, 0), True, crop=False) net.setInput(blob) outs = net.forward(output_layers) # Showing informations on the screen class_ids = [] confidences = [] boxes = [] for out in outs: for detection in out: scores = detection[5:] class_id = np.argmax(scores) confidence = scores[class_id] if confidence > 0.3: # Object detected print(class_id) center_x = int(detection[0] * width) center_y = int(detection[1] * height) w = int(detection[2] * width) h = int(detection[3] * height) # Rectangle coordinates x = int(center_x - w / 2) y = int(center_y - h / 2) boxes.append([x, y, w, h]) confidences.append(float(confidence)) class_ids.append(class_id) indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4) print(indexes) font = cv2.FONT_HERSHEY_PLAIN for i in range(len(boxes)): if i in indexes: x, y, w, h = boxes[i] label = str(classes[class_ids[i]]) color = colors[class_ids[i]] cv2.rectangle(img, (x, y), (x + w, y + h), color, 2) cv2.putText(img, label, (x, y + 30), font, 3, color, 2) plt.imshow(img) plt.show() key = cv2.waitKey(0) cv2.destroyAllWindows() def getObjectsFromVideos(videoList, coolDown): """ [summary] Bu fonksiyon videolardaki benzin bidonu objelerini ve bu objelerle insan vucudu arasindaki iliskiyi gosterir. Args: videoList ([[String]]): [Videolarin pathlerinden olusan array.] coolDown ([Int]): [Objelerin tekrar hesaplanmasi icin gecmesi gereken sure.] """ whichHand = "" # Bidonun hangi elde oldugunu gosteren string humanPos = "" # Insanin kameraya gore hangi konumda oldugunu gosteren string totalCal = 0 # Insanin yaktigi toplam kaloriyi gosteren Int mp_pose = mp.solutions.pose mp_drawing = mp.solutions.drawing_utils # Load Yolo net = cv2.dnn.readNet("Utilities/yolov3_training_last.weights", "Utilities/yolov3_testing.cfg") classes = ["bidon"] layer_names = net.getLayerNames() output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()] colors = np.random.uniform(0, 255, size=(len(classes), 3)) distanceList = [] p1,p2 = [0,0], [0,0] stepCounts = 0 #Toplam adim sayisi tic = time.time() previousStepCounts = 0 # 2 saniye onceki adim sayisi with mp_pose.Pose( min_detection_confidence=0.5, min_tracking_confidence=0.5) as pose: for video in videoList: cap = cv2.VideoCapture(video) while cap.isOpened(): currentSecond = cap.get(cv2.CAP_PROP_POS_MSEC) / 1000 print(currentSecond) timer = cv2.getTickCount() ret, frame = cap.read() img = frame img = cv2.resize(img,[960, 540], cv2.INTER_AREA) height, width, channels = img.shape if not ret: break if cv2.waitKey(1) & 0xFF == 27: ret = False break image = cv2.cvtColor(cv2.flip(img, 1), cv2.COLOR_BGR2RGB) image.flags.writeable = False results = pose.process(image) if results.pose_landmarks: # Insanin kameraya gore yonunun tespiti if not abs(results.pose_landmarks.landmark[12].x - results.pose_landmarks.landmark[11].x) > 0.009: # 5.6 pixel in normal scene if (results.pose_landmarks.landmark[12].z > results.pose_landmarks.landmark[11].z): humanPos = "Sol" else: humanPos = "Sag" else: if results.pose_landmarks.landmark[0].z > results.pose_landmarks.landmark[12].z or results.pose_landmarks.landmark[0].z > results.pose_landmarks.landmark[11].z : humanPos = "Arka" else: humanPos = "On" ## Adim Hesaplama imageWidth = image.shape[1] imageHeight = image.shape[0] oncekiDistance = math.sqrt((p1[0] - p2[0])**2 + (p1[1] - p2[1])**2) p1 = int(results.pose_landmarks.landmark[30].x * imageWidth) , int(results.pose_landmarks.landmark[30].y * imageHeight) p2 = int(results.pose_landmarks.landmark[31].x * imageWidth) , int(results.pose_landmarks.landmark[31].y * imageHeight) distance = math.sqrt((p1[0] - p2[0])**2 + (p1[1] - p2[1])**2) # 2landmark arasindaki mesafe distanceList.append(distance) if len(distanceList) == 14: #14 Frame olduktan sonra minIndex = distanceList.index(min(distanceList)) if minIndex != 0 and minIndex != len(distanceList)-1: #minimum elemandan sonra eleman varsa kisi adim atmis.. print(distanceList[minIndex] , distanceList[minIndex + 1]) if distanceList[minIndex] < distanceList[minIndex + 1]: stepCounts += 1 distanceList = [] image.flags.writeable = True image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR) toc = time.time() if toc - tic > coolDown : # Detecting Objects blob = cv2.dnn.blobFromImage(image, 0.00392, (416, 416), (0, 0, 0), True, crop=False) net.setInput(blob) outs = net.forward(output_layers) # Showing informations on the screen class_ids = [] confidences = [] boxes = [] for out in outs: for detection in out: scores = detection[5:] class_id = np.argmax(scores) confidence = scores[class_id] if confidence > 0.7: # Object detected print(class_id) center_x = int(detection[0] * width) center_y = int(detection[1] * height) w = int(detection[2] * width) h = int(detection[3] * height) # Rectangle coordinates x = int(center_x - w / 2) y = int(center_y - h / 2) boxes.append([x, y, w, h]) confidences.append(float(confidence)) class_ids.append(class_id) indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4) font = cv2.FONT_HERSHEY_PLAIN for i in range(len(boxes)): if i in indexes: x, y, w, h = boxes[i] label = str(classes[class_ids[i]]) color = colors[class_ids[i]] cv2.rectangle(image, (x, y), (x + w, y + h), color, 4) cv2.putText(image, label, (x, y + 30), font, 3, color, 4) imageWidth = image.shape[1] imageHeight = image.shape[0] ## Obje hangi elde tutuluyor? if int(results.pose_landmarks.landmark[17].x * imageWidth) > x and int(results.pose_landmarks.landmark[17].x * imageWidth) < x+h: if int(results.pose_landmarks.landmark[17].y * imageHeight) < y+h and int(results.pose_landmarks.landmark[17].y * imageHeight) - y < 10: whichHand = 'Sol el' elif int(results.pose_landmarks.landmark[18].x * imageWidth) > x and int(results.pose_landmarks.landmark[18].x * imageWidth) < x+h: if int(results.pose_landmarks.landmark[18].y * imageHeight) < y+h and int(results.pose_landmarks.landmark[18].y * imageHeight) - y < 10: whichHand = 'Sag el' elif int(results.pose_landmarks.landmark[18].x * imageWidth) > x and int(results.pose_landmarks.landmark[18].x * imageWidth) < x+h and int(results.pose_landmarks.landmark[17].x * imageWidth) > x and int(results.pose_landmarks.landmark[17].x * imageWidth) < x+h: if results.pose_landmarks.landmark[18].z > results.pose_landmarks.landmark[17].z: whichHand = 'Sag el' else: whichHand = 'Sol el' else: whichHand = 'Tutmuyor.' tic = time.time() if len(boxes) == 0: whichHand = 'Tutmuyor.' mp_drawing.draw_landmarks( image, results.pose_landmarks, mp_pose.POSE_CONNECTIONS) # yakılan kalori = [ zaman(S)/ 60 *(MET * 3.5 * ağırlık(80 kg)] /200 if currentSecond % 2 < 0.05: if stepCounts - previousStepCounts < 100/30: totalCal += 2/60 * (80 * 2 * 3 ) / 200 elif stepCounts - previousStepCounts > 100/30 and stepCounts - previousStepCounts < 4: totalCal += 2/60 * (80 * 3.5 * 3 ) / 200 else: totalCal += 2/60 * (80 * 6 * 3 ) / 200 previousStepCounts = stepCounts # Textlerin ekrana yerlestirilmesi cv2.putText(image, "Nesne Durumu: "+whichHand, (0,60), cv2.FONT_HERSHEY_SIMPLEX, 0.8, [0,255,255], 2) cv2.putText(image, "Pozisyon: "+humanPos,(0,30), cv2.FONT_HERSHEY_SIMPLEX, 0.8, [0,255,255], 2) cv2.putText(image,f"Adim Sayisi: {stepCounts}", [0,90], cv2.FONT_HERSHEY_SIMPLEX, 0.8, [0,255,255],2) cv2.putText(image,f"Kalori: {totalCal}", [0,120], cv2.FONT_HERSHEY_SIMPLEX, 0.8, [0,255,255],2) # Resmin gosterilmesi cv2.imshow("Image", image) if __name__ == "__main__": getObjectsFromVideos(["Examples/bidonludaire.mp4"],0.5)
[ "matplotlib.pyplot.show", "cv2.dnn.NMSBoxes", "cv2.putText", "numpy.argmax", "cv2.waitKey", "matplotlib.pyplot.imshow", "cv2.cvtColor", "cv2.dnn.blobFromImage", "cv2.getTickCount", "cv2.imshow", "math.sqrt", "cv2.dnn.readNet", "time.time", "cv2.VideoCapture", "cv2.rectangle", "cv2.flip...
[((189, 282), 'cv2.dnn.readNet', 'cv2.dnn.readNet', (['"""Utilities/yolov3_training_last.weights"""', '"""Utilities/yolov3_testing.cfg"""'], {}), "('Utilities/yolov3_training_last.weights',\n 'Utilities/yolov3_testing.cfg')\n", (204, 282), False, 'import cv2\n'), ((757, 833), 'cv2.dnn.blobFromImage', 'cv2.dnn.blobFromImage', (['img', '(0.00392)', '(416, 416)', '(0, 0, 0)', '(True)'], {'crop': '(False)'}), '(img, 0.00392, (416, 416), (0, 0, 0), True, crop=False)\n', (778, 833), False, 'import cv2\n'), ((1742, 1788), 'cv2.dnn.NMSBoxes', 'cv2.dnn.NMSBoxes', (['boxes', 'confidences', '(0.5)', '(0.4)'], {}), '(boxes, confidences, 0.5, 0.4)\n', (1758, 1788), False, 'import cv2\n'), ((2160, 2175), 'matplotlib.pyplot.imshow', 'plt.imshow', (['img'], {}), '(img)\n', (2170, 2175), True, 'import matplotlib.pyplot as plt\n'), ((2180, 2190), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2188, 2190), True, 'import matplotlib.pyplot as plt\n'), ((2201, 2215), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], {}), '(0)\n', (2212, 2215), False, 'import cv2\n'), ((2221, 2244), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (2242, 2244), False, 'import cv2\n'), ((2929, 3022), 'cv2.dnn.readNet', 'cv2.dnn.readNet', (['"""Utilities/yolov3_training_last.weights"""', '"""Utilities/yolov3_testing.cfg"""'], {}), "('Utilities/yolov3_training_last.weights',\n 'Utilities/yolov3_testing.cfg')\n", (2944, 3022), False, 'import cv2\n'), ((3323, 3334), 'time.time', 'time.time', ([], {}), '()\n', (3332, 3334), False, 'import time\n'), ((1102, 1119), 'numpy.argmax', 'np.argmax', (['scores'], {}), '(scores)\n', (1111, 1119), True, 'import numpy as np\n'), ((2033, 2085), 'cv2.rectangle', 'cv2.rectangle', (['img', '(x, y)', '(x + w, y + h)', 'color', '(2)'], {}), '(img, (x, y), (x + w, y + h), color, 2)\n', (2046, 2085), False, 'import cv2\n'), ((2098, 2153), 'cv2.putText', 'cv2.putText', (['img', 'label', '(x, y + 30)', 'font', '(3)', 'color', '(2)'], {}), '(img, label, (x, y + 30), font, 3, color, 2)\n', (2109, 2153), False, 'import cv2\n'), ((3549, 3572), 'cv2.VideoCapture', 'cv2.VideoCapture', (['video'], {}), '(video)\n', (3565, 3572), False, 'import cv2\n'), ((3738, 3756), 'cv2.getTickCount', 'cv2.getTickCount', ([], {}), '()\n', (3754, 3756), False, 'import cv2\n'), ((3847, 3890), 'cv2.resize', 'cv2.resize', (['img', '[960, 540]', 'cv2.INTER_AREA'], {}), '(img, [960, 540], cv2.INTER_AREA)\n', (3857, 3890), False, 'import cv2\n'), ((6560, 6598), 'cv2.cvtColor', 'cv2.cvtColor', (['image', 'cv2.COLOR_RGB2BGR'], {}), '(image, cv2.COLOR_RGB2BGR)\n', (6572, 6598), False, 'import cv2\n'), ((6621, 6632), 'time.time', 'time.time', ([], {}), '()\n', (6630, 6632), False, 'import time\n'), ((11212, 11323), 'cv2.putText', 'cv2.putText', (['image', "('Nesne Durumu: ' + whichHand)", '(0, 60)', 'cv2.FONT_HERSHEY_SIMPLEX', '(0.8)', '[0, 255, 255]', '(2)'], {}), "(image, 'Nesne Durumu: ' + whichHand, (0, 60), cv2.\n FONT_HERSHEY_SIMPLEX, 0.8, [0, 255, 255], 2)\n", (11223, 11323), False, 'import cv2\n'), ((11331, 11437), 'cv2.putText', 'cv2.putText', (['image', "('Pozisyon: ' + humanPos)", '(0, 30)', 'cv2.FONT_HERSHEY_SIMPLEX', '(0.8)', '[0, 255, 255]', '(2)'], {}), "(image, 'Pozisyon: ' + humanPos, (0, 30), cv2.\n FONT_HERSHEY_SIMPLEX, 0.8, [0, 255, 255], 2)\n", (11342, 11437), False, 'import cv2\n'), ((11443, 11554), 'cv2.putText', 'cv2.putText', (['image', 'f"""Adim Sayisi: {stepCounts}"""', '[0, 90]', 'cv2.FONT_HERSHEY_SIMPLEX', '(0.8)', '[0, 255, 255]', '(2)'], {}), "(image, f'Adim Sayisi: {stepCounts}', [0, 90], cv2.\n FONT_HERSHEY_SIMPLEX, 0.8, [0, 255, 255], 2)\n", (11454, 11554), False, 'import cv2\n'), ((11561, 11666), 'cv2.putText', 'cv2.putText', (['image', 'f"""Kalori: {totalCal}"""', '[0, 120]', 'cv2.FONT_HERSHEY_SIMPLEX', '(0.8)', '[0, 255, 255]', '(2)'], {}), "(image, f'Kalori: {totalCal}', [0, 120], cv2.\n FONT_HERSHEY_SIMPLEX, 0.8, [0, 255, 255], 2)\n", (11572, 11666), False, 'import cv2\n'), ((11711, 11737), 'cv2.imshow', 'cv2.imshow', (['"""Image"""', 'image'], {}), "('Image', image)\n", (11721, 11737), False, 'import cv2\n'), ((4140, 4156), 'cv2.flip', 'cv2.flip', (['img', '(1)'], {}), '(img, 1)\n', (4148, 4156), False, 'import cv2\n'), ((5319, 5373), 'math.sqrt', 'math.sqrt', (['((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2)'], {}), '((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2)\n', (5328, 5373), False, 'import math\n'), ((5723, 5777), 'math.sqrt', 'math.sqrt', (['((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2)'], {}), '((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2)\n', (5732, 5777), False, 'import math\n'), ((6742, 6820), 'cv2.dnn.blobFromImage', 'cv2.dnn.blobFromImage', (['image', '(0.00392)', '(416, 416)', '(0, 0, 0)', '(True)'], {'crop': '(False)'}), '(image, 0.00392, (416, 416), (0, 0, 0), True, crop=False)\n', (6763, 6820), False, 'import cv2\n'), ((8127, 8173), 'cv2.dnn.NMSBoxes', 'cv2.dnn.NMSBoxes', (['boxes', 'confidences', '(0.5)', '(0.4)'], {}), '(boxes, confidences, 0.5, 0.4)\n', (8143, 8173), False, 'import cv2\n'), ((10299, 10310), 'time.time', 'time.time', ([], {}), '()\n', (10308, 10310), False, 'import time\n'), ((4015, 4029), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (4026, 4029), False, 'import cv2\n'), ((7247, 7264), 'numpy.argmax', 'np.argmax', (['scores'], {}), '(scores)\n', (7256, 7264), True, 'import numpy as np\n'), ((8511, 8565), 'cv2.rectangle', 'cv2.rectangle', (['image', '(x, y)', '(x + w, y + h)', 'color', '(4)'], {}), '(image, (x, y), (x + w, y + h), color, 4)\n', (8524, 8565), False, 'import cv2\n'), ((8594, 8651), 'cv2.putText', 'cv2.putText', (['image', 'label', '(x, y + 30)', 'font', '(3)', 'color', '(4)'], {}), '(image, label, (x, y + 30), font, 3, color, 4)\n', (8605, 8651), False, 'import cv2\n')]
# Author: 14281055 <NAME>U # File Name: import matplotlib.pyplot import pybrain.datasets import pybrain.tools.shortcuts import pybrain.utilities import pybrain.structure import pybrain.supervised.trainers import numpy import Repository def percent_error(out, true, threshold=30): out_array = numpy.array(out).flatten() true_array = numpy.array(true).flatten() wrong_number = 0 for index in range(out_array.size): if numpy.abs(out_array[index] - true_array[index]) > threshold: wrong_number += 1 return 100. * float(wrong_number) / float(out_array.size) def get_classification_data_set(input_np_array, target_np_array, **kwargs): classification_data_set = pybrain.datasets.ClassificationDataSet(input_np_array.shape[1], target_np_array.shape[1], **kwargs) for sample_index in range(input_np_array.shape[0]): classification_data_set.appendLinked(input_np_array[sample_index], target_np_array[sample_index]) return classification_data_set def classification_predict(train_input_file_path, train_target_file_path, test_input_file_path, test_target_file_path, test_predict_file_path, layer_node_number_list): if layer_node_number_list[-1] < 2: return class_labels = list(range(layer_node_number_list[-1])) print('\rReading Data...', end='') train_classification_data_set = get_classification_data_set( Repository.excel_to_np_array(train_input_file_path), Repository.convert_to_one_hot(Repository.excel_to_np_array(train_target_file_path), layer_node_number_list[-1]), nb_classes=layer_node_number_list[-1], class_labels=class_labels ) test_classification_data_set = get_classification_data_set( Repository.excel_to_np_array(test_input_file_path), Repository.excel_to_np_array(test_target_file_path), ) print('\rCreating Neural Network...', end='') network = pybrain.tools.shortcuts.buildNetwork(*layer_node_number_list, outclass=pybrain.structure.SoftmaxLayer) bp_trainer = pybrain.supervised.trainers.BackpropTrainer( network, train_classification_data_set, batchlearning=True ) print('\rTraining...', end='') training_errors, validation_errors = bp_trainer.trainUntilConvergence(maxEpochs=10000) print('\rPrinting Training And Validation Error...', end='') matplotlib.pyplot.plot(training_errors, 'b', validation_errors, 'r') matplotlib.pyplot.show() print('\rTesting...', end='') test_predict = bp_trainer.testOnClassData(test_classification_data_set) print('\rGetting Testing Percent Error...', end='') test_percent_error = percent_error( test_predict, test_classification_data_set['target'] ) print('\rSaving Testing Predict Output...', end='') Repository.np_array_to_excel(numpy.atleast_2d(test_predict).T, test_predict_file_path) print("\rEpoch:%d Test Error:%5.2f%%" % (bp_trainer.totalepochs, test_percent_error)) if __name__ == '__main__': classification_predict( r'C:\Users\陈力恒\Downloads\VulnerabilitySituation\Backup\Backup2\train_input.xlsx', r'C:\Users\陈力恒\Downloads\VulnerabilitySituation\Backup\Backup2\train_target.xlsx', r'C:\Users\陈力恒\Downloads\VulnerabilitySituation\Backup\Backup2\test_input.xlsx', r'C:\Users\陈力恒\Downloads\VulnerabilitySituation\Backup\Backup2\test_target.xlsx', r'C:\Users\陈力恒\Downloads\VulnerabilitySituation\Backup\Backup2\test_predict_125_25_300.xlsx', [125, 25, 300] )
[ "numpy.abs", "Repository.excel_to_np_array", "numpy.array", "numpy.atleast_2d" ]
[((1588, 1639), 'Repository.excel_to_np_array', 'Repository.excel_to_np_array', (['train_input_file_path'], {}), '(train_input_file_path)\n', (1616, 1639), False, 'import Repository\n'), ((1951, 2001), 'Repository.excel_to_np_array', 'Repository.excel_to_np_array', (['test_input_file_path'], {}), '(test_input_file_path)\n', (1979, 2001), False, 'import Repository\n'), ((2011, 2062), 'Repository.excel_to_np_array', 'Repository.excel_to_np_array', (['test_target_file_path'], {}), '(test_target_file_path)\n', (2039, 2062), False, 'import Repository\n'), ((299, 315), 'numpy.array', 'numpy.array', (['out'], {}), '(out)\n', (310, 315), False, 'import numpy\n'), ((343, 360), 'numpy.array', 'numpy.array', (['true'], {}), '(true)\n', (354, 360), False, 'import numpy\n'), ((443, 490), 'numpy.abs', 'numpy.abs', (['(out_array[index] - true_array[index])'], {}), '(out_array[index] - true_array[index])\n', (452, 490), False, 'import numpy\n'), ((1679, 1731), 'Repository.excel_to_np_array', 'Repository.excel_to_np_array', (['train_target_file_path'], {}), '(train_target_file_path)\n', (1707, 1731), False, 'import Repository\n'), ((3097, 3127), 'numpy.atleast_2d', 'numpy.atleast_2d', (['test_predict'], {}), '(test_predict)\n', (3113, 3127), False, 'import numpy\n')]
import matplotlib.pyplot as plt import pandas as pd import numpy as np from matplotlib.ticker import PercentFormatter data = pd.read_csv('C:\\Users\\stewue\\OneDrive - Wuersten\\Uni\\19_HS\\Masterarbeit\\Repo\\Evaluation\\RQ1_Results\\current-commit\\merged-isMain-header.csv') def update(df): if df['jmhParamCount'] == 0: return 0 else: return df['parameterizationCombinations'] updated = data.apply(update, axis=1) values = updated[updated > 1] valuesAll, base = np.histogram(values, bins=29, range=[2, 30], weights=np.ones(len(values)) / len(values)) cumulativeAll = np.cumsum(valuesAll) fig = plt.figure() total = values.size # absolute ax1 = fig.add_subplot() ax1.plot(base[:-1], cumulativeAll * total) ax1.set_ylabel('# benchmarks') ax1.set_ylim(0, total) # relative ax2 = ax1.twinx() plt.gca().yaxis.set_major_formatter(PercentFormatter(1, 0)) ax2.plot(base[:-1], cumulativeAll) ax2.set_ylabel('# benchmarks [cumulative %]') ax2.set_ylim(0, 1) plt.xticks([2, 5, 10, 15, 20, 25, 30]) ax1.set_xlabel('# parameterization combinations') plt.tight_layout() #plt.show() plt.savefig('C:\\Users\\stewue\\OneDrive - Wuersten\\Uni\\19_HS\\Masterarbeit\\Repo\\Evaluation\\RQ1_Results\\images\\parameterization_combinations.pdf') s10 = values[values <= 10] print("<=10: " + str(s10.size / total)) print("<=10: " + str(s10.size)) print("total: " + str(total))
[ "pandas.read_csv", "numpy.cumsum", "matplotlib.pyplot.figure", "matplotlib.ticker.PercentFormatter", "matplotlib.pyplot.gca", "matplotlib.pyplot.xticks", "matplotlib.pyplot.tight_layout", "matplotlib.pyplot.savefig" ]
[((126, 288), 'pandas.read_csv', 'pd.read_csv', (['"""C:\\\\Users\\\\stewue\\\\OneDrive - Wuersten\\\\Uni\\\\19_HS\\\\Masterarbeit\\\\Repo\\\\Evaluation\\\\RQ1_Results\\\\current-commit\\\\merged-isMain-header.csv"""'], {}), "(\n 'C:\\\\Users\\\\stewue\\\\OneDrive - Wuersten\\\\Uni\\\\19_HS\\\\Masterarbeit\\\\Repo\\\\Evaluation\\\\RQ1_Results\\\\current-commit\\\\merged-isMain-header.csv'\n )\n", (137, 288), True, 'import pandas as pd\n'), ((598, 618), 'numpy.cumsum', 'np.cumsum', (['valuesAll'], {}), '(valuesAll)\n', (607, 618), True, 'import numpy as np\n'), ((626, 638), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (636, 638), True, 'import matplotlib.pyplot as plt\n'), ((983, 1021), 'matplotlib.pyplot.xticks', 'plt.xticks', (['[2, 5, 10, 15, 20, 25, 30]'], {}), '([2, 5, 10, 15, 20, 25, 30])\n', (993, 1021), True, 'import matplotlib.pyplot as plt\n'), ((1072, 1090), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (1088, 1090), True, 'import matplotlib.pyplot as plt\n'), ((1103, 1266), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""C:\\\\Users\\\\stewue\\\\OneDrive - Wuersten\\\\Uni\\\\19_HS\\\\Masterarbeit\\\\Repo\\\\Evaluation\\\\RQ1_Results\\\\images\\\\parameterization_combinations.pdf"""'], {}), "(\n 'C:\\\\Users\\\\stewue\\\\OneDrive - Wuersten\\\\Uni\\\\19_HS\\\\Masterarbeit\\\\Repo\\\\Evaluation\\\\RQ1_Results\\\\images\\\\parameterization_combinations.pdf'\n )\n", (1114, 1266), True, 'import matplotlib.pyplot as plt\n'), ((858, 880), 'matplotlib.ticker.PercentFormatter', 'PercentFormatter', (['(1)', '(0)'], {}), '(1, 0)\n', (874, 880), False, 'from matplotlib.ticker import PercentFormatter\n'), ((822, 831), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (829, 831), True, 'import matplotlib.pyplot as plt\n')]
import os from glob import glob import json import numpy as np from tensorflow.keras.utils import Progbar from ..abstract import Loader from .utils import get_class_names class FAT(Loader): """ Dataset loader for the falling things dataset (FAT). # Arguments path: String indicating full path to dataset e.g. /home/user/fat/ split: String determining the data split to load. e.g. `train`, `val` or `test` class_names: `all` or list. If list it should contain as elements strings indicating each class name. # References - [Deep Object Pose Estimation (DOPE)](https://github.com/NVlabs/Deep_Object_Pose) """ # TODO: Allow selection of class_names. def __init__(self, path, split='train', class_names='all'): if class_names == 'all': class_names = get_class_names('FAT') self.class_to_arg = dict( zip(class_names, list(range(len(class_names))))) super(FAT, self).__init__(path, split, class_names, 'FAT') def load_data(self): scene_names = glob(self.path + 'mixed/*') image_paths, label_paths = [], [] for scene_name in scene_names: scene_image_paths, scene_label_paths = [], [] for image_side in ['left', 'right']: image_names = glob(scene_name + '/*%s.jpg' % image_side) side_image_paths = sorted(image_names, key=self._base_number) label_names = glob(scene_name + '/0*%s.json' % image_side) side_label_paths = sorted(label_names, key=self._base_number) scene_image_paths = scene_image_paths + side_image_paths scene_label_paths = scene_label_paths + side_label_paths image_paths = image_paths + scene_image_paths label_paths = label_paths + scene_label_paths self.data = [] progress_bar = Progbar(len(image_paths)) for sample_arg, sample in enumerate(zip(image_paths, label_paths)): image_path, label_path = sample if not self._valid_name_match(image_path, label_path): raise ValueError('Invalid name match:', image_path, label_path) boxes = self._extract_boxes(label_path) if boxes is None: continue self.data.append({'image': image_path, 'boxes': boxes}) progress_bar.update(sample_arg + 1) return self.data def _extract_boxes(self, json_filename): json_data = json.load(open(json_filename, 'r')) num_objects = len(json_data['objects']) if num_objects == 0: return None box_data = np.zeros((num_objects, 5)) for object_arg, object_data in enumerate(json_data['objects']): bounding_box = object_data['bounding_box'] y_min, x_min = bounding_box['top_left'] y_max, x_max = bounding_box['bottom_right'] x_min, y_min = x_min / 960., y_min / 540. x_max, y_max = x_max / 960., y_max / 540. box_data[object_arg, :4] = x_min, y_min, x_max, y_max class_name = object_data['class'][:-4] box_data[object_arg, -1] = self.class_to_arg[class_name] return box_data def _base_number(self, filename): order = os.path.basename(filename) order = order.split('.')[0] order = float(order) return order def _valid_name_match(self, image_path, label_path): image_name = os.path.basename(image_path) label_name = os.path.basename(label_path) return image_name[:-3] == label_name[:-4]
[ "os.path.basename", "numpy.zeros", "glob.glob" ]
[((1110, 1137), 'glob.glob', 'glob', (["(self.path + 'mixed/*')"], {}), "(self.path + 'mixed/*')\n", (1114, 1137), False, 'from glob import glob\n'), ((2702, 2728), 'numpy.zeros', 'np.zeros', (['(num_objects, 5)'], {}), '((num_objects, 5))\n', (2710, 2728), True, 'import numpy as np\n'), ((3337, 3363), 'os.path.basename', 'os.path.basename', (['filename'], {}), '(filename)\n', (3353, 3363), False, 'import os\n'), ((3529, 3557), 'os.path.basename', 'os.path.basename', (['image_path'], {}), '(image_path)\n', (3545, 3557), False, 'import os\n'), ((3579, 3607), 'os.path.basename', 'os.path.basename', (['label_path'], {}), '(label_path)\n', (3595, 3607), False, 'import os\n'), ((1356, 1398), 'glob.glob', 'glob', (["(scene_name + '/*%s.jpg' % image_side)"], {}), "(scene_name + '/*%s.jpg' % image_side)\n", (1360, 1398), False, 'from glob import glob\n'), ((1507, 1551), 'glob.glob', 'glob', (["(scene_name + '/0*%s.json' % image_side)"], {}), "(scene_name + '/0*%s.json' % image_side)\n", (1511, 1551), False, 'from glob import glob\n')]
# -*- coding: utf-8 -*- import pandas as pd import numpy as np from .utils_phi import _phi from .utils_get_r import _get_r def entropy_approximate(signal, order=2, r="default"): """Compute the approximate entropy (ApEn). Approximate entropy is a technique used to quantify the amount of regularity and the unpredictability of fluctuations over time-series data. The advantages of ApEn include lower computational demand (ApEn can be designed to work for small data samples (< 50 data points) and can be applied in real tim) and less sensitive to noise. However, ApEn is heavily dependent on the record length and lacks relative consistency. Parameters ---------- signal : list, array or Series The signal channel in the form of a vector of values. order : int The embedding dimension (often denoted as 'm'), i.e., the length of compared run of data. Typically 1, 2 or 3. r : float Tolerance (i.e., filtering level - max absolute difference between segments). If 'default', will be set to 0.2 times the standard deviation of the signal. See Also -------- entropy_shannon, entropy_sample, entropy_fuzzy Returns ---------- float The approximate entropy as float value. Examples ---------- >>> import neurokit2 as nk >>> >>> signal = nk.signal_simulate(duration=2, frequency=5) >>> nk.entropy_approximate(signal[0:100]) 0.2227235476697098 References ----------- - `EntroPy` <https://github.com/raphaelvallat/entropy>`_ - <NAME>., <NAME>., & <NAME>. (2009). Entropy and complexity measures for EEG signal classification of schizophrenic and control participants. Artificial intelligence in medicine, 47(3), 263-274. """ r = _get_r(signal, r=r) # Get phi phi = _phi(signal, order=order, r=r, metric='chebyshev', approximate=True) return(np.abs(np.subtract(phi[0], phi[1])))
[ "numpy.subtract" ]
[((1900, 1927), 'numpy.subtract', 'np.subtract', (['phi[0]', 'phi[1]'], {}), '(phi[0], phi[1])\n', (1911, 1927), True, 'import numpy as np\n')]
""" Companion code for the Roam blog post on hyperparameter optimization. """ import itertools as it import matplotlib import matplotlib.pyplot as plt import numpy as np from operator import itemgetter import pandas as pd import random from scipy import stats from time import time from hyperopt import fmin, tpe, hp, STATUS_OK, Trials from skopt import gp_minimize, forest_minimize, gbrt_minimize from skopt.space import Categorical from sklearn.datasets import make_classification from sklearn.cross_validation import cross_val_score, StratifiedKFold from sklearn.metrics import accuracy_score from sklearn.linear_model import LogisticRegression from xgboost import XGBClassifier # Ignore these warnings, which are related to the bleeding # edge sklearn we're using. import warnings import sklearn.metrics.base warnings.filterwarnings("ignore", category=DeprecationWarning) __author__ = '<NAME> and <NAME>' __version__ = '1.0' __license__ = 'Apache License Version 2.0, January 2004 http://www.apache.org/licenses/' plt.style.use('../../src/roam.mplstyle') LOG_LOSS = 'log_loss' # Newer versions will use 'neg_log_loss' def artificial_dataset( n_samples=1000, n_features=100, n_classes=3, random_state=None): """ sklearn random classification dataset generation using `sklearn.datasets.make_classification`. Parameters ---------- n_samples : int n_features : int n_classes : int random_state : int or None Returns ------- (X, y) The design matrix `X` and target `y`. """ n_informative = int(0.8 * n_features) n_redundant = int(0.05 * n_features) X, y = make_classification( n_samples=n_samples, n_features=n_features, n_informative=n_informative, n_redundant=n_redundant, n_classes=n_classes, random_state=random_state) return (X, y) def assess( X, y, search_func, model_class, param_grid, xval_indices, loss=LOG_LOSS, test_metric=accuracy_score, dataset_name=None, search_func_args={}): """ The core of the experimental framework. This runs cross-validation and, for the inner loop, does cross-validation to find the optimal hyperparameters according to `search_func`. These optimal parameters are then used for an assessment in the outer cross-validation run. Parameters ---------- X : np.array The design matrix, dimension `(n_samples, n_features)`. y : list or np.array The target, of dimension `n_samples`. search_func : function The search function to use. Can be `grid_search`, `randomized_search`, `hyperopt_search`, `skopt_gp_minimize`, `skopt_forest_minimize`, or `skopt_forest_gbrt`, all defined in this module. This choice has to be compatible with `param_grid`, in the sense that `grid_search` and `randomized_search` require a dict from strings to lists of values, `hyperopt_search` requires a dict from strings to hyperopt sampling functions, and the `skopt` functions require dicts from strings to (upper, lower) pairs of special `skopt` functions. model_class : classifier A classifier model in the mode of `sklearn`, with at least `fit` and `predict` methods operating on things like `X` and `y`. param_grid : dict Map from parameter names to appropriate specifications of appropriate values for that parameter. This is not the expanded grid, but rather the simple map that can be expanded by `expand_grid` below (though not all methods call for that). This has to be compatible with `search_func`, and all the values must be suitable arguments to `model_class` instances. loss : function or string An appropriate loss function or string recognizable by `sklearn.cross_validation.cross_val_score`. In `sklearn`, scores are positive and losses are negative because they maximize, but here we are minimizing so we always want smaller to mean better. test_metric : function An `sklearn.metrics` function. xval_indices : list List of train and test indices into `X` and `y`. This defines the cross-validation. This is done outside of this method to allow for identical splits across different experiments. dataset_name : str or None Name for the dataset being analyzed. For book-keeping and display only. search_func_args : dict Keyword arguments to feed to `search_func`. Returns ------- dict Accumulated information about the experiment: {'Test accuracy': list of float, 'Cross-validation time (in secs.)':list of float, 'Parameters sampled': list of int, 'Method': search_func.__name__, 'Model': model_class.__name__, 'Dataset': dataset_name, 'Best parameters': list of dict, 'Mean test accuracy': float, 'Mean cross-validation time (in secs.)': float, 'Mean parameters sampled': float} """ data = {'Test accuracy': [], 'Cross-validation time (in secs.)': [], 'Parameters sampled': [], 'Best parameters': [], 'Method': search_func.__name__, 'Model': model_class.__name__, 'Dataset': dataset_name, 'Best parameters':[]} for cv_index, (train_index, test_index) in enumerate(xval_indices, start=1): print("\t{}".format(cv_index)) X_train, X_test = X[train_index], X[test_index] y_train, y_test = y[train_index], y[test_index] start = time() results = search_func( X_train, y_train, model_class, param_grid, loss, **search_func_args) data['Cross-validation time (in secs.)'].append(time() - start) data['Parameters sampled'].append(len(results)) best_params = sorted(results, key=itemgetter('loss'), reverse=False) best_params = best_params[0]['params'] data['Best parameters'].append(best_params) bestmod = model_class(**best_params) bestmod.fit(X_train, y_train) predictions = bestmod.predict(X_test) data['Test accuracy'].append(test_metric(y_test, predictions)) data['Mean test accuracy'] = np.mean( data['Test accuracy']) data['Mean cross-validation time (in secs.)'] = np.mean( data['Cross-validation time (in secs.)']) data['Mean parameters sampled'] = np.mean( data['Parameters sampled']) return data def get_cross_validation_indices(X, y, n_folds=5, random_state=None): """ Use `StratifiedKFold` to create an `n_folds` cross-validator for the dataset defined by `X` and y`. Only `y` is used, but both are given for an intuitive interface; `X` could just as easily be used. """ return StratifiedKFold(y, n_folds=n_folds, random_state=random_state) def random_search( X_train, y_train, model_class, param_grid, loss, sampsize=None): """ Random search over the grid defined by `param_grid`. Parameters ---------- X_train : np.array The design matrix, dimension `(n_samples, n_features)`. y_train : list or np.array The target, of dimension `n_samples`. model_class : classifier A classifier model in the mode of `sklearn`, with at least `fit` and `predict` methods operating on things like `X` and `y`. param_grid : dict Map from parameter names to lists of appropriate values for that parameter. This is not the expanded grid, but rather the simple map that can be expanded by `expand_grid` below. This method performs the expansion. loss : function or string An appropriate loss function or string recognizable by sklearn.cross_validation.cross_val_score. In sklearn, scores are positive and losses are negative because they maximize, but here we are minimizing so we always want smaller to mean better. sampsize : int or None Number of samples to take from the grid. If `None`, then `sampsize` is half the size of the full grid. Returns ------- list of dict Each has keys 'loss' and 'params', where 'params' stores the values from `param_grid` for that run. The primary organizing value is 'loss'. Example ------- >>> param_grid = { 'max_depth' : [4, 8], 'learning_rate' : [0.01, 0.3], 'n_estimators' : [20, 50], 'objective' : ['multi:softprob'], 'gamma' : [0, 0.25], 'min_child_weight' : [1], 'subsample' : [1], 'colsample_bytree' : [1]} >>> res = random_search(X, y, XGBClassifier, param_grid, LOG_LOSS) To be followed by (see below): >>> best_params, best_loss = best_results(res) """ exapnded_param_grid = expand_grid(param_grid) if sampsize == None: sampsize = int(len(exapnded_param_grid) / 2.0) samp = random.sample(exapnded_param_grid, sampsize) results = [] for params in samp: err = cross_validated_scorer( X_train, y_train, model_class, params, loss) results.append({'loss': err, 'params': params}) return results def grid_search(X_train, y_train, model_class, param_grid, loss): """ Full grid search over the grid defined by `param_grid`. Parameters ---------- X_train : np.array The design matrix, dimension `(n_samples, n_features)`. y_train : list or np.array The target, of dimension `n_samples`. model_class : classifier A classifier model in the mode of `sklearn`, with at least `fit` and `predict` methods operating on things like `X` and `y`. param_grid : dict Map from parameter names to lists of appropriate values for that parameter. This is not the expanded grid, but rather the simple map that can be expanded by `expand_grid` below. This method performs the expansion. loss : function or string An appropriate loss function or string recognizable by sklearn.cross_validation.cross_val_score. In sklearn, scores are positive and losses are negative because they maximize, but here we are minimizing so we always want smaller to mean better. Returns ------- list of dict Each has keys 'loss' and 'params', where 'params' stores the values from `param_grid` for that run. The primary organizing value is 'loss'. Example ------- >>> param_grid = { 'max_depth' : [4, 8], 'learning_rate' : [0.01, 0.3], 'n_estimators' : [20, 50], 'objective' : ['multi:softprob'], 'gamma' : [0, 0.25], 'min_child_weight' : [1], 'subsample' : [1], 'colsample_bytree' : [1]} >>> res = grid_search(X, y, XGBClassifier, param_grid, LOG_LOSS) To be followed by (see below): >>> best_params, best_loss = best_results(res) """ results = [] expanded_param_grid = expand_grid(param_grid) for params in expanded_param_grid: err = cross_validated_scorer( X_train, y_train, model_class, params, loss) results.append({'loss': err, 'params': params}) return results def expand_grid(param_grid): """ Expand `param_grid` to the full grid, as a list of dicts. Parameters ---------- param_grid : dict Map from parameter names to lists of appropriate values for that parameter. This is not the expanded grid, but rather the simple map that can be expanded by `expand_grid` below. This method performs the expansion. Returns ------- list of dict If `param_grid` was {'foo': [1,2], 'bar': [3,4]} Then the return value would be [{'foo': 1, 'bar': 3}, {'foo': 1, 'bar': 4}, {'foo': 2, 'bar': 3}, {'foo': 2, 'bar': 4}] """ varNames = sorted(param_grid) return [dict(zip(varNames, prod)) for prod in it.product(*(param_grid[varName] for varName in varNames))] def cross_validated_scorer( X_train, y_train, model_class, params, loss, kfolds=5): """ The scoring function used through this module, by all search functions. Parameters ---------- X_train : np.array The design matrix, dimension `(n_samples, n_features)`. y_train : list or np.array The target, of dimension `n_samples`. model_class : classifier A classifier model in the mode of `sklearn`, with at least `fit` and `predict` methods operating on things like `X` and `y`. params : dict Map from parameter names to single appropriate values for that parameter. This will be used to build a model from `model_class`. loss : function or string An appropriate loss function or string recognizable by sklearn.cross_validation.cross_val_score. In sklearn, scores are positive and losses are negative because they maximize, but here we are minimizing so we always want smaller to mean better. kfolds : int Number of cross-validation runs to do. Returns ------- float Average loss over the `kfolds` runs. """ mod = model_class(**params) cv_score = -1 * cross_val_score( mod, X_train, y=y_train, scoring=loss, cv=kfolds, n_jobs=1).mean() return cv_score def hyperopt_search( X_train, y_train, model_class, param_grid, loss, max_evals=100): """ Search according to hyperopt's Tree of Parzen Estimator. Parameters ---------- X_train : np.array The design matrix, dimension `(n_samples, n_features)`. y_train : list or np.array The target, of dimension `n_samples`. model_class : classifier A classifier model in the mode of `sklearn`, with at least `fit` and `predict` methods operating on things like `X` and `y`. param_grid : dict Map from parameter names to `hyperopt` sampling functions. The parameter names need to work with `model_class`, and the values specifying how to sample values. loss : function or string An appropriate loss function or string recognizable by sklearn.cross_validation.cross_val_score. In sklearn, scores are positive and losses are negative because they maximize, but here we are minimizing so we always want smaller to mean better. max_evals : int Number of evaluations to do. Returns ------- list of dict Each has keys 'loss' and 'params', where 'params' stores the values from `param_grid` for that run. The primary organizing value is 'loss'. These values are accumulated and stored by the `Trials` instance used in the call to `fmin`. A 'status' record is also retained but not used elsewhere in the module. Example ------- >>> hyperopt_grid = { 'max_depth' : hp.choice('max_depth', range(4, 13, 1)), 'learning_rate' : hp.quniform('learning_rate', 0.01, 0.5, 0.01), 'n_estimators' : hp.choice('n_estimators', range(20, 205, 5)), 'objective' : 'multi:softprob', 'gamma' : hp.quniform('gamma', 0, 0.50, 0.01), 'min_child_weight' : hp.quniform('min_child_weight', 1, 5, 1), 'subsample' : hp.quniform('subsample', 0.1, 1, 0.01), 'colsample_bytree' : hp.quniform('colsample_bytree', 0.1, 1.0, 0.01)} >>> res = hyperopt_search(X, y, XGBClassifier, hyperopt_grid, LOG_LOSS, max_evals=10) To be followed by (see below): >>> best_params, best_loss = best_results(res) """ def objective(params): err = cross_validated_scorer( X_train, y_train, model_class, params, loss) return {'loss': err, 'params': params, 'status': STATUS_OK} trials = Trials() results = fmin( objective, param_grid, algo=tpe.suggest, trials=trials, max_evals=max_evals) return trials.results def skopt_search( X_train, y_train, model_class, param_grid, loss, skopt_method, n_calls=100): """ General method for applying `skopt_method` to the data. Parameters ---------- X_train : np.array The design matrix, dimension `(n_samples, n_features)`. y_train : list or np.array The target, of dimension `n_samples`. model_class : classifier A classifier model in the mode of `sklearn`, with at least `fit` and `predict` methods operating on things like `X` and `y`. param_grid : dict Map from parameter names to pairs of values specifying the upper and lower ends of the space from which to sample. The values can also be directly specified as `skopt` objects like `Categorical`. loss : function or string An appropriate loss function or string recognizable by sklearn.cross_validation.cross_val_score. In sklearn, scores are positive and losses are negative because they maximize, but here we are minimizing so we always want smaller to mean better. skopt_method : skopt function Can be `gp_minimize`, `forest_minimize`, or `gbrt_minimize`. n_calls : int Number of evaluations to do. Returns ------- list of dict Each has keys 'loss' and 'params', where 'params' stores the values from `param_grid` for that run. The primary organizing value is 'loss'. """ param_keys, param_vecs = zip(*param_grid.items()) param_keys = list(param_keys) param_vecs = list(param_vecs) def skopt_scorer(param_vec): params = dict(zip(param_keys, param_vec)) err = cross_validated_scorer( X_train, y_train, model_class, params, loss) return err outcome = skopt_method(skopt_scorer, list(param_vecs), n_calls=n_calls) results = [] for err, param_vec in zip(outcome.func_vals, outcome.x_iters): params = dict(zip(param_keys, param_vec)) results.append({'loss': err, 'params': params}) return results def skopt_gp_search( X_train, y_train, model_class, param_grid, loss, n_calls=100): """`skopt` according to the Gaussian Process search method. For details on the parameters, see `skopt_search`. Example ------- >>> skopt_grid = { 'max_depth': (4, 12), 'learning_rate': (0.01, 0.5), 'n_estimators': (20, 200), 'objective' : Categorical(('multi:softprob',)), 'gamma': (0, 0.5), 'min_child_weight': (1, 5), 'subsample': (0.1, 1), 'colsample_bytree': (0.1, 1)} >>> res = skopt_gp_search(X, y, XGBClassifier, skopt_grid, LOG_LOSS, n_calls=10) To be followed by (see below): >>> best_params, best_loss = best_results(res) """ return skopt_search( X_train, y_train, model_class, param_grid, loss, gp_minimize, n_calls=n_calls) def skopt_forest_search( X_train, y_train, model_class, param_grid, loss, n_calls=100): """`skopt` according to the decision tree search method. For details on the parameters, see `skopt_search`. Example ------- >>> skopt_grid = { 'max_depth': (4, 12), 'learning_rate': (0.01, 0.5), 'n_estimators': (20, 200), 'objective' : Categorical(('multi:softprob',)), 'gamma': (0, 0.5), 'min_child_weight': (1, 5), 'subsample': (0.1, 1), 'colsample_bytree': (0.1, 1)} >>> res = skopt_forest_search(X, y, XGBClassifier, skopt_grid, LOG_LOSS, n_calls=10) To be followed by (see below): >>> best_params, best_loss = best_results(res) """ return skopt_search( X_train, y_train, model_class, param_grid, loss, forest_minimize, n_calls=n_calls) def skopt_gbrt_search( X_train, y_train, model_class, param_grid, loss, n_calls=100): """`skopt` according to the gradient-boosting-tree search method. For details on the parameters, see `skopt_search`. Example ------- >>> skopt_grid = { 'max_depth': (4, 12), 'learning_rate': (0.01, 0.5), 'n_estimators': (20, 200), 'objective' : Categorical(('multi:softprob',)), 'gamma': (0, 0.5), 'min_child_weight': (1, 5), 'subsample': (0.1, 1), 'colsample_bytree': (0.1, 1)} >>> res = skopt_gbrt_search(X, y, XGBClassifier, skopt_grid, LOG_LOSS, n_calls=10) To be followed by (see below): >>> best_params, best_loss = best_results(res) """ return skopt_search( X_train, y_train, model_class, param_grid, loss, gbrt_minimize, n_calls=n_calls) def prepare_summary(results): """Format the `results` dictionary into a `pandas` `DataFrame`, with columns 'Method', 'Mean parameters sampled', 'Mean test accuracy', 'Mean cross-validation time (in secs.)'.""" results = {k:v for k,v in results.items() if k not in {'Test accuracy', 'Cross-validation time (in secs.)', 'Parameters sampled'}} df = pd.DataFrame([results]) df = df[['Method', 'Mean parameters sampled', 'Mean test accuracy', 'Mean cross-validation time (in secs.)']] return df def prepare_summaries(results_list): """Format all the results dictionaries in `results_list` into a single pandas `DataFrame`. """ dfs = [] for results in results_list: dfs.append(prepare_summary(results)) combo = pd.concat(dfs, axis=0) combo.index = range(1,len(combo)+1) return combo def run_experiments( experimental_run, dataset, model_class=XGBClassifier, loss=LOG_LOSS, test_metric=accuracy_score, random_state=None, dataset_name=None): """ Basic experimental framework. Parameters ---------- experimental_run : list of tuples These tuples should have exactly three members: the first one of `grid_search`, `randomized_search`, `hyperopt_search`, `skopt_gp_minimize`, `skopt_forest_minimize`, or `skopt_forest_gbrt`, the second an appropriate `param_grid` dict for that function, and the third a dict specifying keyword arguments to the search function. dataset : (np.array, iterable) A dataset (X, y) where `X` has dimension `(n_samples, n_features)` and `y` has dimension `n_samples`. model_class : classifier A classifier model in the mode of `sklearn`, with at least `fit` and `predict` methods operating on things like `X` and `y`. loss : function or string An appropriate loss function or string recognizable by `sklearn.cross_validation.cross_val_score`. In `sklearn`, scores are positive and losses are negative because they maximize, but here we are minimizing so we always want smaller to mean better. test_metric : function An `sklearn.metrics` function. random_state : int dataset_name : str or None Informal name to give the dataset. Purely for book-keeping. Returns ------- list of dict Each dict is a results dictionary of the sort returned by `assess`. """ X, y = dataset skf = get_cross_validation_indices( X, y, random_state=random_state) all_results = [] # This loop can easily be parallelized, but doing so can # be tricky on some systems, since `cross_val_score` # calls `joblib` even if `n_jobs=1`, resulting in # nested parallel jobs even if there is no actual # parallelization elsewhere in the experimental run. for search_func, param_grid, kwargs in experimental_run: print(search_func.__name__) all_results.append( assess( X, y, search_func=search_func, model_class=XGBClassifier, param_grid=param_grid, xval_indices=skf, loss=loss, test_metric=test_metric, dataset_name=dataset_name, search_func_args=kwargs)) return all_results def representation_size_experiments( experimental_run, n_samples=100, min_features=50, max_features=100, increment=50, loss=LOG_LOSS, test_metric=accuracy_score, random_state=None): """Run a series of experiments with `experimental_run` exploring `n_feature` sizes from `min_features` to `max_features` (inclusive) in increments of `increment`. Parameters ---------- experimental_run : list of tuples These tuples should have exactly three members: the first one of `grid_search`, `randomized_search`, `hyperopt_search`, `skopt_gp_minimize`, `skopt_forest_minimize`, or `skopt_forest_gbrt`, the second an appropriate `param_grid` dict for that function, and the third a dict specifying keyword arguments to the search function. n_samples : int Number of examples. min_features : int Smallest feature representation size. max_features : int Largest feature representation size. increment : int Increments between `min_features` and `max_features`. loss : function or string An appropriate loss function or string recognizable by `sklearn.cross_validation.cross_val_score`. In `sklearn`, scores are positive and losses are negative because they maximize, but here we are minimizing so we always want smaller to mean better. test_metric : function An `sklearn.metrics` function. random_state : int Returns ------- list of values returned by `run_experiments`. """ all_results = [] for n_features in range(min_features, max_features+1, increment): dataset = artificial_dataset( n_samples=100, n_features=n_features, n_classes=3, random_state=random_state) results = run_experiments( experimental_run, dataset, loss=loss, test_metric=accuracy_score, random_state=random_state, dataset_name=n_features) all_results.append(results) return all_results def plot_representation_size_accuracy( representation_size_results, include_cis=True): """Plot the test accuracy values from the output of `representation_size_experiments`""" kwargs = { 'metric_name': 'Test accuracy', 'metric_mean_name': 'Mean test accuracy', 'ylabel': 'Test accuracy', 'value_transform': (lambda x : x), 'include_cis': include_cis, 'ylabel_overlap_threshold': 0.02} plot_representation_size(representation_size_results, **kwargs) def plot_representation_size_time( representation_size_results, include_cis=True): """Plot the cross-validation time values from the output of `representation_size_experiments`""" kwargs = { 'metric_name': 'Cross-validation time (in secs.)', 'metric_mean_name': 'Mean cross-validation time (in secs.)', 'ylabel': 'Cross-validation time (log-scale)', 'value_transform': (lambda x : np.log(x)), 'include_cis': include_cis, 'ylabel_overlap_threshold': 0.2} plot_representation_size(representation_size_results, **kwargs) def plot_representation_size( representation_size_results, metric_name='', metric_mean_name='', ylabel='', value_transform=(lambda x : x), include_cis=True, ylabel_overlap_threshold=0.2): """Generic interface for plotting the output of `representation_size_experiments`""" fig, ax = plt.subplots(1) fig.set_figwidth(10) fig.set_figheight(8) methods = set([d['Method'] for results in representation_size_results for d in results]) colors = { 'grid_search': '#212121', 'random_search': '#876DB5', 'hyperopt_search': '#4D8951', 'skopt_forest_minimize': '#0499CC', 'skopt_gp_minimize': '#03A9F4', 'skopt_forest_gbrt': '#32A8B4'} text_positions = [] for method in methods: color = colors[method] method_results = [d for results in representation_size_results for d in results if d['Method']==method] method_results = sorted(method_results, key=itemgetter('Dataset')) xpos = [d['Dataset'] for d in method_results] mus = [value_transform(d[metric_mean_name]) for d in method_results] if include_cis: cis = [value_transform(get_ci(d[metric_name])) for d in method_results] for x, ci in zip(xpos, cis): ax.plot([x,x], ci, color=color) ax.plot( xpos, mus, marker='.', linestyle='-', markersize=12, color=color) text_positions.append(mus[-1]) method_text_positions = [[p,m] for p, m in zip(text_positions, methods)] method_text_positions = sorted(method_text_positions) for i in range(len(method_text_positions)-1): here = method_text_positions[i][0] there = method_text_positions[i+1][0] if there - here < ylabel_overlap_threshold: method_text_positions[i+1][0] = here + ylabel_overlap_threshold xpad = min(xpos)*0.2 for text_pos, method in method_text_positions: ax.text(max(xpos)+(xpad*2), text_pos, method, fontsize=16, color=colors[method], va='center', weight='bold') ax.set_xlim([min(xpos)-xpad, max(xpos)+xpad]) ax.set_xlabel("Number of features") ax.set_ylabel(ylabel) def get_ci(vals, percent=0.95): """Confidence interval for `vals` from the Students' t distribution. Uses `stats.t.interval`. Parameters ---------- percent : float Size of the confidence interval. The default is 0.95. The only requirement is that this be above 0 and at or below 1. Returns ------- tuple The first member is the upper end of the interval, the second the lower end of the interval. """ if len(set(vals)) == 1: return (vals[0], vals[0]) mu = np.mean(vals) df = len(vals)-1 sigma = np.std(vals) / np.sqrt(len(vals)) return stats.t.interval(percent, df, loc=mu, scale=sigma)
[ "pandas.DataFrame", "sklearn.cross_validation.cross_val_score", "numpy.log", "warnings.filterwarnings", "random.sample", "numpy.std", "hyperopt.fmin", "sklearn.datasets.make_classification", "time.time", "matplotlib.pyplot.style.use", "numpy.mean", "scipy.stats.t.interval", "itertools.produc...
[((815, 877), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {'category': 'DeprecationWarning'}), "('ignore', category=DeprecationWarning)\n", (838, 877), False, 'import warnings\n'), ((1024, 1064), 'matplotlib.pyplot.style.use', 'plt.style.use', (['"""../../src/roam.mplstyle"""'], {}), "('../../src/roam.mplstyle')\n", (1037, 1064), True, 'import matplotlib.pyplot as plt\n'), ((1674, 1848), 'sklearn.datasets.make_classification', 'make_classification', ([], {'n_samples': 'n_samples', 'n_features': 'n_features', 'n_informative': 'n_informative', 'n_redundant': 'n_redundant', 'n_classes': 'n_classes', 'random_state': 'random_state'}), '(n_samples=n_samples, n_features=n_features,\n n_informative=n_informative, n_redundant=n_redundant, n_classes=\n n_classes, random_state=random_state)\n', (1693, 1848), False, 'from sklearn.datasets import make_classification\n'), ((6565, 6595), 'numpy.mean', 'np.mean', (["data['Test accuracy']"], {}), "(data['Test accuracy'])\n", (6572, 6595), True, 'import numpy as np\n'), ((6657, 6706), 'numpy.mean', 'np.mean', (["data['Cross-validation time (in secs.)']"], {}), "(data['Cross-validation time (in secs.)'])\n", (6664, 6706), True, 'import numpy as np\n'), ((6754, 6789), 'numpy.mean', 'np.mean', (["data['Parameters sampled']"], {}), "(data['Parameters sampled'])\n", (6761, 6789), True, 'import numpy as np\n'), ((7125, 7187), 'sklearn.cross_validation.StratifiedKFold', 'StratifiedKFold', (['y'], {'n_folds': 'n_folds', 'random_state': 'random_state'}), '(y, n_folds=n_folds, random_state=random_state)\n', (7140, 7187), False, 'from sklearn.cross_validation import cross_val_score, StratifiedKFold\n'), ((9318, 9362), 'random.sample', 'random.sample', (['exapnded_param_grid', 'sampsize'], {}), '(exapnded_param_grid, sampsize)\n', (9331, 9362), False, 'import random\n'), ((16428, 16436), 'hyperopt.Trials', 'Trials', ([], {}), '()\n', (16434, 16436), False, 'from hyperopt import fmin, tpe, hp, STATUS_OK, Trials\n'), ((16451, 16537), 'hyperopt.fmin', 'fmin', (['objective', 'param_grid'], {'algo': 'tpe.suggest', 'trials': 'trials', 'max_evals': 'max_evals'}), '(objective, param_grid, algo=tpe.suggest, trials=trials, max_evals=\n max_evals)\n', (16455, 16537), False, 'from hyperopt import fmin, tpe, hp, STATUS_OK, Trials\n'), ((21761, 21784), 'pandas.DataFrame', 'pd.DataFrame', (['[results]'], {}), '([results])\n', (21773, 21784), True, 'import pandas as pd\n'), ((22201, 22223), 'pandas.concat', 'pd.concat', (['dfs'], {'axis': '(0)'}), '(dfs, axis=0)\n', (22210, 22223), True, 'import pandas as pd\n'), ((28653, 28668), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)'], {}), '(1)\n', (28665, 28668), True, 'import matplotlib.pyplot as plt\n'), ((31170, 31183), 'numpy.mean', 'np.mean', (['vals'], {}), '(vals)\n', (31177, 31183), True, 'import numpy as np\n'), ((31262, 31312), 'scipy.stats.t.interval', 'stats.t.interval', (['percent', 'df'], {'loc': 'mu', 'scale': 'sigma'}), '(percent, df, loc=mu, scale=sigma)\n', (31278, 31312), False, 'from scipy import stats\n'), ((5821, 5827), 'time.time', 'time', ([], {}), '()\n', (5825, 5827), False, 'from time import time\n'), ((31217, 31229), 'numpy.std', 'np.std', (['vals'], {}), '(vals)\n', (31223, 31229), True, 'import numpy as np\n'), ((12436, 12494), 'itertools.product', 'it.product', (['*(param_grid[varName] for varName in varNames)'], {}), '(*(param_grid[varName] for varName in varNames))\n', (12446, 12494), True, 'import itertools as it\n'), ((28139, 28148), 'numpy.log', 'np.log', (['x'], {}), '(x)\n', (28145, 28148), True, 'import numpy as np\n'), ((6076, 6082), 'time.time', 'time', ([], {}), '()\n', (6080, 6082), False, 'from time import time\n'), ((6190, 6208), 'operator.itemgetter', 'itemgetter', (['"""loss"""'], {}), "('loss')\n", (6200, 6208), False, 'from operator import itemgetter\n'), ((13782, 13857), 'sklearn.cross_validation.cross_val_score', 'cross_val_score', (['mod', 'X_train'], {'y': 'y_train', 'scoring': 'loss', 'cv': 'kfolds', 'n_jobs': '(1)'}), '(mod, X_train, y=y_train, scoring=loss, cv=kfolds, n_jobs=1)\n', (13797, 13857), False, 'from sklearn.cross_validation import cross_val_score, StratifiedKFold\n'), ((29356, 29377), 'operator.itemgetter', 'itemgetter', (['"""Dataset"""'], {}), "('Dataset')\n", (29366, 29377), False, 'from operator import itemgetter\n')]
import numpy as np import os import six.moves.urllib as urllib import sys import tarfile import tensorflow.compat.v1 as tf import zipfile import cv2 import glob from distutils.version import StrictVersion from collections import defaultdict from io import StringIO from matplotlib import pyplot as plt from PIL import Image # This is needed since the notebook is stored in the object_detection folder. sys.path.append("..") from utils import ops as utils_ops if StrictVersion(tf.__version__) < StrictVersion('1.9.0'): raise ImportError('Please upgrade your TensorFlow installation to v1.9.* or later!') from utils import label_map_util from utils import visualization_utils as vis_util detection_graph = tf.Graph() with detection_graph.as_default(): od_graph_def = tf.GraphDef() with tf.gfile.GFile("./ibrahim_training/exports/track_ssd_v3_large_512/frozen_inference_graph.pb", 'rb') as fid: serialized_graph = fid.read() od_graph_def.ParseFromString(serialized_graph) tf.import_graph_def(od_graph_def, name='') category_index = label_map_util.create_category_index_from_labelmap('data/mscoco_label_map.pbtxt', use_display_name=True) def load_image_into_numpy_array(image): (im_width, im_height) = image.size return np.array(image.getdata()).reshape((im_height, im_width, 3)).astype(np.uint8) def run_inference_for_single_image(image, graph): with graph.as_default(): with tf.Session() as sess: # Get handles to input and output tensors ops = tf.get_default_graph().get_operations() all_tensor_names = {output.name for op in ops for output in op.outputs} tensor_dict = {} for key in [ 'num_detections', 'detection_boxes', 'detection_scores', 'detection_classes', 'detection_masks', 'nms_embedding', 'raw_detection_boxes', 'raw_detection_scores' ]: tensor_name = key + ':0' if tensor_name in all_tensor_names: tensor_dict[key] = tf.get_default_graph().get_tensor_by_name(tensor_name) if 'detection_masks' in tensor_dict: # The following processing is only for single image detection_boxes = tf.squeeze(tensor_dict['detection_boxes'], [0]) detection_masks = tf.squeeze(tensor_dict['detection_masks'], [0]) # Reframe is required to translate mask from box coordinates to image coordinates and fit the image size. real_num_detection = tf.cast(tensor_dict['num_detections'][0], tf.int32) detection_boxes = tf.slice(detection_boxes, [0, 0], [real_num_detection, -1]) detection_masks = tf.slice(detection_masks, [0, 0, 0], [real_num_detection, -1, -1]) detection_masks_reframed = utils_ops.reframe_box_masks_to_image_masks( detection_masks, detection_boxes, image.shape[0], image.shape[1]) detection_masks_reframed = tf.cast( tf.greater(detection_masks_reframed, 0.5), tf.uint8) # Follow the convention by adding back the batch dimension tensor_dict['detection_masks'] = tf.expand_dims( detection_masks_reframed, 0) image_tensor = tf.get_default_graph().get_tensor_by_name('image_tensor:0') # Run inference output_dict = sess.run(tensor_dict, feed_dict={image_tensor: np.expand_dims(image, 0)}) # all outputs are float32 numpy arrays, so convert types as appropriate output_dict['raw_detection_boxes'] = output_dict['raw_detection_boxes'][0] output_dict['raw_detection_scores'] = output_dict['raw_detection_scores'][0] output_dict['num_detections'] = int(output_dict['num_detections'][0]) output_dict['detection_classes'] = output_dict[ 'detection_classes'][0].astype(np.uint8) output_dict['detection_boxes'] = output_dict['detection_boxes'][0] output_dict['detection_scores'] = output_dict['detection_scores'][0] if 'nms_embedding' in output_dict: output_dict['nms_embedding'] = output_dict['nms_embedding'][0] if 'detection_masks' in output_dict: output_dict['detection_masks'] = output_dict['detection_masks'][0] return output_dict # for image_path in glob.glob("images_test/*.jpg"): # image = Image.open(image_path) # # the array based representation of the image will be used later in order to prepare the # # result image with boxes and labels on it. # image_np = load_image_into_numpy_array(image) # # Expand dimensions since the model expects images to have shape: [1, None, None, 3] # image_np_expanded = np.expand_dims(image_np, axis=0) # # Actual detection. # output_dict = run_inference_for_single_image(image_np, detection_graph) # print(output_dict['nms_embedding'].shape) # print(output_dict['detection_scores']) # # Visualization of the results of a detection. # vis_util.visualize_boxes_and_labels_on_image_array( # image_np, # output_dict['detection_boxes'], # output_dict['detection_classes'], # output_dict['detection_scores'], # category_index, # instance_masks=output_dict.get('detection_masks'), # use_normalized_coordinates=True, # line_thickness=8) # cv2.imwrite(image_path+"_output.jpg", image_np) image = Image.open("test1.png") # the array based representation of the image will be used later in order to prepare the # result image with boxes and labels on it. image_np = load_image_into_numpy_array(image) # Expand dimensions since the model expects images to have shape: [1, None, None, 3] image_np_expanded = np.expand_dims(image_np, axis=0) # Actual detection. output_dict = run_inference_for_single_image(image_np, detection_graph) print(output_dict['nms_embedding'].shape) output_dict['raw_detection_scores'] = output_dict['raw_detection_scores'].reshape((7, 5118)) print(output_dict['raw_detection_scores'][:,1513]) print(output_dict['raw_detection_scores'][:,1534]) print(output_dict['raw_detection_boxes'][1513]) print(output_dict['raw_detection_boxes'][1534]) # Visualization of the results of a detection. vis_util.visualize_boxes_and_labels_on_image_array( image_np, output_dict['detection_boxes'], output_dict['detection_classes'], output_dict['detection_scores'], category_index, instance_masks=output_dict.get('detection_masks'), use_normalized_coordinates=True, line_thickness=8) cv2.imwrite("test1_output.jpg", image_np)
[ "sys.path.append", "utils.ops.reframe_box_masks_to_image_masks", "tensorflow.compat.v1.cast", "distutils.version.StrictVersion", "tensorflow.compat.v1.import_graph_def", "cv2.imwrite", "tensorflow.compat.v1.get_default_graph", "numpy.expand_dims", "tensorflow.compat.v1.gfile.GFile", "PIL.Image.ope...
[((403, 424), 'sys.path.append', 'sys.path.append', (['""".."""'], {}), "('..')\n", (418, 424), False, 'import sys\n'), ((710, 720), 'tensorflow.compat.v1.Graph', 'tf.Graph', ([], {}), '()\n', (718, 720), True, 'import tensorflow.compat.v1 as tf\n'), ((1052, 1161), 'utils.label_map_util.create_category_index_from_labelmap', 'label_map_util.create_category_index_from_labelmap', (['"""data/mscoco_label_map.pbtxt"""'], {'use_display_name': '(True)'}), "(\n 'data/mscoco_label_map.pbtxt', use_display_name=True)\n", (1102, 1161), False, 'from utils import label_map_util\n'), ((5520, 5543), 'PIL.Image.open', 'Image.open', (['"""test1.png"""'], {}), "('test1.png')\n", (5530, 5543), False, 'from PIL import Image\n'), ((5828, 5860), 'numpy.expand_dims', 'np.expand_dims', (['image_np'], {'axis': '(0)'}), '(image_np, axis=0)\n', (5842, 5860), True, 'import numpy as np\n'), ((6644, 6685), 'cv2.imwrite', 'cv2.imwrite', (['"""test1_output.jpg"""', 'image_np'], {}), "('test1_output.jpg', image_np)\n", (6655, 6685), False, 'import cv2\n'), ((464, 493), 'distutils.version.StrictVersion', 'StrictVersion', (['tf.__version__'], {}), '(tf.__version__)\n', (477, 493), False, 'from distutils.version import StrictVersion\n'), ((496, 518), 'distutils.version.StrictVersion', 'StrictVersion', (['"""1.9.0"""'], {}), "('1.9.0')\n", (509, 518), False, 'from distutils.version import StrictVersion\n'), ((773, 786), 'tensorflow.compat.v1.GraphDef', 'tf.GraphDef', ([], {}), '()\n', (784, 786), True, 'import tensorflow.compat.v1 as tf\n'), ((794, 903), 'tensorflow.compat.v1.gfile.GFile', 'tf.gfile.GFile', (['"""./ibrahim_training/exports/track_ssd_v3_large_512/frozen_inference_graph.pb"""', '"""rb"""'], {}), "(\n './ibrahim_training/exports/track_ssd_v3_large_512/frozen_inference_graph.pb'\n , 'rb')\n", (808, 903), True, 'import tensorflow.compat.v1 as tf\n'), ((991, 1033), 'tensorflow.compat.v1.import_graph_def', 'tf.import_graph_def', (['od_graph_def'], {'name': '""""""'}), "(od_graph_def, name='')\n", (1010, 1033), True, 'import tensorflow.compat.v1 as tf\n'), ((1420, 1432), 'tensorflow.compat.v1.Session', 'tf.Session', ([], {}), '()\n', (1430, 1432), True, 'import tensorflow.compat.v1 as tf\n'), ((2233, 2280), 'tensorflow.compat.v1.squeeze', 'tf.squeeze', (["tensor_dict['detection_boxes']", '[0]'], {}), "(tensor_dict['detection_boxes'], [0])\n", (2243, 2280), True, 'import tensorflow.compat.v1 as tf\n'), ((2315, 2362), 'tensorflow.compat.v1.squeeze', 'tf.squeeze', (["tensor_dict['detection_masks']", '[0]'], {}), "(tensor_dict['detection_masks'], [0])\n", (2325, 2362), True, 'import tensorflow.compat.v1 as tf\n'), ((2522, 2573), 'tensorflow.compat.v1.cast', 'tf.cast', (["tensor_dict['num_detections'][0]", 'tf.int32'], {}), "(tensor_dict['num_detections'][0], tf.int32)\n", (2529, 2573), True, 'import tensorflow.compat.v1 as tf\n'), ((2608, 2667), 'tensorflow.compat.v1.slice', 'tf.slice', (['detection_boxes', '[0, 0]', '[real_num_detection, -1]'], {}), '(detection_boxes, [0, 0], [real_num_detection, -1])\n', (2616, 2667), True, 'import tensorflow.compat.v1 as tf\n'), ((2702, 2768), 'tensorflow.compat.v1.slice', 'tf.slice', (['detection_masks', '[0, 0, 0]', '[real_num_detection, -1, -1]'], {}), '(detection_masks, [0, 0, 0], [real_num_detection, -1, -1])\n', (2710, 2768), True, 'import tensorflow.compat.v1 as tf\n'), ((2812, 2924), 'utils.ops.reframe_box_masks_to_image_masks', 'utils_ops.reframe_box_masks_to_image_masks', (['detection_masks', 'detection_boxes', 'image.shape[0]', 'image.shape[1]'], {}), '(detection_masks, detection_boxes,\n image.shape[0], image.shape[1])\n', (2854, 2924), True, 'from utils import ops as utils_ops\n'), ((3191, 3234), 'tensorflow.compat.v1.expand_dims', 'tf.expand_dims', (['detection_masks_reframed', '(0)'], {}), '(detection_masks_reframed, 0)\n', (3205, 3234), True, 'import tensorflow.compat.v1 as tf\n'), ((1510, 1532), 'tensorflow.compat.v1.get_default_graph', 'tf.get_default_graph', ([], {}), '()\n', (1530, 1532), True, 'import tensorflow.compat.v1 as tf\n'), ((3014, 3055), 'tensorflow.compat.v1.greater', 'tf.greater', (['detection_masks_reframed', '(0.5)'], {}), '(detection_masks_reframed, 0.5)\n', (3024, 3055), True, 'import tensorflow.compat.v1 as tf\n'), ((3283, 3305), 'tensorflow.compat.v1.get_default_graph', 'tf.get_default_graph', ([], {}), '()\n', (3303, 3305), True, 'import tensorflow.compat.v1 as tf\n'), ((3481, 3505), 'numpy.expand_dims', 'np.expand_dims', (['image', '(0)'], {}), '(image, 0)\n', (3495, 3505), True, 'import numpy as np\n'), ((2027, 2049), 'tensorflow.compat.v1.get_default_graph', 'tf.get_default_graph', ([], {}), '()\n', (2047, 2049), True, 'import tensorflow.compat.v1 as tf\n')]
import numpy as np class Penalty: """ class for penalty function """ __slots__ = ['alpha','beta','C'] def __init__(self,alpha=2,beta=2,C=100): self.alpha = alpha self.beta = beta self.C = C def eval_ics(self,values,ii): """ evaluate penalty term for inequality constraints""" p = np.zeros(values.shape,dtype=float) idx = np.nonzero(values>0) p[idx] = ((ii+1)*self.C)**(self.alpha) * values[idx]**self.beta return p def eval_ecs(self,values,ii): """ evaluate penalty term for equality constraints""" p = np.zeros(values.shape,dtype=float) idx = np.nonzero(values) p[idx] = ((ii+1)*self.C)**(self.alpha) * np.abs(values[idx])**self.beta return p
[ "numpy.nonzero", "numpy.abs", "numpy.zeros" ]
[((340, 375), 'numpy.zeros', 'np.zeros', (['values.shape'], {'dtype': 'float'}), '(values.shape, dtype=float)\n', (348, 375), True, 'import numpy as np\n'), ((389, 411), 'numpy.nonzero', 'np.nonzero', (['(values > 0)'], {}), '(values > 0)\n', (399, 411), True, 'import numpy as np\n'), ((610, 645), 'numpy.zeros', 'np.zeros', (['values.shape'], {'dtype': 'float'}), '(values.shape, dtype=float)\n', (618, 645), True, 'import numpy as np\n'), ((659, 677), 'numpy.nonzero', 'np.nonzero', (['values'], {}), '(values)\n', (669, 677), True, 'import numpy as np\n'), ((727, 746), 'numpy.abs', 'np.abs', (['values[idx]'], {}), '(values[idx])\n', (733, 746), True, 'import numpy as np\n')]
import numpy as np from LtP import * from sklearn.ensemble import RandomForestClassifier X_train = np.array([[0, 0, 1, 1, 1, 1, 1, 0, 1], [0, 0, 1, 0, 0, 1, 0, 1, 1], [0, 0, 1, 1, 0, 1, 1, 0, 0], [1, 1, 1, 1, 0, 1, 1, 0, 1], [0, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 0, 1, 1, 0, 0, 1], [1, 0, 1, 1, 0, 1, 1, 1, 1]]) y_train = np.array([9, 56, 11, 4, 4, 6, 12]) placing = LearningToPlace(method="voting", efficient=True, clf=RandomForestClassifier( n_estimators=100, n_jobs=-1, random_state=0)) placing.fit(X_train, y_train) X_test = np.array([0, 1, 0, 1, 1, 1, 0, 0, 1]) predict = placing.predict(X_test) print("Prediction: %s" % predict)
[ "sklearn.ensemble.RandomForestClassifier", "numpy.array" ]
[((100, 322), 'numpy.array', 'np.array', (['[[0, 0, 1, 1, 1, 1, 1, 0, 1], [0, 0, 1, 0, 0, 1, 0, 1, 1], [0, 0, 1, 1, 0, \n 1, 1, 0, 0], [1, 1, 1, 1, 0, 1, 1, 0, 1], [0, 1, 1, 1, 1, 1, 1, 1, 1],\n [1, 1, 1, 0, 1, 1, 0, 0, 1], [1, 0, 1, 1, 0, 1, 1, 1, 1]]'], {}), '([[0, 0, 1, 1, 1, 1, 1, 0, 1], [0, 0, 1, 0, 0, 1, 0, 1, 1], [0, 0, \n 1, 1, 0, 1, 1, 0, 0], [1, 1, 1, 1, 0, 1, 1, 0, 1], [0, 1, 1, 1, 1, 1, 1,\n 1, 1], [1, 1, 1, 0, 1, 1, 0, 0, 1], [1, 0, 1, 1, 0, 1, 1, 1, 1]])\n', (108, 322), True, 'import numpy as np\n'), ((444, 478), 'numpy.array', 'np.array', (['[9, 56, 11, 4, 4, 6, 12]'], {}), '([9, 56, 11, 4, 4, 6, 12])\n', (452, 478), True, 'import numpy as np\n'), ((657, 694), 'numpy.array', 'np.array', (['[0, 1, 0, 1, 1, 1, 0, 0, 1]'], {}), '([0, 1, 0, 1, 1, 1, 0, 0, 1])\n', (665, 694), True, 'import numpy as np\n'), ((543, 610), 'sklearn.ensemble.RandomForestClassifier', 'RandomForestClassifier', ([], {'n_estimators': '(100)', 'n_jobs': '(-1)', 'random_state': '(0)'}), '(n_estimators=100, n_jobs=-1, random_state=0)\n', (565, 610), False, 'from sklearn.ensemble import RandomForestClassifier\n')]
from matplotlib import pyplot as plt import numpy as np angle_from = -90 angle_to = 91 angle_step = 10 x_ = np.arange(angle_from,angle_to,angle_step) x = np.radians(x_) lambda_l = np.reshape(np.repeat(x,x.shape[0],axis=0),(x.shape[0],x.shape[0])) phi_l = np.repeat([x],x.shape[0],axis=0) # specific case: l = 0 # phi_r = np.arctan2(np.tan(phi_l)*np.cos(lambda_l),1) # generalized # angle = 10 for angle in range(0,91,10): l = np.radians(angle) # phi_r = np.arctan2(np.cos(lambda_l)*np.sqrt(1-np.power(np.cos(phi_l)*np.cos(l),2)),np.cos(phi_l)*np.cos(l)) # root(1-sin^2) form # phi_r = np.arctan2(np.cos(lambda_l)*np.sin(np.arccos(np.cos(phi_l)*np.cos(l))),np.cos(phi_l)*np.cos(l)) # cos^-1 form # phi_r[phi_l > 0] = -phi_r[phi_l > 0] phi_r = np.arctan2(np.cos(lambda_l)*np.sin(phi_l),np.cos(phi_l)*np.cos(l)) #??? idk why but it works plt.cla() plt.title("azimuth angle: "+str(angle)+"(degree)") plt.xlabel("\u03BB") plt.ylabel("\u03C6") plt.plot(x_,phi_r*180/np.pi) # plt.show() plt.savefig('./epipolar_line_visualization/epipolar_'+str(angle)+'.png')
[ "numpy.radians", "matplotlib.pyplot.plot", "numpy.sin", "numpy.arange", "matplotlib.pyplot.cla", "numpy.cos", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xlabel", "numpy.repeat" ]
[((110, 153), 'numpy.arange', 'np.arange', (['angle_from', 'angle_to', 'angle_step'], {}), '(angle_from, angle_to, angle_step)\n', (119, 153), True, 'import numpy as np\n'), ((156, 170), 'numpy.radians', 'np.radians', (['x_'], {}), '(x_)\n', (166, 170), True, 'import numpy as np\n'), ((257, 291), 'numpy.repeat', 'np.repeat', (['[x]', 'x.shape[0]'], {'axis': '(0)'}), '([x], x.shape[0], axis=0)\n', (266, 291), True, 'import numpy as np\n'), ((193, 225), 'numpy.repeat', 'np.repeat', (['x', 'x.shape[0]'], {'axis': '(0)'}), '(x, x.shape[0], axis=0)\n', (202, 225), True, 'import numpy as np\n'), ((431, 448), 'numpy.radians', 'np.radians', (['angle'], {}), '(angle)\n', (441, 448), True, 'import numpy as np\n'), ((846, 855), 'matplotlib.pyplot.cla', 'plt.cla', ([], {}), '()\n', (853, 855), True, 'from matplotlib import pyplot as plt\n'), ((909, 924), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""λ"""'], {}), "('λ')\n", (919, 924), True, 'from matplotlib import pyplot as plt\n'), ((931, 946), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""φ"""'], {}), "('φ')\n", (941, 946), True, 'from matplotlib import pyplot as plt\n'), ((953, 986), 'matplotlib.pyplot.plot', 'plt.plot', (['x_', '(phi_r * 180 / np.pi)'], {}), '(x_, phi_r * 180 / np.pi)\n', (961, 986), True, 'from matplotlib import pyplot as plt\n'), ((762, 778), 'numpy.cos', 'np.cos', (['lambda_l'], {}), '(lambda_l)\n', (768, 778), True, 'import numpy as np\n'), ((779, 792), 'numpy.sin', 'np.sin', (['phi_l'], {}), '(phi_l)\n', (785, 792), True, 'import numpy as np\n'), ((793, 806), 'numpy.cos', 'np.cos', (['phi_l'], {}), '(phi_l)\n', (799, 806), True, 'import numpy as np\n'), ((807, 816), 'numpy.cos', 'np.cos', (['l'], {}), '(l)\n', (813, 816), True, 'import numpy as np\n')]
# Copyright 2017 <NAME>, <NAME> and <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. from sciope.features.feature_extraction import generate_tsfresh_features, _get_tsfresh_features_names from sciope.utilities.summarystats.summary_base import SummaryBase from itertools import combinations from tsfresh.feature_extraction.settings import EfficientFCParameters, MinimalFCParameters import numpy as np class SummariesTSFRESH(SummaryBase): """ Class for computing features/statistics on time series data. An ensemble of different statistics from TSFRESH are supported. """ def __init__(self, features='minimal', corrcoef=False, use_logger=False): self.name = 'SummariesTSFRESH' super(SummariesTSFRESH, self).__init__(self.name, use_logger=use_logger) if type(features) is str: allowed_str = ['minimal', 'full'] assert features in allowed_str,"{0} is not recognized, supported sets are 'minimal' and 'full'".format(features) if features == 'minimal': self.features = MinimalFCParameters() self.features.pop('length') else: self.features = EfficientFCParameters() else: self.features = features self.corrcoef = corrcoef self.summaries_names = _get_tsfresh_features_names(self.features) def _compute_tsfresh(self, point): """ Computes features for one point (time series). Parameters ---------- point : ndarray trajectory of shape n_timepoints x 1 Returns ------- list list of generated features """ return generate_tsfresh_features(point, features=self.features) def _compute_corrcoef(self, x, y): """ Computes the Pearson correlation coefficient between two trajectories Parameters --------- x : ndarray Trajectory of shape n_timepoints x 1 y: ndarray Trajectory of shape n_timepoints x 1 Returns list list of generated feature """ return [np.corrcoef(x, y)[0, 1]] def compute(self, point): """[summary] Parameters ---------- point : [type] [description] """ point = np.asarray(point) assert len(point.shape) == 3, "required input shape is (n_points, n_species, n_timepoints)" tsfresh_summaries = self._compute_tsfresh(point) tsfresh_summaries = np.asarray(tsfresh_summaries) tsfresh_summaries = np.mean(tsfresh_summaries, axis=0, keepdims=True) if self.corrcoef: assert point.shape[1] > 1, "corrcoef = True can only be used if the n_species > 1" corrcoef_summaries = [] n_species = range(point.shape[1]) for n in point: corr = [] for s in combinations(n_species, 2): x = n[s[0]] y = n[s[1]] corr.append(self._compute_corrcoef(x, y)[0]) corrcoef_summaries.append(corr) corrcoef_summaries = np.asarray(corrcoef_summaries) corrcoef_summaries = np.mean(corrcoef_summaries, axis=0, keepdims=True) tot = np.hstack((tsfresh_summaries, corrcoef_summaries)) return tot else: return tsfresh_summaries
[ "tsfresh.feature_extraction.settings.EfficientFCParameters", "numpy.corrcoef", "numpy.asarray", "numpy.hstack", "sciope.features.feature_extraction.generate_tsfresh_features", "itertools.combinations", "numpy.mean", "tsfresh.feature_extraction.settings.MinimalFCParameters", "sciope.features.feature_...
[((1880, 1922), 'sciope.features.feature_extraction._get_tsfresh_features_names', '_get_tsfresh_features_names', (['self.features'], {}), '(self.features)\n', (1907, 1922), False, 'from sciope.features.feature_extraction import generate_tsfresh_features, _get_tsfresh_features_names\n'), ((2299, 2355), 'sciope.features.feature_extraction.generate_tsfresh_features', 'generate_tsfresh_features', (['point'], {'features': 'self.features'}), '(point, features=self.features)\n', (2324, 2355), False, 'from sciope.features.feature_extraction import generate_tsfresh_features, _get_tsfresh_features_names\n'), ((3001, 3018), 'numpy.asarray', 'np.asarray', (['point'], {}), '(point)\n', (3011, 3018), True, 'import numpy as np\n'), ((3208, 3237), 'numpy.asarray', 'np.asarray', (['tsfresh_summaries'], {}), '(tsfresh_summaries)\n', (3218, 3237), True, 'import numpy as np\n'), ((3267, 3316), 'numpy.mean', 'np.mean', (['tsfresh_summaries'], {'axis': '(0)', 'keepdims': '(True)'}), '(tsfresh_summaries, axis=0, keepdims=True)\n', (3274, 3316), True, 'import numpy as np\n'), ((3849, 3879), 'numpy.asarray', 'np.asarray', (['corrcoef_summaries'], {}), '(corrcoef_summaries)\n', (3859, 3879), True, 'import numpy as np\n'), ((3914, 3964), 'numpy.mean', 'np.mean', (['corrcoef_summaries'], {'axis': '(0)', 'keepdims': '(True)'}), '(corrcoef_summaries, axis=0, keepdims=True)\n', (3921, 3964), True, 'import numpy as np\n'), ((3984, 4034), 'numpy.hstack', 'np.hstack', (['(tsfresh_summaries, corrcoef_summaries)'], {}), '((tsfresh_summaries, corrcoef_summaries))\n', (3993, 4034), True, 'import numpy as np\n'), ((1606, 1627), 'tsfresh.feature_extraction.settings.MinimalFCParameters', 'MinimalFCParameters', ([], {}), '()\n', (1625, 1627), False, 'from tsfresh.feature_extraction.settings import EfficientFCParameters, MinimalFCParameters\n'), ((1725, 1748), 'tsfresh.feature_extraction.settings.EfficientFCParameters', 'EfficientFCParameters', ([], {}), '()\n', (1746, 1748), False, 'from tsfresh.feature_extraction.settings import EfficientFCParameters, MinimalFCParameters\n'), ((2790, 2807), 'numpy.corrcoef', 'np.corrcoef', (['x', 'y'], {}), '(x, y)\n', (2801, 2807), True, 'import numpy as np\n'), ((3606, 3632), 'itertools.combinations', 'combinations', (['n_species', '(2)'], {}), '(n_species, 2)\n', (3618, 3632), False, 'from itertools import combinations\n')]
from .SpikeUnit import SpikeUnit import numpy as np def gaussian_kernel(sigma): """ The gaussian kernel. .. math :: w(\\tau) = \\frac{1}{\\sqrt{2 \\pi} \\sigma_w} \\exp(-\\frac{\\tau^2}{2 \\sigma^2_w}) example: .. code-block:: python >>> kernel('guassian', {'sigma': 0.4}) """ return lambda t: 1/(np.sqrt(2*np.pi)*sigma) * np.exp(-t**2/(2*sigma**2)) def causal_kernel(alpha): """ The causal kernel. .. math:: w(\\tau) = [\\alpha^2 \\tau \\exp(- \\alpha \\tau)]_+ example: .. code-block:: python >>> kernel('causal', {'alpha': 0.4}) """ def causal(t): v = alpha**2 * t * np.exp(-alpha*t) v[v<0] = 0 return v return causal def rectangular_kernel(delta): """ Moving rectangular kernel. .. math:: w(\\tau) = \\begin{cases} \\frac{1}{\Delta t} &,\\ -\\frac{\Delta t}{2} \\leq t \\leq \\frac{\\Delta t}{2} \\\\ 0 &,\\ otherwise \\end{cases} example: .. code-block:: python >>> kernel('square', {'delta': 0.4}) """ return lambda t: np.ones_like(t[(t>=-delta/2)&(t<=delta/2)]) / delta def kernel(name, **args): """ Get the kernel function. Kernels: - gaussian, args: [sigma] - causal, args: [alpha] - square, args: [delta] Args: - name: name of the kernel - \*\*args: arguments for each kernel. Return: - kernel function in lambda. Example: .. code-block:: python >>> kernel('guassian', {'sigma':0.4}) """ if name == "gaussian": return gaussian_kernel(**args) elif name == "causal": return causal_kernel(**args) elif name=="square": return rectangular_kernel(**args) else: raise NameError("unkown kernel: "+str(name)) def _check_and_convert_to_ndarray(subject): if isinstance(subject,SpikeUnit): target = subject.spike_train elif isinstance(subject,list): target = np.array(subject) elif isinstance(subject, np.ndarray): target = subject else: raise ValueError("type of to is not supported: "+str(type(subject))) return target def generate_linear_filter(to, k): """ Convert the discrete spike train array into a linear filter funciton. Args: - to: data in numpy.ndarray or SpikeUnit class - k: kernel Returns: - kernel lambda function """ target = _check_and_convert_to_ndarray(to) return lambda t: np.sum(k(target - t)) def apply_linear_filter(to, k, x_range=None, nbins=1000, returnX=True): """ Map linear filter into a ndarray. Args: - to: data in numpy.ndarray or SpikeUnit class - k: kernel - x_range: time range tuple (starttime, endtime), default as None - nbins: number of steps, default as 1000 - returnX: return timespan ndarray Returns: - [X_range,] discrete_linear_filter """ target = _check_and_convert_to_ndarray(to) linear_filter = generate_linear_filter(to, k) if x_range is None: x_range = np.linspace(0, target[-1], nbins) elif isinstance(x_range, tuple) or isinstance(x_range, list): x_range = np.linspace(x_range[0], x_range[1], nbins) elif isinstance(x_range, np.ndarray): returnX = False pass else: raise ValueError("invalid x_range") if returnX: return x_range, np.array(list(map(linear_filter, x_range))) # XXX else: return np.array(list(map(linear_filter, x_range))) def apply_linear_filter_withroi(train, k, starts, roi=(0,0), nbins=1000, pbar=None): """ Map linear filter into a ndarray with a region of interest. Args: - to: data in numpy.ndarray or SpikeUnit class - k: kernel - starts: start time points in list or 1-d ndarray - roi: region of interest, in time tuple (starttime, endtime) - nbins: number of steps, default as 1000 - pbar: progress bar in tqdm Returns: - _mean_response: 1-d ndarray """ _mean_response = None for each_start in starts: a = apply_linear_filter(train, k, x_range=(each_start+roi[0], each_start+roi[1]), nbins=nbins, returnX=False) if _mean_response is None: _mean_response = a else: _mean_response = np.vstack((_mean_response, a)) if pbar: pbar.update(1) return _mean_response
[ "numpy.ones_like", "numpy.array", "numpy.exp", "numpy.linspace", "numpy.vstack", "numpy.sqrt" ]
[((2963, 2996), 'numpy.linspace', 'np.linspace', (['(0)', 'target[-1]', 'nbins'], {}), '(0, target[-1], nbins)\n', (2974, 2996), True, 'import numpy as np\n'), ((353, 387), 'numpy.exp', 'np.exp', (['(-t ** 2 / (2 * sigma ** 2))'], {}), '(-t ** 2 / (2 * sigma ** 2))\n', (359, 387), True, 'import numpy as np\n'), ((634, 652), 'numpy.exp', 'np.exp', (['(-alpha * t)'], {}), '(-alpha * t)\n', (640, 652), True, 'import numpy as np\n'), ((1048, 1101), 'numpy.ones_like', 'np.ones_like', (['t[(t >= -delta / 2) & (t <= delta / 2)]'], {}), '(t[(t >= -delta / 2) & (t <= delta / 2)])\n', (1060, 1101), True, 'import numpy as np\n'), ((1902, 1919), 'numpy.array', 'np.array', (['subject'], {}), '(subject)\n', (1910, 1919), True, 'import numpy as np\n'), ((3081, 3123), 'numpy.linspace', 'np.linspace', (['x_range[0]', 'x_range[1]', 'nbins'], {}), '(x_range[0], x_range[1], nbins)\n', (3092, 3123), True, 'import numpy as np\n'), ((4247, 4277), 'numpy.vstack', 'np.vstack', (['(_mean_response, a)'], {}), '((_mean_response, a))\n', (4256, 4277), True, 'import numpy as np\n'), ((327, 345), 'numpy.sqrt', 'np.sqrt', (['(2 * np.pi)'], {}), '(2 * np.pi)\n', (334, 345), True, 'import numpy as np\n')]
import unittest import os from maskgen import plugins, image_wrap import numpy import tempfile class MaskSelectorTestCase(unittest.TestCase): filesToKill = [] def setUp(self): plugins.loadPlugins() def test_something(self): img = numpy.zeros((500,500),dtype='uint8') wrapper = image_wrap.ImageWrapper(img) filename = tempfile.mktemp(prefix='mstc',suffix='.png',dir='.') filename_output = tempfile.mktemp(prefix='mstcr', suffix='.png', dir='.') self.filesToKill.append(filename) wrapper.save(filename) self.filesToKill.append(filename_output) wrapper.save(filename_output) args,error = plugins.callPlugin('MaskSelector', wrapper, filename, filename_output, percentage_width = 0.1, percentage_height=0.1) wrapper = image_wrap.openImageFile(filename_output) output = wrapper.to_array() self.assertTrue(sum(sum(output))>255) self.assertTrue(sum(sum(output)) < numpy.prod(output.shape)) self.assertEqual(output.shape, img.shape) self.assertTrue('paste_x' in args and args['paste_x'] > 0) self.assertTrue('paste_y' in args and args['paste_y'] > 0) def tearDown(self): for f in self.filesToKill: if os.path.exists(f): os.remove(f) if __name__ == '__main__': unittest.main()
[ "unittest.main", "maskgen.image_wrap.openImageFile", "os.remove", "maskgen.plugins.loadPlugins", "maskgen.image_wrap.ImageWrapper", "numpy.zeros", "os.path.exists", "maskgen.plugins.callPlugin", "tempfile.mktemp", "numpy.prod" ]
[((1488, 1503), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1501, 1503), False, 'import unittest\n'), ((194, 215), 'maskgen.plugins.loadPlugins', 'plugins.loadPlugins', ([], {}), '()\n', (213, 215), False, 'from maskgen import plugins, image_wrap\n'), ((261, 299), 'numpy.zeros', 'numpy.zeros', (['(500, 500)'], {'dtype': '"""uint8"""'}), "((500, 500), dtype='uint8')\n", (272, 299), False, 'import numpy\n'), ((316, 344), 'maskgen.image_wrap.ImageWrapper', 'image_wrap.ImageWrapper', (['img'], {}), '(img)\n', (339, 344), False, 'from maskgen import plugins, image_wrap\n'), ((365, 419), 'tempfile.mktemp', 'tempfile.mktemp', ([], {'prefix': '"""mstc"""', 'suffix': '""".png"""', 'dir': '"""."""'}), "(prefix='mstc', suffix='.png', dir='.')\n", (380, 419), False, 'import tempfile\n'), ((444, 499), 'tempfile.mktemp', 'tempfile.mktemp', ([], {'prefix': '"""mstcr"""', 'suffix': '""".png"""', 'dir': '"""."""'}), "(prefix='mstcr', suffix='.png', dir='.')\n", (459, 499), False, 'import tempfile\n'), ((681, 800), 'maskgen.plugins.callPlugin', 'plugins.callPlugin', (['"""MaskSelector"""', 'wrapper', 'filename', 'filename_output'], {'percentage_width': '(0.1)', 'percentage_height': '(0.1)'}), "('MaskSelector', wrapper, filename, filename_output,\n percentage_width=0.1, percentage_height=0.1)\n", (699, 800), False, 'from maskgen import plugins, image_wrap\n'), ((954, 995), 'maskgen.image_wrap.openImageFile', 'image_wrap.openImageFile', (['filename_output'], {}), '(filename_output)\n', (978, 995), False, 'from maskgen import plugins, image_wrap\n'), ((1408, 1425), 'os.path.exists', 'os.path.exists', (['f'], {}), '(f)\n', (1422, 1425), False, 'import os\n'), ((1121, 1145), 'numpy.prod', 'numpy.prod', (['output.shape'], {}), '(output.shape)\n', (1131, 1145), False, 'import numpy\n'), ((1443, 1455), 'os.remove', 'os.remove', (['f'], {}), '(f)\n', (1452, 1455), False, 'import os\n')]
import copy import math import numpy as np from astropy import units as u from astropy.coordinates import SkyCoord ################################ # Functions for locating the SN. ################################ # Function that takes in the latitude and longitude (in degrees) and returns the (x,y,z) coordinates # of the point on earth (in m), with the centre of the earth as the origin # # Input: latitude (number), longitude (number), radius (number) # # Output: numpy array [x, y, z] # def find_xyz_from_latlong(latitude, longitude, radius): x = radius*math.cos(math.radians(longitude))*math.cos(math.radians(latitude)) y = radius*math.sin(math.radians(longitude))*math.cos(math.radians(latitude)) z = radius*math.sin(math.radians(latitude)) return np.array([x,y,z]) # Function that returns the latitude and longitude of a point in 3D # # Input: list/numpy array [x, y, z] # # Output: numpy array [latitude, longitude] # def lat_long_from_xyz(point): lat = math.degrees(math.asin(point[2] / np.linalg.norm(point))) # If the point is on the north or south pole, the longitude can take any value # The following code makes sure the correct atan value is chosen, since in the range # -pi-->pi there are 2 atan values for any number if point[1] >= 0.: if point[0] >= 0.: long = math.degrees(math.atan(point[1]/point[0])) elif point[0] < 0.: long = 180. + math.degrees(math.atan(point[1]/point[0])) elif point[1] < 0.: if point[0] >= 0.: long = math.degrees(math.atan(point[1]/point[0])) elif point[0] < 0.: long = math.degrees(math.atan(point[1]/point[0])) - 180. return np.array([lat,long]) # Function that takes in 2 3D points and returns the separation # # Input: list/numpy array [x1, y1, z1], list/numpy array [x2, y2, z2] # # Output: number # def distance_between_3d_points(p1, p2): separation_vector = p1 - p2 return math.sqrt(separation_vector[0]**2+separation_vector[1]**2+separation_vector[2]**2) # Function to produce the equation of the plane on which the SN lies # # Input: list/numpy array [x1, y1, z1], list/numpy array [x2, y2, z2], number, number, number # # Output: numpy array [a, b, c, d] # def produce_plane(pos1, pos2, dT, SN_dist, c_light): dT_max = distance_between_3d_points(pos1, pos2) / c_light # Find angle between the SN position and the relative positions of the detectors theta = math.acos(dT / dT_max) plane_normal = pos2 - pos1 mag_plane_normal = np.linalg.norm(plane_normal) plane_normal /= mag_plane_normal # Normalize the plane normal vector plane_point = SN_dist*math.cos(theta)*plane_normal # The plane equation is of the form [a, b, c, d] which defines a scalar equation of the plane # ax + by + cz = d plane = np.append(plane_normal, np.array([np.dot(plane_normal, plane_point)])) return plane # Function to output the equation of a line intersecting 2 planes # # Input: list/numpy array [a1, b1, c1, d1], list/numpy array [a2, b2, c2, d2] # # Output: numpy array [gradx, x, grady, y, gradz, z] # def plane_intersection(plane_1, plane_2): # Define the line direction vector for planes 1 and 2 line_vector = np.cross(plane_1[0:3], plane_2[0:3]) # Initialise the point on the line line_point = np.empty(3) # Choose a valid point on the line if plane_1[0] != 0 and (plane_2[2]*plane_1[0]-plane_2[0]*plane_1[2]) != 0: # Define a point on the line (valid for plane_1[0] =/= 0) line_point[1] = 0. line_point[2] = (plane_1[0]*plane_2[3]-plane_2[0]*plane_1[3])/(plane_2[2]*plane_1[0]-plane_2[0]*plane_1[2]) line_point[0] = (plane_1[3]/plane_1[0])-(plane_1[2]/plane_1[0])*line_point[2] elif plane_1[1] != 0 and (plane_2[1]*plane_1[2]-plane_2[2]*plane_1[1]) != 0: # Define a point on the line (valid for plane_1[1] =/= 0) line_point[0] = 0. line_point[1] = (plane_1[2]*plane_2[3]-plane_2[2]*plane_1[3])/(plane_2[1]*plane_1[2]-plane_2[2]*plane_1[1]) line_point[2] = (plane_1[3]/plane_1[2])-(plane_1[1]/plane_1[2])*line_point[1] elif plane_1[2] != 0 and (plane_2[0]*plane_1[1]-plane_2[1]*plane_1[0]) != 0: # Define a point on the line (valid for plane_1[2] =/= 0) line_point[2] = 0. line_point[0] = (plane_1[1]*plane_2[3]-plane_2[1]*plane_1[3])/(plane_2[0]*plane_1[1]-plane_2[1]*plane_1[0]) line_point[1] = (plane_1[3] / plane_1[1]) - (plane_1[0] / plane_1[1]) * line_point[0] # Return equation of line in form [gradx, x, grady, y, gradz, z] # [gradx, grady, gradz] refers to the gradient of the line # [x, y, z] refers to a point on the line return np.array([line_vector[0],line_point[0],line_vector[1],line_point[1],line_vector[2],line_point[2]]) # Function to find the intersection points of 2 planes with a sphere # A sphere is defined as [x, y, z, r] where [x, y, z] is the centre and r is the radius # # Input: list/numpy array [gradx, x, grady, y, gradz, z], list/numpy array [x, y, z, r] # # Output: list/numpy array [x1, y1, z1], list/numpy array [x2, y2, z2] # def intersection_2planes_sphere(line, sphere): a = line[0]**2 + line[2]**2 + line[4]**2 b = 2*(line[0]*(line[1]-sphere[0])+line[2]*(line[3]-sphere[1])+line[4]*(line[5]-sphere[2])) c = (line[1]-sphere[0])**2 + (line[3]-sphere[1])**2 + (line[5]-sphere[2])**2 - sphere[3]**2 # The check a==0 is to see if the planes are parallel, in which case they cannot intersect if a == 0: raise ValueError('Planes do not meet.') else: discriminant = b**2 - 4*a*c if discriminant >= 0: # Find the t value(s) t1 = (-b+math.sqrt(discriminant)) / (2*a) t2 = (-b-math.sqrt(discriminant)) / (2*a) # Find the positions of the intersection points by plugging the t value(s) into the line equation point1 = np.array([line[0]*t1+line[1], line[2]*t1+line[3], line[4]*t1+line[5]]) point2 = np.array([line[0]*t2+line[1], line[2]*t2+line[3], line[4]*t2+line[5]]) return point1, point2 elif discriminant < 0: raise ValueError('Discriminant less than 0.') # Find the difference in time-of-arrival for the neutrinos and 2 detectors located at pos1 and pos2 and a supernova # located at posSN # # Input: list/numpy array [x1, y1, z1], list/numpy array [x2, y2, z2], list/numpy array [x, y, z], number # # Output: number # def find_deltaT(pos1, pos2, posSN, c_light): local_posSN = copy.copy(posSN) # Define a local version of the SN position dT_max = distance_between_3d_points(pos1, pos2) / c_light relative_pos = pos2 - pos1 relative_pos /= np.linalg.norm(relative_pos) local_posSN /= np.linalg.norm(local_posSN) return (dT_max * np.dot(local_posSN, relative_pos)) / (np.linalg.norm(local_posSN) * np.linalg.norm(relative_pos)) # Function that takes in quantities defining a circle in 3D space and returns a point on the circle at # a user-given angle # # Input: list/numpy array [x1, y1, z1], list/numpy array [x2, y2, z2], number, number (angle in radians) # # Output: list/numpy array [x, y, z] # def point_on_3d_circle(normal, centre, radius, theta): local_normal = copy.copy(normal) # Define a local variable for the normal vector so it is not changed outwith the function local_normal /= np.linalg.norm(local_normal) # normalize the normal vector # Now we find the first vector orthogonal to the normal vector # We do this by solving a.n = 0 # If the normal vector is 0 then we cannot get a definite solution if local_normal[0] == local_normal[1] == local_normal[2] == 0.: raise ValueError('local_normal vector is the 0 vector.') if local_normal[0] == 0: a = np.array([1,0,0]) elif local_normal[1] == 0.: a = np.array([0,1,0]) elif local_normal[2] == 0.: a = np.array([0,0,1]) else: a = np.array([1,1,(-local_normal[0]-local_normal[1])/local_normal[2]]) a /= np.linalg.norm(a) # Our final orthogonal vector is found by b = n x a so it is perpendicular to both a and n b = np.cross(a,local_normal) # Now we define the x,y,z coordinates of the point on the circle using this method: # https://math.stackexchange.com/questions/73237/parametric-equation-of-a-circle-in-3d-space return centre + radius * math.cos(theta) * a + radius * math.sin(theta) * b # Function to produce a Skycoord object of long/lats of a 3D circle based on # the ToA difference between 2 detectors # The wrapped long/lats are returned # # Input: number, list/numpy array [x1, y1, z1], list/numpy array [x2, y2, z2], number, number, number # # Output: Skycoord array, Skycoord array # def circle_plot_points_astropy(N_points, pos1, pos2, c_light, dT, SN_dist): angle_list = np.linspace(0, 2 * np.pi, N_points) # Circle parameters theta = math.acos(dT * c_light / distance_between_3d_points(pos1, pos2)) radius = SN_dist * math.sin(theta) circle_normal = pos2 - pos1 circle_normal /= np.linalg.norm(circle_normal) # Normalize the plane normal vector circle_centre = SN_dist*math.cos(theta) * circle_normal long_list = np.empty(N_points) lat_list = np.empty(N_points) # Fill arrays for i in range(len(angle_list)): angle = angle_list[i] current_point = point_on_3d_circle(circle_normal, circle_centre, radius, angle) current_lat_long = lat_long_from_xyz(current_point) lat_list[i] = current_lat_long[0] long_list[i] = current_lat_long[1] lat_list = lat_list long_list = long_list lat_list = lat_list * u.degree long_list = long_list * u.degree c = SkyCoord(ra=long_list, dec=lat_list, frame='icrs') ra_rad = c.ra.wrap_at(180 * u.deg).radian dec_rad = c.dec.radian return ra_rad, dec_rad
[ "math.atan", "math.sqrt", "math.radians", "numpy.empty", "numpy.cross", "copy.copy", "math.sin", "math.acos", "numpy.linalg.norm", "numpy.array", "numpy.linspace", "math.cos", "numpy.dot", "astropy.coordinates.SkyCoord" ]
[((775, 794), 'numpy.array', 'np.array', (['[x, y, z]'], {}), '([x, y, z])\n', (783, 794), True, 'import numpy as np\n'), ((1703, 1724), 'numpy.array', 'np.array', (['[lat, long]'], {}), '([lat, long])\n', (1711, 1724), True, 'import numpy as np\n'), ((1965, 2062), 'math.sqrt', 'math.sqrt', (['(separation_vector[0] ** 2 + separation_vector[1] ** 2 + separation_vector[\n 2] ** 2)'], {}), '(separation_vector[0] ** 2 + separation_vector[1] ** 2 + \n separation_vector[2] ** 2)\n', (1974, 2062), False, 'import math\n'), ((2466, 2488), 'math.acos', 'math.acos', (['(dT / dT_max)'], {}), '(dT / dT_max)\n', (2475, 2488), False, 'import math\n'), ((2544, 2572), 'numpy.linalg.norm', 'np.linalg.norm', (['plane_normal'], {}), '(plane_normal)\n', (2558, 2572), True, 'import numpy as np\n'), ((3249, 3285), 'numpy.cross', 'np.cross', (['plane_1[0:3]', 'plane_2[0:3]'], {}), '(plane_1[0:3], plane_2[0:3])\n', (3257, 3285), True, 'import numpy as np\n'), ((3343, 3354), 'numpy.empty', 'np.empty', (['(3)'], {}), '(3)\n', (3351, 3354), True, 'import numpy as np\n'), ((4719, 4826), 'numpy.array', 'np.array', (['[line_vector[0], line_point[0], line_vector[1], line_point[1], line_vector[\n 2], line_point[2]]'], {}), '([line_vector[0], line_point[0], line_vector[1], line_point[1],\n line_vector[2], line_point[2]])\n', (4727, 4826), True, 'import numpy as np\n'), ((6549, 6565), 'copy.copy', 'copy.copy', (['posSN'], {}), '(posSN)\n', (6558, 6565), False, 'import copy\n'), ((6723, 6751), 'numpy.linalg.norm', 'np.linalg.norm', (['relative_pos'], {}), '(relative_pos)\n', (6737, 6751), True, 'import numpy as np\n'), ((6771, 6798), 'numpy.linalg.norm', 'np.linalg.norm', (['local_posSN'], {}), '(local_posSN)\n', (6785, 6798), True, 'import numpy as np\n'), ((7266, 7283), 'copy.copy', 'copy.copy', (['normal'], {}), '(normal)\n', (7275, 7283), False, 'import copy\n'), ((7394, 7422), 'numpy.linalg.norm', 'np.linalg.norm', (['local_normal'], {}), '(local_normal)\n', (7408, 7422), True, 'import numpy as np\n'), ((8168, 8193), 'numpy.cross', 'np.cross', (['a', 'local_normal'], {}), '(a, local_normal)\n', (8176, 8193), True, 'import numpy as np\n'), ((8858, 8893), 'numpy.linspace', 'np.linspace', (['(0)', '(2 * np.pi)', 'N_points'], {}), '(0, 2 * np.pi, N_points)\n', (8869, 8893), True, 'import numpy as np\n'), ((9088, 9117), 'numpy.linalg.norm', 'np.linalg.norm', (['circle_normal'], {}), '(circle_normal)\n', (9102, 9117), True, 'import numpy as np\n'), ((9230, 9248), 'numpy.empty', 'np.empty', (['N_points'], {}), '(N_points)\n', (9238, 9248), True, 'import numpy as np\n'), ((9264, 9282), 'numpy.empty', 'np.empty', (['N_points'], {}), '(N_points)\n', (9272, 9282), True, 'import numpy as np\n'), ((9733, 9783), 'astropy.coordinates.SkyCoord', 'SkyCoord', ([], {'ra': 'long_list', 'dec': 'lat_list', 'frame': '"""icrs"""'}), "(ra=long_list, dec=lat_list, frame='icrs')\n", (9741, 9783), False, 'from astropy.coordinates import SkyCoord\n'), ((7802, 7821), 'numpy.array', 'np.array', (['[1, 0, 0]'], {}), '([1, 0, 0])\n', (7810, 7821), True, 'import numpy as np\n'), ((9019, 9034), 'math.sin', 'math.sin', (['theta'], {}), '(theta)\n', (9027, 9034), False, 'import math\n'), ((610, 632), 'math.radians', 'math.radians', (['latitude'], {}), '(latitude)\n', (622, 632), False, 'import math\n'), ((692, 714), 'math.radians', 'math.radians', (['latitude'], {}), '(latitude)\n', (704, 714), False, 'import math\n'), ((740, 762), 'math.radians', 'math.radians', (['latitude'], {}), '(latitude)\n', (752, 762), False, 'import math\n'), ((2673, 2688), 'math.cos', 'math.cos', (['theta'], {}), '(theta)\n', (2681, 2688), False, 'import math\n'), ((5935, 6021), 'numpy.array', 'np.array', (['[line[0] * t1 + line[1], line[2] * t1 + line[3], line[4] * t1 + line[5]]'], {}), '([line[0] * t1 + line[1], line[2] * t1 + line[3], line[4] * t1 +\n line[5]])\n', (5943, 6021), True, 'import numpy as np\n'), ((6027, 6113), 'numpy.array', 'np.array', (['[line[0] * t2 + line[1], line[2] * t2 + line[3], line[4] * t2 + line[5]]'], {}), '([line[0] * t2 + line[1], line[2] * t2 + line[3], line[4] * t2 +\n line[5]])\n', (6035, 6113), True, 'import numpy as np\n'), ((6820, 6853), 'numpy.dot', 'np.dot', (['local_posSN', 'relative_pos'], {}), '(local_posSN, relative_pos)\n', (6826, 6853), True, 'import numpy as np\n'), ((6858, 6885), 'numpy.linalg.norm', 'np.linalg.norm', (['local_posSN'], {}), '(local_posSN)\n', (6872, 6885), True, 'import numpy as np\n'), ((6888, 6916), 'numpy.linalg.norm', 'np.linalg.norm', (['relative_pos'], {}), '(relative_pos)\n', (6902, 6916), True, 'import numpy as np\n'), ((7864, 7883), 'numpy.array', 'np.array', (['[0, 1, 0]'], {}), '([0, 1, 0])\n', (7872, 7883), True, 'import numpy as np\n'), ((9182, 9197), 'math.cos', 'math.cos', (['theta'], {}), '(theta)\n', (9190, 9197), False, 'import math\n'), ((576, 599), 'math.radians', 'math.radians', (['longitude'], {}), '(longitude)\n', (588, 599), False, 'import math\n'), ((658, 681), 'math.radians', 'math.radians', (['longitude'], {}), '(longitude)\n', (670, 681), False, 'import math\n'), ((1022, 1043), 'numpy.linalg.norm', 'np.linalg.norm', (['point'], {}), '(point)\n', (1036, 1043), True, 'import numpy as np\n'), ((1355, 1385), 'math.atan', 'math.atan', (['(point[1] / point[0])'], {}), '(point[1] / point[0])\n', (1364, 1385), False, 'import math\n'), ((2870, 2903), 'numpy.dot', 'np.dot', (['plane_normal', 'plane_point'], {}), '(plane_normal, plane_point)\n', (2876, 2903), True, 'import numpy as np\n'), ((7926, 7945), 'numpy.array', 'np.array', (['[0, 0, 1]'], {}), '([0, 0, 1])\n', (7934, 7945), True, 'import numpy as np\n'), ((7966, 8038), 'numpy.array', 'np.array', (['[1, 1, (-local_normal[0] - local_normal[1]) / local_normal[2]]'], {}), '([1, 1, (-local_normal[0] - local_normal[1]) / local_normal[2]])\n', (7974, 8038), True, 'import numpy as np\n'), ((8046, 8063), 'numpy.linalg.norm', 'np.linalg.norm', (['a'], {}), '(a)\n', (8060, 8063), True, 'import numpy as np\n'), ((8439, 8454), 'math.sin', 'math.sin', (['theta'], {}), '(theta)\n', (8447, 8454), False, 'import math\n'), ((1565, 1595), 'math.atan', 'math.atan', (['(point[1] / point[0])'], {}), '(point[1] / point[0])\n', (1574, 1595), False, 'import math\n'), ((5717, 5740), 'math.sqrt', 'math.sqrt', (['discriminant'], {}), '(discriminant)\n', (5726, 5740), False, 'import math\n'), ((5771, 5794), 'math.sqrt', 'math.sqrt', (['discriminant'], {}), '(discriminant)\n', (5780, 5794), False, 'import math\n'), ((8408, 8423), 'math.cos', 'math.cos', (['theta'], {}), '(theta)\n', (8416, 8423), False, 'import math\n'), ((1452, 1482), 'math.atan', 'math.atan', (['(point[1] / point[0])'], {}), '(point[1] / point[0])\n', (1461, 1482), False, 'import math\n'), ((1655, 1685), 'math.atan', 'math.atan', (['(point[1] / point[0])'], {}), '(point[1] / point[0])\n', (1664, 1685), False, 'import math\n')]
import argparse import pickle from tqdm import tqdm from pathlib import Path import os import cv2 import numpy as np import pandas as pd from collections import defaultdict from utils.mask_functions import mask2rle, rle_encode from utils.helpers import load_yaml def argparser(): parser = argparse.ArgumentParser(description='Body Morp pipeline') parser.add_argument('cfg', type=str, help='experiment name') return parser.parse_args() def extract_largest(mask, n_objects): contours, _ = cv2.findContours( mask.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE ) areas = [cv2.contourArea(c) for c in contours] contours = np.array(contours)[np.argsort(areas)[::-1]] background = np.zeros(mask.shape, np.uint8) choosen = cv2.drawContours( background, contours[:n_objects], -1, (255), thickness=cv2.FILLED ) return choosen def remove_smallest(mask, min_contour_area): contours, _ = cv2.findContours( mask.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE ) contours = [c for c in contours if cv2.contourArea(c) > min_contour_area] background = np.zeros(mask.shape, np.uint8) choosen = cv2.drawContours( background, contours, -1, (255), thickness=cv2.FILLED ) return choosen def apply_thresholds(mask, n_objects, area_threshold, top_score_threshold, bottom_score_threshold, leak_score_threshold, use_contours, min_contour_area, name_i): # if n_objects == 1: # crazy_mask = (mask > top_score_threshold).astype(np.uint8) # if crazy_mask.sum() < area_threshold: # return -1 # mask = (mask > bottom_score_threshold).astype(np.uint8) # else: # mask = mask.astype(np.uint8) * 255 # if min_contour_area > 0: # choosen = remove_smallest(mask, min_contour_area) # elif use_contours: # choosen = extract_largest(mask, n_objects) # else: # choosen = mask * 255 if mask.shape[0] == 512: reshaped_mask = mask else: reshaped_mask = cv2.resize( mask, dsize=(512, 512), interpolation=cv2.INTER_LINEAR ) reshaped_mask = (reshaped_mask > 63).astype(int) * 255 # cv2.imwrite(name_i + '_.png', reshaped_mask) return rle_encode(reshaped_mask) def remove_smallest_multiclass(mask, min_contour_area, name_i): mask_uint8 = (mask*255).astype(np.uint8) num_class = mask_uint8.shape[0] mask_larges = np.zeros(mask.shape, np.uint8) min_contours = {} # 1st-pass 작은 영역 지워내기 for i in range(0, num_class): mask_i = mask_uint8[i, :, :] # contour 찾기 contours, _ = cv2.findContours(mask_i.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) # 영역을 크기별로 구분함 - min은 2nd-pass를 위해 저장 min_contours[i] = [c for c in contours if cv2.contourArea(c) <= min_contour_area] max_contours = [c for c in contours if cv2.contourArea(c) > min_contour_area] # if (name_i == 'case209'): # # 영역을 크기별로 구분함 - min은 2nd-pass를 위해 저장 # min_contours[i] = [c for c in contours if cv2.contourArea(c) <= 1100] # max_contours = [c for c in contours if cv2.contourArea(c) > 1100] # 영역 따로 그리기 mask_larges[i,:,:] = cv2.drawContours(mask_larges[i,:,:], max_contours,-1, (255), thickness=cv2.FILLED) # 2nd-pass - 겹치는 영역이 젤 많은곳으로 컨투어를 보낸다. for i in range(0, num_class): # 작은 조각 하나씩 둘러보면서 적용하기 min_contours_ = min_contours[i] for contour in min_contours_: mask_larges_ = mask_larges.copy()/255 # 작은 영역은 그린 후 팽창(dilate) 시킨다 mask_small = cv2.drawContours(np.zeros([mask_uint8.shape[1],mask_uint8.shape[2]], np.uint8), contour,-1, (255), thickness=cv2.FILLED) mask_small_dilate = cv2.dilate(mask_small, cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3)), iterations=3) # 작은영역 boolean mask mask_small_dilate = (mask_small_dilate>0) # 큰 영역의 확률맵 prob_large_contour = mask * mask_larges_ # 확률이 제일 높은 영역의 채널 번호를 가져온다. score = [] for c in range(0, num_class): # 탐색하는곳과 원본 class가 같아도, small은 이미 0이므로 그대로 진행 score.append((prob_large_contour[c, :, :] * mask_small_dilate).sum()) # 최고 점수가 나온 채널 획득 idxes = np.argwhere(score == np.amax(score)) # 높은 영역의 채널로 small contour를 편입시킨다. mask_larges[idxes[0], :, :] += mask_small # k=1 # mask_uint8[k, :, :] # mask_larges[k,:,:] output = mask_larges.astype(np.float64)/255.0 return output def build_rle_dict(mask_dict, n_objects_dict, area_threshold, top_score_threshold, bottom_score_threshold, leak_score_threshold, use_contours, min_contour_area, sub_img_path): rle_dict = {} for name, mask in tqdm(mask_dict.items()): # 물체 개수를 판단 (채널이 다르므로 늘 1개) # TODO: 대회를 위한 후처리 하드코딩 # class 개수 4개 설정 num_class = 4 if mask.shape[1] != 512: # 마스크 리사이즈 reshaped_mask = np.zeros([4, 512, 512]) for i in range(0, num_class): reshaped_mask[i,:,:] = cv2.resize(mask[i,:,:], dsize=(512, 512), interpolation=cv2.INTER_LINEAR) mask = reshaped_mask max_mask = (mask.max(axis=0,keepdims=1) == mask) * 1.0 mask_123 = np.zeros([max_mask.shape[1], max_mask.shape[2]]) # rgb 형태 마스크 저장 (확률 반영) - 전처리 없음 max_masked = mask * max_mask rgb_image = np.transpose((max_masked[1:4, :, :]/np.max(max_masked[1:4, :, :])) * 255, (1, 2, 0)) cv2.imwrite(sub_img_path + name + '_rgb.png', rgb_image) # 레이블 형태 마스크 저장 for i in range(1, num_class): # 데이터 이름에 _1,_2,_3 붙이기 name_i = name + f'_{i}' n_objects = n_objects_dict.get(name_i, 0) mask_123 = mask_123 + max_mask[i,:,:]*i # cv2.imwrite(sub_img_path + name + '.png', mask_123) # 레이블 영역 thresholding if min_contour_area > 0: mask_postproc = remove_smallest_multiclass(max_masked, min_contour_area, name) # rgb 형태 마스크 저장 (확률 반영) - 전처리 없음 rgb_image = np.transpose(mask_postproc[1:4, :, :] * 255, (1, 2, 0)) cv2.imwrite(sub_img_path + name + '_rgb_masked.png', rgb_image) else: mask_postproc = max_masked # 레이블 rle로 저장 for i in range(1, num_class): # 데이터 이름에 _1,_2,_3 붙이기 name_i = name + f'_{i}' mask_i = mask_postproc[i, :, :] # 마스크는 0아니면 1 rle_dict[name_i] = apply_thresholds( mask_i, n_objects, area_threshold, top_score_threshold, bottom_score_threshold, leak_score_threshold, use_contours, min_contour_area, sub_img_path + name_i ) return rle_dict def buid_submission(rle_dict, sample_sub): sub = pd.DataFrame.from_dict([rle_dict]).T.reset_index() sub.columns = sample_sub.columns sub.loc[sub.EncodedPixels == '', 'EncodedPixels'] = -1 return sub def load_mask_dict(cfg): reshape_mode = cfg.get('RESHAPE_MODE', False) if 'MASK_DICT' in cfg: result_path = Path(cfg['MASK_DICT']) with open(result_path, 'rb') as handle: mask_dict = pickle.load(handle) return mask_dict if 'RESULT_WEIGHTS' in cfg: result_weights = cfg['RESULT_WEIGHTS'] mask_dict = defaultdict(int) for result_path, weight in result_weights.items(): print(result_path, weight) with open(Path(result_path), 'rb') as handle: current_mask_dict = pickle.load(handle) for name, mask in current_mask_dict.items(): if reshape_mode and mask.shape[1] != 512: reshaped_mask = np.zeros([mask.shape[0],512,512]) for c in range(mask.shape[0]): reshaped_mask[c,:,:] = cv2.resize(mask[c,:,:], dsize=(512, 512), interpolation=cv2.INTER_LINEAR) mask = reshaped_mask #crazy_mask = (mask > 0.75).astype(np.uint8) #if crazy_mask.sum() < 1000: # mask = np.zeros_like(mask) mask_dict[name] = mask_dict[name] + mask * weight return mask_dict def main(): args = argparser() # config_path = 'experiments/albunet_public/05_submit.yaml' # config_path = Path(args.cfg.strip("/")) sub_config = load_yaml(config_path) print(sub_config) sample_sub = pd.read_csv(sub_config['SAMPLE_SUB']) n_objects_dict = sample_sub.ImageId.value_counts().to_dict() print('start loading mask results....') mask_dict = load_mask_dict(sub_config) use_contours = sub_config['USECONTOURS'] min_contour_area = sub_config.get('MIN_CONTOUR_AREA', 0) area_threshold = sub_config['AREA_THRESHOLD'] top_score_threshold = sub_config['TOP_SCORE_THRESHOLD'] bottom_score_threshold = sub_config['BOTTOM_SCORE_THRESHOLD'] if sub_config['USELEAK']: leak_score_threshold = sub_config['LEAK_SCORE_THRESHOLD'] else: leak_score_threshold = bottom_score_threshold sub_file = Path(sub_config['SUB_FILE']) sub_img_path = '../subs/' + sub_file.parts[-1][:-4] + '/' if not os.path.exists(sub_img_path): os.mkdir(sub_img_path) rle_dict = build_rle_dict( mask_dict, n_objects_dict, area_threshold, top_score_threshold, bottom_score_threshold, leak_score_threshold, use_contours, min_contour_area, sub_img_path ) sub = buid_submission(rle_dict, sample_sub) print((sub.EncodedPixels != -1).sum()) print(sub.head()) sub.to_csv(sub_file, index=False) if __name__ == "__main__": main()
[ "os.mkdir", "argparse.ArgumentParser", "pandas.read_csv", "collections.defaultdict", "numpy.argsort", "pathlib.Path", "pickle.load", "utils.mask_functions.rle_encode", "cv2.contourArea", "cv2.imwrite", "os.path.exists", "numpy.transpose", "numpy.max", "cv2.drawContours", "cv2.resize", ...
[((297, 354), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Body Morp pipeline"""'}), "(description='Body Morp pipeline')\n", (320, 354), False, 'import argparse\n'), ((727, 757), 'numpy.zeros', 'np.zeros', (['mask.shape', 'np.uint8'], {}), '(mask.shape, np.uint8)\n', (735, 757), True, 'import numpy as np\n'), ((772, 858), 'cv2.drawContours', 'cv2.drawContours', (['background', 'contours[:n_objects]', '(-1)', '(255)'], {'thickness': 'cv2.FILLED'}), '(background, contours[:n_objects], -1, 255, thickness=cv2.\n FILLED)\n', (788, 858), False, 'import cv2\n'), ((1149, 1179), 'numpy.zeros', 'np.zeros', (['mask.shape', 'np.uint8'], {}), '(mask.shape, np.uint8)\n', (1157, 1179), True, 'import numpy as np\n'), ((1194, 1263), 'cv2.drawContours', 'cv2.drawContours', (['background', 'contours', '(-1)', '(255)'], {'thickness': 'cv2.FILLED'}), '(background, contours, -1, 255, thickness=cv2.FILLED)\n', (1210, 1263), False, 'import cv2\n'), ((2322, 2347), 'utils.mask_functions.rle_encode', 'rle_encode', (['reshaped_mask'], {}), '(reshaped_mask)\n', (2332, 2347), False, 'from utils.mask_functions import mask2rle, rle_encode\n'), ((2515, 2545), 'numpy.zeros', 'np.zeros', (['mask.shape', 'np.uint8'], {}), '(mask.shape, np.uint8)\n', (2523, 2545), True, 'import numpy as np\n'), ((8685, 8707), 'utils.helpers.load_yaml', 'load_yaml', (['config_path'], {}), '(config_path)\n', (8694, 8707), False, 'from utils.helpers import load_yaml\n'), ((8752, 8789), 'pandas.read_csv', 'pd.read_csv', (["sub_config['SAMPLE_SUB']"], {}), "(sub_config['SAMPLE_SUB'])\n", (8763, 8789), True, 'import pandas as pd\n'), ((9411, 9439), 'pathlib.Path', 'Path', (["sub_config['SUB_FILE']"], {}), "(sub_config['SUB_FILE'])\n", (9415, 9439), False, 'from pathlib import Path\n'), ((613, 631), 'cv2.contourArea', 'cv2.contourArea', (['c'], {}), '(c)\n', (628, 631), False, 'import cv2\n'), ((666, 684), 'numpy.array', 'np.array', (['contours'], {}), '(contours)\n', (674, 684), True, 'import numpy as np\n'), ((2087, 2153), 'cv2.resize', 'cv2.resize', (['mask'], {'dsize': '(512, 512)', 'interpolation': 'cv2.INTER_LINEAR'}), '(mask, dsize=(512, 512), interpolation=cv2.INTER_LINEAR)\n', (2097, 2153), False, 'import cv2\n'), ((3309, 3397), 'cv2.drawContours', 'cv2.drawContours', (['mask_larges[i, :, :]', 'max_contours', '(-1)', '(255)'], {'thickness': 'cv2.FILLED'}), '(mask_larges[i, :, :], max_contours, -1, 255, thickness=cv2\n .FILLED)\n', (3325, 3397), False, 'import cv2\n'), ((5499, 5547), 'numpy.zeros', 'np.zeros', (['[max_mask.shape[1], max_mask.shape[2]]'], {}), '([max_mask.shape[1], max_mask.shape[2]])\n', (5507, 5547), True, 'import numpy as np\n'), ((5740, 5796), 'cv2.imwrite', 'cv2.imwrite', (["(sub_img_path + name + '_rgb.png')", 'rgb_image'], {}), "(sub_img_path + name + '_rgb.png', rgb_image)\n", (5751, 5796), False, 'import cv2\n'), ((7372, 7394), 'pathlib.Path', 'Path', (["cfg['MASK_DICT']"], {}), "(cfg['MASK_DICT'])\n", (7376, 7394), False, 'from pathlib import Path\n'), ((7611, 7627), 'collections.defaultdict', 'defaultdict', (['int'], {}), '(int)\n', (7622, 7627), False, 'from collections import defaultdict\n'), ((9513, 9541), 'os.path.exists', 'os.path.exists', (['sub_img_path'], {}), '(sub_img_path)\n', (9527, 9541), False, 'import os\n'), ((9551, 9573), 'os.mkdir', 'os.mkdir', (['sub_img_path'], {}), '(sub_img_path)\n', (9559, 9573), False, 'import os\n'), ((685, 702), 'numpy.argsort', 'np.argsort', (['areas'], {}), '(areas)\n', (695, 702), True, 'import numpy as np\n'), ((5204, 5227), 'numpy.zeros', 'np.zeros', (['[4, 512, 512]'], {}), '([4, 512, 512])\n', (5212, 5227), True, 'import numpy as np\n'), ((6323, 6378), 'numpy.transpose', 'np.transpose', (['(mask_postproc[1:4, :, :] * 255)', '(1, 2, 0)'], {}), '(mask_postproc[1:4, :, :] * 255, (1, 2, 0))\n', (6335, 6378), True, 'import numpy as np\n'), ((6391, 6454), 'cv2.imwrite', 'cv2.imwrite', (["(sub_img_path + name + '_rgb_masked.png')", 'rgb_image'], {}), "(sub_img_path + name + '_rgb_masked.png', rgb_image)\n", (6402, 6454), False, 'import cv2\n'), ((7467, 7486), 'pickle.load', 'pickle.load', (['handle'], {}), '(handle)\n', (7478, 7486), False, 'import pickle\n'), ((1092, 1110), 'cv2.contourArea', 'cv2.contourArea', (['c'], {}), '(c)\n', (1107, 1110), False, 'import cv2\n'), ((3715, 3777), 'numpy.zeros', 'np.zeros', (['[mask_uint8.shape[1], mask_uint8.shape[2]]', 'np.uint8'], {}), '([mask_uint8.shape[1], mask_uint8.shape[2]], np.uint8)\n', (3723, 3777), True, 'import numpy as np\n'), ((3874, 3923), 'cv2.getStructuringElement', 'cv2.getStructuringElement', (['cv2.MORPH_RECT', '(3, 3)'], {}), '(cv2.MORPH_RECT, (3, 3))\n', (3899, 3923), False, 'import cv2\n'), ((5309, 5384), 'cv2.resize', 'cv2.resize', (['mask[i, :, :]'], {'dsize': '(512, 512)', 'interpolation': 'cv2.INTER_LINEAR'}), '(mask[i, :, :], dsize=(512, 512), interpolation=cv2.INTER_LINEAR)\n', (5319, 5384), False, 'import cv2\n'), ((7085, 7119), 'pandas.DataFrame.from_dict', 'pd.DataFrame.from_dict', (['[rle_dict]'], {}), '([rle_dict])\n', (7107, 7119), True, 'import pandas as pd\n'), ((7820, 7839), 'pickle.load', 'pickle.load', (['handle'], {}), '(handle)\n', (7831, 7839), False, 'import pickle\n'), ((2880, 2898), 'cv2.contourArea', 'cv2.contourArea', (['c'], {}), '(c)\n', (2895, 2898), False, 'import cv2\n'), ((2967, 2985), 'cv2.contourArea', 'cv2.contourArea', (['c'], {}), '(c)\n', (2982, 2985), False, 'import cv2\n'), ((4429, 4443), 'numpy.amax', 'np.amax', (['score'], {}), '(score)\n', (4436, 4443), True, 'import numpy as np\n'), ((5683, 5712), 'numpy.max', 'np.max', (['max_masked[1:4, :, :]'], {}), '(max_masked[1:4, :, :])\n', (5689, 5712), True, 'import numpy as np\n'), ((7748, 7765), 'pathlib.Path', 'Path', (['result_path'], {}), '(result_path)\n', (7752, 7765), False, 'from pathlib import Path\n'), ((8003, 8038), 'numpy.zeros', 'np.zeros', (['[mask.shape[0], 512, 512]'], {}), '([mask.shape[0], 512, 512])\n', (8011, 8038), True, 'import numpy as np\n'), ((8143, 8218), 'cv2.resize', 'cv2.resize', (['mask[c, :, :]'], {'dsize': '(512, 512)', 'interpolation': 'cv2.INTER_LINEAR'}), '(mask[c, :, :], dsize=(512, 512), interpolation=cv2.INTER_LINEAR)\n', (8153, 8218), False, 'import cv2\n')]
import os import gc import time import torch import random import pickle import numpy as np import pandas as pd from tqdm import tqdm from torch.autograd import Variable from train_help import * from multi_task_models import * import torch import yaml with open("./config.yaml") as file: config = yaml.load(file) class AddGaussianNoise(object): def __init__(self, mean=0., std=1.): self.std = std self.mean = mean def __call__(self, tensor): return tensor + (torch.randn(tensor.size()).cuda()) * self.std + self.mean def __repr__(self): return self.__class__.__name__ + '(mean={0}, std={1})'.format(self.mean, self.std) def get_embeddings(model, reverse_encoded_vocab, epoch, batch_id): embedding_matrix = model.embeddings.weight.data.clone() if torch.cuda.is_available(): embedding_matrix = embedding_matrix.cpu() embedding_matrix = embedding_matrix.numpy() final_layer_embeddings = {} for i in reverse_encoded_vocab: final_layer_embeddings[reverse_encoded_vocab[i]] = embedding_matrix[i] with open('../saved/amazon_embeddings_'+config["model_name"]+'_e-{}_b-{}_.pkl'.format(epoch, batch_id), 'wb') as file: pickle.dump(final_layer_embeddings, file) def train(): category = config["category"] gaussian = AddGaussianNoise() prod_images = get_image_data(category) encoded_data, encoded_vocab, reverse_encoded_vocab, user_dict, prod_dict = encode(category, bool(config["weights"])) total_words = len(encoded_vocab) print('\nVocabulary size = ', total_words) ## Declare embedding dimension ## embedding_dimension = config["embedding_dim"] ################################# if (bool(config["load_saved_decoder"])): skip_gram_model = SkipGram2(len(encoded_vocab),config["embedding_dim"],encoded_vocab,prod_images,4096, '../saved/'+str(config["embedding_dim"])+'dim_ae_encoder') image_model = ImageDecoder(embedding_dimension = embedding_dimension, image_dimension = 4096) image_model.load_state_dict(torch.load('../saved/'+str(config["embedding_dim"])+'dim_ae_decoder')) multi_task_model = MultiTaskLossWrapper(task_num = 2) else: skip_gram_model = SkipGram(vocab_size = total_words, embedding_dimension = embedding_dimension) image_model = ImageDecoder(embedding_dimension = embedding_dimension, image_dimension = 4096) multi_task_model = MultiTaskLossWrapper(task_num = 2) if torch.cuda.is_available(): print('!!GPU!!') skip_gram_model.cuda() image_model.cuda() multi_task_model.cuda() skip_optimizer = torch.optim.Adam(skip_gram_model.parameters(), lr = 0.01) image_optimizer = torch.optim.Adam(list(image_model.parameters()) + list(skip_gram_model.parameters()) + list(multi_task_model.parameters()), lr = 0.01) print('\nStart Training\n') epoch_num = config["multi_train_epochs"] batch_size = config["multi_train_batch_size"] Kill = True p_u_ratio = int(len(prod_dict)/len(user_dict)) print('#products/#users = ', p_u_ratio) epoch = 0 for batch, batch_id, train_mode in gen(encoded_data, reverse_encoded_vocab, batch_size, p_u_ratio, user_dict, prod_dict): if batch_id == 2: print('Saving model and embeddings') torch.save(image_model.state_dict(), '../saved/'+config["model_name"]+'_image_model.e-{}_b-{}_'.format(epoch, int(batch_id))) torch.save(skip_gram_model.state_dict(), '../saved/'+config["model_name"]+'_skip_gram_model.e-{}_b-{}_'.format(epoch, int(batch_id))) get_embeddings(skip_gram_model, reverse_encoded_vocab, epoch, int(batch_id)) epoch += 1 start_b = time.time() batch = np.array(batch) words = Variable(torch.LongTensor(batch[:,0])) context_words = Variable(torch.LongTensor(batch[:,1])) retain = False if train_mode == 'prod': image_batch = generate_image_batch(batch, prod_images, reverse_encoded_vocab) image_batch = Variable(torch.FloatTensor(image_batch)) retain = True if torch.cuda.is_available(): words = words.cuda() context_words = context_words.cuda() if train_mode == 'prod': image_batch = image_batch.cuda() skip_optimizer.zero_grad() image_optimizer.zero_grad() skip_gram_loss, skip_gram_emb = skip_gram_model(words, context_words) if train_mode == 'user': skip_gram_loss.backward() skip_optimizer.step() if train_mode == 'prod': if (bool(config["add_noise"])): skip_gram_emb = gaussian(skip_gram_emb) pred_image = image_model(skip_gram_emb) image_loss, only_image = multi_task_model(skip_gram_loss, pred_image, image_batch) ######################## image_loss.backward() image_optimizer.step() ######################## if batch_id % 100 == 0: end_b = time.time() print('epoch = {}\tbatch = {}\tskip_gram_loss = {:.5f}\t\timage_loss = {:.5f}\t\ttime = {:.2f}'.format(epoch, batch_id, skip_gram_loss, only_image, end_b - start_b)) start_b = time.time() if batch_id % 3000 == 0: print('Saving model and embeddings') torch.save(image_model.state_dict(), '../saved/'+config["model_name"]+'_image_model.e-{}_b-{}_'.format(epoch, int(batch_id))) torch.save(skip_gram_model.state_dict(), '../saved/'+config["model_name"]+'_skip_gram_model.e-{}_b-{}_'.format(epoch, int(batch_id))) get_embeddings(skip_gram_model, reverse_encoded_vocab, epoch, int(batch_id)) if epoch > epoch_num: print("\nOptimization Finished") break return model if __name__ == '__main__': model = train()
[ "yaml.load", "pickle.dump", "torch.LongTensor", "torch.FloatTensor", "time.time", "numpy.array", "torch.cuda.is_available" ]
[((301, 316), 'yaml.load', 'yaml.load', (['file'], {}), '(file)\n', (310, 316), False, 'import yaml\n'), ((784, 809), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (807, 809), False, 'import torch\n'), ((2393, 2418), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (2416, 2418), False, 'import torch\n'), ((1161, 1202), 'pickle.dump', 'pickle.dump', (['final_layer_embeddings', 'file'], {}), '(final_layer_embeddings, file)\n', (1172, 1202), False, 'import pickle\n'), ((3538, 3549), 'time.time', 'time.time', ([], {}), '()\n', (3547, 3549), False, 'import time\n'), ((3560, 3575), 'numpy.array', 'np.array', (['batch'], {}), '(batch)\n', (3568, 3575), True, 'import numpy as np\n'), ((3889, 3914), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (3912, 3914), False, 'import torch\n'), ((3595, 3624), 'torch.LongTensor', 'torch.LongTensor', (['batch[:, 0]'], {}), '(batch[:, 0])\n', (3611, 3624), False, 'import torch\n'), ((3652, 3681), 'torch.LongTensor', 'torch.LongTensor', (['batch[:, 1]'], {}), '(batch[:, 1])\n', (3668, 3681), False, 'import torch\n'), ((4655, 4666), 'time.time', 'time.time', ([], {}), '()\n', (4664, 4666), False, 'import time\n'), ((4849, 4860), 'time.time', 'time.time', ([], {}), '()\n', (4858, 4860), False, 'import time\n'), ((3834, 3864), 'torch.FloatTensor', 'torch.FloatTensor', (['image_batch'], {}), '(image_batch)\n', (3851, 3864), False, 'import torch\n')]
import numpy as np def calc_bic(num_params: float, data_size: float, log_likelihood: float) -> float: return -2 * log_likelihood + num_params * np.log(data_size)
[ "numpy.log" ]
[((150, 167), 'numpy.log', 'np.log', (['data_size'], {}), '(data_size)\n', (156, 167), True, 'import numpy as np\n')]
#!/usr/bin/env python import rospy, cv2, cv_bridge, numpy, math, imutils from geometry_msgs.msg import Twist from nav_msgs.msg import Odometry from std_msgs.msg import Int32 from sensor_msgs.msg import Image from tf.transformations import euler_from_quaternion from scipy.spatial import distance from collections import OrderedDict class CPU: def __init__(self): ###############Publishers################# #pubs self.bridge = cv_bridge.CvBridge() self.move = rospy.Publisher('/cpu/cmd_vel', Twist, queue_size=1) #subs self.cpsub = rospy.Subscriber('cpu/odom', Odometry, self.odom_cb) self.color = rospy.Subscriber('color_mode', Int32, self.color_cb) #self.status = rospy.Subscriber('winner', Int32, self.status_cb) self.goal = rospy.Subscriber('goal', Int32, self.goal_tile) self.eyes = rospy.Subscriber('/cpu/camera/rgb/image_raw', Image, self.image_callback) #variables self.goal = [0,0] self.location = [0,0] self.permission = False # tells the robot if it can go on a tile self.nextStep = "" self.color = "" self.setting = "black" self.direction = 0 # right self.status = 0 self.kp = .5 self.d = rospy.Duration.from_sec(10) self.colors = OrderedDict({ "black" : (0, 0, 0), "white" : (255, 255, 255)}) self.rate = rospy.Rate(10) self.gas_pedal = Twist() self.lab = numpy.zeros((len(self.colors), 1, 3), dtype="uint8") self.colornames = [] for (i, (name, rgb)) in enumerate(self.colors.items()): self.lab[i] = rgb self.colornames.append(name) self.lab = cv2.cvtColor(self.lab, cv2.COLOR_BGR2LAB) def image_callback(self, msg): self.image = self.bridge.imgmsg_to_cv2(msg) self.imgblur = cv2.GaussianBlur(self.image, (7,7), 1) self.gray = cv2.cvtColor(self.imgblur, cv2.COLOR_BGR2GRAY) cv2.imshow('original', self.image) # creates tunnel vision self.blank = numpy.zeros(self.image.shape[:2], dtype='uint8') mask = cv2.circle(self.blank, (1000,800), 25, 255, -1) masked = cv2.bitwise_and(self.image, self.image, mask=mask) cv2.imshow('eye', masked) #creating contour self.edge = cv2.Canny(masked, 75, 200) cv2.imshow('contour', self.edge) _, contours, _ = cv2.findContours(self.edge, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) contour_list = [] for contour in contours: self.approx = cv2.approxPolyDP(contour,0.01*cv2.arcLength(contour,True),True) self.area = cv2.contourArea(contour) if ((len(self.approx) > 8) & (len(self.approx) < 23) & (self.area > 30) ): contour_list.append(contour) mask = numpy.zeros(self.image.shape[:2], dtype="uint8") cv2.drawContours(mask, contour_list, 0, 255, -1) mask = cv2.erode(mask, None, iterations=2) mean = cv2.mean(self.image, mask=mask)[:3] #detecting color minDis = (numpy.inf, None) for (i, row) in enumerate(self.lab): d = distance.euclidean(row[0], mean) if d < minDis[0]: minDis = (d, i) self.nextStep = self.colornames[minDis[1]] if (self.nextStep == self.setting): self.permission = True else: self.permission = False print(str(self.colornames[minDis[1]])) cv2.waitKey(3) def goal_tile(msg): self.goal = msg.data def odom_cb(self,msg): self.x = msg.pose.pose.position.x self.y = msg.pose.pose.position.y self.orientation_q = msg.pose.pose.orientation self.orientation_list = [self.orientation_q.x, self.orientation_q.y, self.orientation_q.z, self.orientation_q.w] (self.roll, self.pitch, self.yaw) = euler_from_quaternion (self.orientation_list) # tells the robot what color it can go on def color_cb(self, msg): self.setting = msg.data # 0 is black, 1 is white if self.setting == 0: self.color = "black" else: self.color = "white" # status of game def status_cb(self, msg): self.leaderboard = msg.data if (self.status == 0): # no one has won self.game_on() else: if (self.status == 1): #cpu has won self.happydance() stop() # -----------------DIRECTIONS----------------------------- while (True): if (permission): self.drive() else: if (direction == 0): self.up() self.direction = 1 else: self.right() self.direction = 0 def up(): #moves into next box now = rospy.get_rostime() stop = self.d + now while (rospy.get_rostime() < stop): target_rad = 0 gas_pedal.angular.z = .5 * (target_rad-self.yaw) move.publish(gas_pedal) def right(): now = rospy.get_rostime() stop = self.d + now while (rospy.get_rostime() < stop): target_rad = -1.57 move.angular.z = .5 * (target_rad-self.yaw) move.publish(t) def stop(): while(true): self.gas_pedal.angular.z = 0 self.gas_pedal.linear.x = 0 self.publish(gas_pedal) def drive(): gas_pedal.angular.z = 0 gas_pedal.linear.x = .2 move.publish(gas_pedal) rospy.sleep(5) gas_pedal.linear.x = 0 move.publish(gas_pedal) rospy.sleep(5) def happy_dance(): self.gas_pedal.angular.z = 2 #meters self.move.publish(t) self.timebuffer() self.stop() def where_am_i(): print(str(location)) # set up nodes rospy.init_node('cpu') cpu = CPU() rospy.spin()
[ "cv2.GaussianBlur", "rospy.Subscriber", "cv2.bitwise_and", "cv2.arcLength", "rospy.Duration.from_sec", "cv2.erode", "cv2.imshow", "cv2.contourArea", "scipy.spatial.distance.euclidean", "cv2.cvtColor", "rospy.Rate", "rospy.init_node", "cv2.drawContours", "cv2.mean", "cv2.Canny", "cv2.ci...
[((5949, 5971), 'rospy.init_node', 'rospy.init_node', (['"""cpu"""'], {}), "('cpu')\n", (5964, 5971), False, 'import rospy, cv2, cv_bridge, numpy, math, imutils\n'), ((5984, 5996), 'rospy.spin', 'rospy.spin', ([], {}), '()\n', (5994, 5996), False, 'import rospy, cv2, cv_bridge, numpy, math, imutils\n'), ((456, 476), 'cv_bridge.CvBridge', 'cv_bridge.CvBridge', ([], {}), '()\n', (474, 476), False, 'import rospy, cv2, cv_bridge, numpy, math, imutils\n'), ((497, 549), 'rospy.Publisher', 'rospy.Publisher', (['"""/cpu/cmd_vel"""', 'Twist'], {'queue_size': '(1)'}), "('/cpu/cmd_vel', Twist, queue_size=1)\n", (512, 549), False, 'import rospy, cv2, cv_bridge, numpy, math, imutils\n'), ((586, 638), 'rospy.Subscriber', 'rospy.Subscriber', (['"""cpu/odom"""', 'Odometry', 'self.odom_cb'], {}), "('cpu/odom', Odometry, self.odom_cb)\n", (602, 638), False, 'import rospy, cv2, cv_bridge, numpy, math, imutils\n'), ((660, 712), 'rospy.Subscriber', 'rospy.Subscriber', (['"""color_mode"""', 'Int32', 'self.color_cb'], {}), "('color_mode', Int32, self.color_cb)\n", (676, 712), False, 'import rospy, cv2, cv_bridge, numpy, math, imutils\n'), ((806, 853), 'rospy.Subscriber', 'rospy.Subscriber', (['"""goal"""', 'Int32', 'self.goal_tile'], {}), "('goal', Int32, self.goal_tile)\n", (822, 853), False, 'import rospy, cv2, cv_bridge, numpy, math, imutils\n'), ((874, 947), 'rospy.Subscriber', 'rospy.Subscriber', (['"""/cpu/camera/rgb/image_raw"""', 'Image', 'self.image_callback'], {}), "('/cpu/camera/rgb/image_raw', Image, self.image_callback)\n", (890, 947), False, 'import rospy, cv2, cv_bridge, numpy, math, imutils\n'), ((1278, 1305), 'rospy.Duration.from_sec', 'rospy.Duration.from_sec', (['(10)'], {}), '(10)\n', (1301, 1305), False, 'import rospy, cv2, cv_bridge, numpy, math, imutils\n'), ((1330, 1389), 'collections.OrderedDict', 'OrderedDict', (["{'black': (0, 0, 0), 'white': (255, 255, 255)}"], {}), "({'black': (0, 0, 0), 'white': (255, 255, 255)})\n", (1341, 1389), False, 'from collections import OrderedDict\n'), ((1450, 1464), 'rospy.Rate', 'rospy.Rate', (['(10)'], {}), '(10)\n', (1460, 1464), False, 'import rospy, cv2, cv_bridge, numpy, math, imutils\n'), ((1490, 1497), 'geometry_msgs.msg.Twist', 'Twist', ([], {}), '()\n', (1495, 1497), False, 'from geometry_msgs.msg import Twist\n'), ((1757, 1798), 'cv2.cvtColor', 'cv2.cvtColor', (['self.lab', 'cv2.COLOR_BGR2LAB'], {}), '(self.lab, cv2.COLOR_BGR2LAB)\n', (1769, 1798), False, 'import rospy, cv2, cv_bridge, numpy, math, imutils\n'), ((1910, 1949), 'cv2.GaussianBlur', 'cv2.GaussianBlur', (['self.image', '(7, 7)', '(1)'], {}), '(self.image, (7, 7), 1)\n', (1926, 1949), False, 'import rospy, cv2, cv_bridge, numpy, math, imutils\n'), ((1969, 2015), 'cv2.cvtColor', 'cv2.cvtColor', (['self.imgblur', 'cv2.COLOR_BGR2GRAY'], {}), '(self.imgblur, cv2.COLOR_BGR2GRAY)\n', (1981, 2015), False, 'import rospy, cv2, cv_bridge, numpy, math, imutils\n'), ((2024, 2058), 'cv2.imshow', 'cv2.imshow', (['"""original"""', 'self.image'], {}), "('original', self.image)\n", (2034, 2058), False, 'import rospy, cv2, cv_bridge, numpy, math, imutils\n'), ((2110, 2158), 'numpy.zeros', 'numpy.zeros', (['self.image.shape[:2]'], {'dtype': '"""uint8"""'}), "(self.image.shape[:2], dtype='uint8')\n", (2121, 2158), False, 'import rospy, cv2, cv_bridge, numpy, math, imutils\n'), ((2174, 2222), 'cv2.circle', 'cv2.circle', (['self.blank', '(1000, 800)', '(25)', '(255)', '(-1)'], {}), '(self.blank, (1000, 800), 25, 255, -1)\n', (2184, 2222), False, 'import rospy, cv2, cv_bridge, numpy, math, imutils\n'), ((2239, 2289), 'cv2.bitwise_and', 'cv2.bitwise_and', (['self.image', 'self.image'], {'mask': 'mask'}), '(self.image, self.image, mask=mask)\n', (2254, 2289), False, 'import rospy, cv2, cv_bridge, numpy, math, imutils\n'), ((2298, 2323), 'cv2.imshow', 'cv2.imshow', (['"""eye"""', 'masked'], {}), "('eye', masked)\n", (2308, 2323), False, 'import rospy, cv2, cv_bridge, numpy, math, imutils\n'), ((2368, 2394), 'cv2.Canny', 'cv2.Canny', (['masked', '(75)', '(200)'], {}), '(masked, 75, 200)\n', (2377, 2394), False, 'import rospy, cv2, cv_bridge, numpy, math, imutils\n'), ((2403, 2435), 'cv2.imshow', 'cv2.imshow', (['"""contour"""', 'self.edge'], {}), "('contour', self.edge)\n", (2413, 2435), False, 'import rospy, cv2, cv_bridge, numpy, math, imutils\n'), ((2462, 2529), 'cv2.findContours', 'cv2.findContours', (['self.edge', 'cv2.RETR_TREE', 'cv2.CHAIN_APPROX_SIMPLE'], {}), '(self.edge, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n', (2478, 2529), False, 'import rospy, cv2, cv_bridge, numpy, math, imutils\n'), ((2877, 2925), 'numpy.zeros', 'numpy.zeros', (['self.image.shape[:2]'], {'dtype': '"""uint8"""'}), "(self.image.shape[:2], dtype='uint8')\n", (2888, 2925), False, 'import rospy, cv2, cv_bridge, numpy, math, imutils\n'), ((2934, 2982), 'cv2.drawContours', 'cv2.drawContours', (['mask', 'contour_list', '(0)', '(255)', '(-1)'], {}), '(mask, contour_list, 0, 255, -1)\n', (2950, 2982), False, 'import rospy, cv2, cv_bridge, numpy, math, imutils\n'), ((2998, 3033), 'cv2.erode', 'cv2.erode', (['mask', 'None'], {'iterations': '(2)'}), '(mask, None, iterations=2)\n', (3007, 3033), False, 'import rospy, cv2, cv_bridge, numpy, math, imutils\n'), ((3542, 3556), 'cv2.waitKey', 'cv2.waitKey', (['(3)'], {}), '(3)\n', (3553, 3556), False, 'import rospy, cv2, cv_bridge, numpy, math, imutils\n'), ((3949, 3993), 'tf.transformations.euler_from_quaternion', 'euler_from_quaternion', (['self.orientation_list'], {}), '(self.orientation_list)\n', (3970, 3993), False, 'from tf.transformations import euler_from_quaternion\n'), ((4900, 4919), 'rospy.get_rostime', 'rospy.get_rostime', ([], {}), '()\n', (4917, 4919), False, 'import rospy, cv2, cv_bridge, numpy, math, imutils\n'), ((5149, 5168), 'rospy.get_rostime', 'rospy.get_rostime', ([], {}), '()\n', (5166, 5168), False, 'import rospy, cv2, cv_bridge, numpy, math, imutils\n'), ((5634, 5648), 'rospy.sleep', 'rospy.sleep', (['(5)'], {}), '(5)\n', (5645, 5648), False, 'import rospy, cv2, cv_bridge, numpy, math, imutils\n'), ((5720, 5734), 'rospy.sleep', 'rospy.sleep', (['(5)'], {}), '(5)\n', (5731, 5734), False, 'import rospy, cv2, cv_bridge, numpy, math, imutils\n'), ((2704, 2728), 'cv2.contourArea', 'cv2.contourArea', (['contour'], {}), '(contour)\n', (2719, 2728), False, 'import rospy, cv2, cv_bridge, numpy, math, imutils\n'), ((3049, 3080), 'cv2.mean', 'cv2.mean', (['self.image'], {'mask': 'mask'}), '(self.image, mask=mask)\n', (3057, 3080), False, 'import rospy, cv2, cv_bridge, numpy, math, imutils\n'), ((3208, 3240), 'scipy.spatial.distance.euclidean', 'distance.euclidean', (['row[0]', 'mean'], {}), '(row[0], mean)\n', (3226, 3240), False, 'from scipy.spatial import distance\n'), ((4963, 4982), 'rospy.get_rostime', 'rospy.get_rostime', ([], {}), '()\n', (4980, 4982), False, 'import rospy, cv2, cv_bridge, numpy, math, imutils\n'), ((5212, 5231), 'rospy.get_rostime', 'rospy.get_rostime', ([], {}), '()\n', (5229, 5231), False, 'import rospy, cv2, cv_bridge, numpy, math, imutils\n'), ((2646, 2674), 'cv2.arcLength', 'cv2.arcLength', (['contour', '(True)'], {}), '(contour, True)\n', (2659, 2674), False, 'import rospy, cv2, cv_bridge, numpy, math, imutils\n')]
import numpy as np import pytest from alibi_detect.cd import MMDDriftOnline from alibi_detect.cd.pytorch.mmd_online import MMDDriftOnlineTorch from alibi_detect.cd.tensorflow.mmd_online import MMDDriftOnlineTF n, n_features = 100, 5 tests_mmddriftonline = ['tensorflow', 'pytorch', 'PyToRcH', 'mxnet'] n_tests = len(tests_mmddriftonline) @pytest.fixture def mmddriftonline_params(request): return tests_mmddriftonline[request.param] @pytest.mark.parametrize('mmddriftonline_params', list(range(n_tests)), indirect=True) def test_mmddriftonline(mmddriftonline_params): backend = mmddriftonline_params x_ref = np.random.randn(*(n, n_features)) # Instantiate and check detector class try: cd = MMDDriftOnline(x_ref=x_ref, ert=25, window_size=5, backend=backend, n_bootstraps=100) except NotImplementedError: cd = None if backend.lower() == 'pytorch': assert isinstance(cd._detector, MMDDriftOnlineTorch) elif backend.lower() == 'tensorflow': assert isinstance(cd._detector, MMDDriftOnlineTF) else: assert cd is None return # Test predict x_t = np.random.randn(n_features) t0 = cd.t cd.predict(x_t) assert cd.t - t0 == 1 # This checks state updated (self.t at least) # Test score t0 = cd.t cd.score(x_t) assert cd.t - t0 == 1
[ "alibi_detect.cd.MMDDriftOnline", "numpy.random.randn" ]
[((626, 659), 'numpy.random.randn', 'np.random.randn', (['*(n, n_features)'], {}), '(*(n, n_features))\n', (641, 659), True, 'import numpy as np\n'), ((1142, 1169), 'numpy.random.randn', 'np.random.randn', (['n_features'], {}), '(n_features)\n', (1157, 1169), True, 'import numpy as np\n'), ((726, 815), 'alibi_detect.cd.MMDDriftOnline', 'MMDDriftOnline', ([], {'x_ref': 'x_ref', 'ert': '(25)', 'window_size': '(5)', 'backend': 'backend', 'n_bootstraps': '(100)'}), '(x_ref=x_ref, ert=25, window_size=5, backend=backend,\n n_bootstraps=100)\n', (740, 815), False, 'from alibi_detect.cd import MMDDriftOnline\n')]
"""This module contains function solely related to the estimation of the model.""" import shutil import copy import os from statsmodels.tools.eval_measures import rmse as get_rmse from scipy.optimize import minimize import pandas as pd import numpy as np from trempy.shared.shared_auxiliary import get_optimal_compensations from trempy.shared.shared_auxiliary import dist_class_attributes from trempy.shared.shared_auxiliary import char_floats from trempy.config_trempy import PREFERENCE_PARAMETERS from trempy.config_trempy import NEVER_SWITCHERS from trempy.custom_exceptions import MaxfunError from trempy.simulate.simulate import simulate from trempy.config_trempy import SMALL_FLOAT from trempy.config_trempy import HUGE_FLOAT from trempy.shared.clsBase import BaseCls class StartClass(BaseCls): """This class manages all issues about the model estimation.""" def __init__(self, questions, m_optimal_obs, start_fixed, start_utility_paras, version, **version_specific): """Init class.""" self.attr = dict() self.attr['version'] = version # Handle version-specific objects if version in ['scaled_archimedean']: # assert all(x in version_specific.keys() for x in ['marginals', 'upper']) self.attr['marginals'] = version_specific['marginals'] self.attr['upper'] = version_specific['upper'] elif version in ['nonstationary']: pass # Initialization attributes self.attr['start_utility_paras'] = start_utility_paras self.attr['m_optimal_obs'] = m_optimal_obs self.attr['start_fixed'] = start_fixed self.attr['questions'] = questions # Housekeeping attributes self.attr['f_current'] = HUGE_FLOAT self.attr['f_start'] = HUGE_FLOAT self.attr['f_step'] = HUGE_FLOAT self.attr['num_eval'] = 0 def evaluate(self, x_vals): """Evalute. This will be the criterion function.""" if self.attr['num_eval'] > 10: return HUGE_FLOAT version = self.attr['version'] if version in ['scaled_archimedean']: marginals = self.attr['marginals'] upper = self.attr['upper'] version_specific = {'upper': upper, 'marginals': marginals} elif version in ['nonstationary']: version_specific = dict() start_utility_paras = self.attr['start_utility_paras'] m_optimal_obs = self.attr['m_optimal_obs'] start_fixed = self.attr['start_fixed'] questions = self.attr['questions'] # Override non-fixed values in the para_obj with the xvals. utility_cand = copy.deepcopy(start_utility_paras) para_obj = utility_cand.attr['para_objs'] j = 0 nparas_econ = start_utility_paras.attr['nparas_econ'] for i in range(nparas_econ): if start_fixed[i]: continue else: para_obj[i].attr['value'] = x_vals[j] j += 1 # Update para_obj in utility candidate utility_cand.attr['para_objs'] = para_obj m_optimal_cand = get_optimal_compensations( version=version, paras_obj=utility_cand, questions=questions, **version_specific) m_optimal_cand = np.array([m_optimal_cand[q] for q in questions]) # We need to ensure that we only compare values if the mean is not missing. np_stats = np.tile(np.nan, (len(questions), 2)) for i, _ in enumerate(questions): np_stats[i, :] = [m_optimal_obs[i], m_optimal_cand[i]] np_stats = np_stats[~np.isnan(np_stats).any(axis=1)] fval = np.mean((np_stats[:, 0] - np_stats[:, 1]) ** 2) # Update class attributes self.attr['num_eval'] += 1 self._update_evaluation(fval, x_vals) return fval def _update_evaluation(self, fval, x_vals): """Update all attributes based on the new evaluation and write some information to files.""" self.attr['f_current'] = fval self.attr['num_eval'] += 1 # Determine special events is_start = self.attr['num_eval'] == 1 is_step = fval < self.attr['f_step'] # Record information at start if is_start: self.attr['x_vals_start'] = x_vals self.attr['f_start'] = fval # Record information at step if is_step: self.attr['x_vals_step'] = x_vals self.attr['f_step'] = fval if self.attr['num_eval'] == 100: raise MaxfunError def get_automatic_starting_values(paras_obj, df_obs, questions, version, **version_specific): """Update the container for the parameters with the automatic starting values.""" def _adjust_bounds(value, bounds): """Adjust the starting values to meet the requirements of the bounds.""" lower, upper = bounds if value <= bounds[0]: value = lower + 2 * SMALL_FLOAT elif value >= bounds[1]: value = upper - 2 * SMALL_FLOAT else: pass return value # During testing it might occur that we in fact run an estimation on a dataset that does not # contain any interior observations for any question. This results in a failure of the # automatic determination of the starting values and is thus ruled out here from the # beginning. In that case, we simply use the starting values from the initialization file. cond = df_obs['Compensation'].isin([NEVER_SWITCHERS]) df_mask = df_obs['Compensation'].mask(cond) if df_mask.isnull().all(): return paras_obj # We first get the observed average compensation from the data. m_optimal_obs = [df_mask.loc[slice(None), q].mean() for q in questions] m_optimal_obs = np.array(m_optimal_obs) # Now we gather information about the utility parameters and prepare for the interface to the # optimization algorithm. # start_utility_paras = paras_obj.get_values('econ', 'all')[:5 start_paras, start_bounds, start_fixed = [], [], [] for label in PREFERENCE_PARAMETERS[version]: value, is_fixed, bounds = paras_obj.get_para(label) start_fixed += [is_fixed] # Get list of labels that are not fixed if is_fixed: continue start_paras += [value] start_bounds += [bounds] # We minimize the squared distance between the observed and theoretical average # compensations. This is only a valid request if there are any free preference parameters. if len(start_paras) > 0: args = [questions, m_optimal_obs, start_fixed, copy.deepcopy(paras_obj), version] start_obj = StartClass(*args, **version_specific) try: minimize(start_obj.evaluate, start_paras, method='L-BFGS-B', bounds=start_bounds) except MaxfunError: pass start_utility = start_obj.get_attr('x_vals_step').tolist() # We construct the relevant set of free economic starting values. x_econ_free_start = [] for label in PREFERENCE_PARAMETERS[version] + questions: value, is_fixed, bounds = paras_obj.get_para(label) if is_fixed: continue else: if label in PREFERENCE_PARAMETERS[version]: x_econ_free_start += [_adjust_bounds(start_utility.pop(0), bounds)] else: cond = df_obs['Compensation'].isin([NEVER_SWITCHERS]) value = df_obs['Compensation'].mask(cond).loc[slice(None), label].std() # If there are no individuals observed without truncation for a particular # question, we start with 0.1. if pd.isnull(value): x_econ_free_start += [_adjust_bounds(0.1, bounds)] else: x_econ_free_start += [_adjust_bounds(value, bounds)] paras_obj.set_values('econ', 'free', x_econ_free_start) return paras_obj def estimate_cleanup(): """Ensure that we start the estimation with a clean slate.""" # We remove the directories that contain the simulated choice menus at the start. for dirname in ['start', 'stop']: if os.path.exists(dirname): shutil.rmtree(dirname) # We remove the information from earlier estimation runs. for fname in ['est.trempy.info', 'est.trempy.log', '.stop.trempy.scratch']: if os.path.exists(fname): os.remove(fname) def estimate_simulate(which, points, model_obj, df_obs): """Allow the user to easily simulate samples at the beginning and the end of the estimation.""" paras_obj, questions, version = \ dist_class_attributes(model_obj, 'paras_obj', 'questions', 'version') if version in ['scaled_archimedean']: upper, marginals = dist_class_attributes(model_obj, 'upper', 'marginals') version_specific = {'upper': upper, 'marginals': marginals} elif version in ['nonstationary']: version_specific = dict() m_optimal = get_optimal_compensations(version, paras_obj, questions, **version_specific) os.mkdir(which) os.chdir(which) sim_model = copy.deepcopy(model_obj) sim_model.attr['sim_file'] = which sim_model.update('optim', 'free', points) sim_model.write_out(which + '.trempy.ini') simulate(which + '.trempy.ini') compare_datasets(which, df_obs, questions, m_optimal) os.chdir('../') def compare_datasets(which, df_obs, questions, m_optimal): """Compare the estimation dataset with a simulated one using the estimated parameter vector.""" df_sim = pd.read_pickle(which + '.trempy.pkl') df_sim_masked = df_sim['Compensation'].mask(df_sim['Compensation'].isin([NEVER_SWITCHERS])) df_obs_masked = df_obs['Compensation'].mask(df_obs['Compensation'].isin([NEVER_SWITCHERS])) statistic = ['count', 'mean', 'std', 'min', '25%', '50%', '75%', 'max'] # Summary statistics -- simulated data n_sim = int(df_sim_masked.shape[0] / len(questions)) sim = df_sim_masked.groupby(['Question']).describe().to_dict(orient='index') stats_sim = {q: [n_sim] + [val[key] for key in statistic] for q, val in sim.items()} # Summary statistics -- observed data n_obs = int(df_obs_masked.shape[0] / len(questions)) obs = df_obs_masked.groupby(['Question']).describe().to_dict(orient='index') stats_obs = {q: [n_obs] + [val[key] for key in statistic] for q, val in obs.items()} # Collect statistics stats = {'sim': stats_sim, 'obs': stats_obs} with open('compare.trempy.info', 'w') as outfile: outfile.write('\n') string = '{:>15}' * 11 + '\n' label = [] label += ['', 'Question', 'Observed', 'Interior', 'Mean', 'Std.', 'Min.'] label += ['25%', '50%', '75%', 'Max.'] outfile.write(string.format(*label)) outfile.write('\n') for q in questions: for key_ in ['obs', 'sim']: if key_ == 'obs': label = 'Observed' elif key_ == 'sim': label = 'Simulated' info = [label, q] + stats[key_][q] for i in range(len(info)): if pd.isnull(info[i]): info[i] = '{:>15}'.format('---') continue if i in [1, 2, 3]: info[i] = '{:d}'.format(int(info[i])) if i in [4, 5, 6, 7, 8, 9, 10]: info[i] = '{:15.5f}'.format(info[i]) outfile.write(string.format(*info)) outfile.write('\n') # We calculate the RMSE based on all mean compensations. np_stats = np.tile(np.nan, (len(questions), 2)) for i, q in enumerate(questions): for j, label in enumerate(['obs', 'sim']): np_stats[i, j] = stats[label][q][2] np_stats = np_stats[~np.isnan(np_stats).any(axis=1)] # During testing it might occur that there are no interior observations for any # questions. if np_stats.size == 0: rmse = '---' else: rmse = '{:15.5f}\n'.format(get_rmse(*np_stats.T)) line = '{:>15}'.format('RMSE') + '{:>15}\n'.format(rmse) outfile.write(line) fmt_ = ' {:>10} ' + '{:>25} ' * 3 for identifier, df_individual in df_obs['Compensation'].groupby(level=0): outfile.write('\n Individual {:d}\n\n'.format(identifier)) outfile.write(fmt_.format(*['Question', 'Optimal', 'Observed', 'Difference']) + '\n\n') for (_, q), m_obs in df_individual.iteritems(): m_opt = m_optimal[q] info = ['{:d}'.format(q)] + char_floats(m_opt) + char_floats(m_obs) info += char_floats(m_obs - m_opt) outfile.write(fmt_.format(*info) + '\n')
[ "trempy.simulate.simulate.simulate", "os.mkdir", "copy.deepcopy", "scipy.optimize.minimize", "os.remove", "trempy.shared.shared_auxiliary.get_optimal_compensations", "os.path.exists", "trempy.shared.shared_auxiliary.dist_class_attributes", "pandas.isnull", "statsmodels.tools.eval_measures.rmse", ...
[((5824, 5847), 'numpy.array', 'np.array', (['m_optimal_obs'], {}), '(m_optimal_obs)\n', (5832, 5847), True, 'import numpy as np\n'), ((8690, 8759), 'trempy.shared.shared_auxiliary.dist_class_attributes', 'dist_class_attributes', (['model_obj', '"""paras_obj"""', '"""questions"""', '"""version"""'], {}), "(model_obj, 'paras_obj', 'questions', 'version')\n", (8711, 8759), False, 'from trempy.shared.shared_auxiliary import dist_class_attributes\n'), ((9043, 9119), 'trempy.shared.shared_auxiliary.get_optimal_compensations', 'get_optimal_compensations', (['version', 'paras_obj', 'questions'], {}), '(version, paras_obj, questions, **version_specific)\n', (9068, 9119), False, 'from trempy.shared.shared_auxiliary import get_optimal_compensations\n'), ((9125, 9140), 'os.mkdir', 'os.mkdir', (['which'], {}), '(which)\n', (9133, 9140), False, 'import os\n'), ((9145, 9160), 'os.chdir', 'os.chdir', (['which'], {}), '(which)\n', (9153, 9160), False, 'import os\n'), ((9178, 9202), 'copy.deepcopy', 'copy.deepcopy', (['model_obj'], {}), '(model_obj)\n', (9191, 9202), False, 'import copy\n'), ((9340, 9371), 'trempy.simulate.simulate.simulate', 'simulate', (["(which + '.trempy.ini')"], {}), "(which + '.trempy.ini')\n", (9348, 9371), False, 'from trempy.simulate.simulate import simulate\n'), ((9436, 9451), 'os.chdir', 'os.chdir', (['"""../"""'], {}), "('../')\n", (9444, 9451), False, 'import os\n'), ((9626, 9663), 'pandas.read_pickle', 'pd.read_pickle', (["(which + '.trempy.pkl')"], {}), "(which + '.trempy.pkl')\n", (9640, 9663), True, 'import pandas as pd\n'), ((2681, 2715), 'copy.deepcopy', 'copy.deepcopy', (['start_utility_paras'], {}), '(start_utility_paras)\n', (2694, 2715), False, 'import copy\n'), ((3155, 3266), 'trempy.shared.shared_auxiliary.get_optimal_compensations', 'get_optimal_compensations', ([], {'version': 'version', 'paras_obj': 'utility_cand', 'questions': 'questions'}), '(version=version, paras_obj=utility_cand,\n questions=questions, **version_specific)\n', (3180, 3266), False, 'from trempy.shared.shared_auxiliary import get_optimal_compensations\n'), ((3313, 3361), 'numpy.array', 'np.array', (['[m_optimal_cand[q] for q in questions]'], {}), '([m_optimal_cand[q] for q in questions])\n', (3321, 3361), True, 'import numpy as np\n'), ((3689, 3736), 'numpy.mean', 'np.mean', (['((np_stats[:, 0] - np_stats[:, 1]) ** 2)'], {}), '((np_stats[:, 0] - np_stats[:, 1]) ** 2)\n', (3696, 3736), True, 'import numpy as np\n'), ((8219, 8242), 'os.path.exists', 'os.path.exists', (['dirname'], {}), '(dirname)\n', (8233, 8242), False, 'import os\n'), ((8433, 8454), 'os.path.exists', 'os.path.exists', (['fname'], {}), '(fname)\n', (8447, 8454), False, 'import os\n'), ((8830, 8884), 'trempy.shared.shared_auxiliary.dist_class_attributes', 'dist_class_attributes', (['model_obj', '"""upper"""', '"""marginals"""'], {}), "(model_obj, 'upper', 'marginals')\n", (8851, 8884), False, 'from trempy.shared.shared_auxiliary import dist_class_attributes\n'), ((6663, 6687), 'copy.deepcopy', 'copy.deepcopy', (['paras_obj'], {}), '(paras_obj)\n', (6676, 6687), False, 'import copy\n'), ((6782, 6868), 'scipy.optimize.minimize', 'minimize', (['start_obj.evaluate', 'start_paras'], {'method': '"""L-BFGS-B"""', 'bounds': 'start_bounds'}), "(start_obj.evaluate, start_paras, method='L-BFGS-B', bounds=\n start_bounds)\n", (6790, 6868), False, 'from scipy.optimize import minimize\n'), ((8256, 8278), 'shutil.rmtree', 'shutil.rmtree', (['dirname'], {}), '(dirname)\n', (8269, 8278), False, 'import shutil\n'), ((8468, 8484), 'os.remove', 'os.remove', (['fname'], {}), '(fname)\n', (8477, 8484), False, 'import os\n'), ((7725, 7741), 'pandas.isnull', 'pd.isnull', (['value'], {}), '(value)\n', (7734, 7741), True, 'import pandas as pd\n'), ((12196, 12217), 'statsmodels.tools.eval_measures.rmse', 'get_rmse', (['*np_stats.T'], {}), '(*np_stats.T)\n', (12204, 12217), True, 'from statsmodels.tools.eval_measures import rmse as get_rmse\n'), ((12822, 12848), 'trempy.shared.shared_auxiliary.char_floats', 'char_floats', (['(m_obs - m_opt)'], {}), '(m_obs - m_opt)\n', (12833, 12848), False, 'from trempy.shared.shared_auxiliary import char_floats\n'), ((11233, 11251), 'pandas.isnull', 'pd.isnull', (['info[i]'], {}), '(info[i])\n', (11242, 11251), True, 'import pandas as pd\n'), ((12779, 12797), 'trempy.shared.shared_auxiliary.char_floats', 'char_floats', (['m_obs'], {}), '(m_obs)\n', (12790, 12797), False, 'from trempy.shared.shared_auxiliary import char_floats\n'), ((3641, 3659), 'numpy.isnan', 'np.isnan', (['np_stats'], {}), '(np_stats)\n', (3649, 3659), True, 'import numpy as np\n'), ((11945, 11963), 'numpy.isnan', 'np.isnan', (['np_stats'], {}), '(np_stats)\n', (11953, 11963), True, 'import numpy as np\n'), ((12758, 12776), 'trempy.shared.shared_auxiliary.char_floats', 'char_floats', (['m_opt'], {}), '(m_opt)\n', (12769, 12776), False, 'from trempy.shared.shared_auxiliary import char_floats\n')]
import pytest import numpy as np import pandas as pd from metaspace.image_processing import clip_hotspots, colocalization, colocalization_matrix IMG_A = np.array([[1, 1, 0, 0], [1, 1, 0, 0], [1, 1, 0, 0], [1, 1, 0, 0]]) IMG_B = np.array([[1, 1, 1, 1], [1, 1, 1, 1], [0, 0, 0, 0], [0, 0, 0, 0]]) IMG_C = np.array([[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 1, 1], [0, 0, 1, 1]]) COLOC_A_B = 0.5 def test_clip_hotspots(): # First 99 pixels are "effectively empty" (less than 1/256th of the max) # and shouldn't count towards the thresholds # Second half of the image is a gradient from 100 to 200, meaning the hotspot threshold # should be 199 and the last pixel should be clipped img = np.concatenate([np.ones(99) * 0.5, np.arange(100, 201)]).reshape(20, 10) clipped = clip_hotspots(img) assert img.shape == clipped.shape assert np.isclose(clipped.flat[:199], img.flat[:199]).all() assert clipped.flat[199] == 199 def test_colocalization(): assert np.isclose(colocalization(IMG_A, IMG_A), 1) assert np.isclose(colocalization(IMG_A, IMG_B), COLOC_A_B) assert np.isclose(colocalization(IMG_B, IMG_A), COLOC_A_B) assert np.isclose(colocalization(IMG_A, IMG_C), 0) def test_colocalization_matrix(): IMGS = [IMG_A, IMG_B, IMG_C] LABELS = ['a', 'b', 'c'] EXPECTED = [[1, COLOC_A_B, 0], [COLOC_A_B, 1, 0], [0, 0, 1]] mat = colocalization_matrix(IMGS) assert isinstance(mat, np.ndarray) assert np.isclose(mat, EXPECTED).all() df = colocalization_matrix(IMGS, labels=LABELS) expected_df = pd.DataFrame(EXPECTED, index=LABELS, columns=LABELS, dtype='d') pd.testing.assert_frame_equal(df, expected_df)
[ "pandas.DataFrame", "metaspace.image_processing.clip_hotspots", "pandas.testing.assert_frame_equal", "numpy.ones", "metaspace.image_processing.colocalization_matrix", "metaspace.image_processing.colocalization", "numpy.isclose", "numpy.array", "numpy.arange" ]
[((155, 221), 'numpy.array', 'np.array', (['[[1, 1, 0, 0], [1, 1, 0, 0], [1, 1, 0, 0], [1, 1, 0, 0]]'], {}), '([[1, 1, 0, 0], [1, 1, 0, 0], [1, 1, 0, 0], [1, 1, 0, 0]])\n', (163, 221), True, 'import numpy as np\n'), ((230, 296), 'numpy.array', 'np.array', (['[[1, 1, 1, 1], [1, 1, 1, 1], [0, 0, 0, 0], [0, 0, 0, 0]]'], {}), '([[1, 1, 1, 1], [1, 1, 1, 1], [0, 0, 0, 0], [0, 0, 0, 0]])\n', (238, 296), True, 'import numpy as np\n'), ((305, 371), 'numpy.array', 'np.array', (['[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 1, 1], [0, 0, 1, 1]]'], {}), '([[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 1, 1], [0, 0, 1, 1]])\n', (313, 371), True, 'import numpy as np\n'), ((788, 806), 'metaspace.image_processing.clip_hotspots', 'clip_hotspots', (['img'], {}), '(img)\n', (801, 806), False, 'from metaspace.image_processing import clip_hotspots, colocalization, colocalization_matrix\n'), ((1383, 1410), 'metaspace.image_processing.colocalization_matrix', 'colocalization_matrix', (['IMGS'], {}), '(IMGS)\n', (1404, 1410), False, 'from metaspace.image_processing import clip_hotspots, colocalization, colocalization_matrix\n'), ((1503, 1545), 'metaspace.image_processing.colocalization_matrix', 'colocalization_matrix', (['IMGS'], {'labels': 'LABELS'}), '(IMGS, labels=LABELS)\n', (1524, 1545), False, 'from metaspace.image_processing import clip_hotspots, colocalization, colocalization_matrix\n'), ((1564, 1627), 'pandas.DataFrame', 'pd.DataFrame', (['EXPECTED'], {'index': 'LABELS', 'columns': 'LABELS', 'dtype': '"""d"""'}), "(EXPECTED, index=LABELS, columns=LABELS, dtype='d')\n", (1576, 1627), True, 'import pandas as pd\n'), ((1632, 1678), 'pandas.testing.assert_frame_equal', 'pd.testing.assert_frame_equal', (['df', 'expected_df'], {}), '(df, expected_df)\n', (1661, 1678), True, 'import pandas as pd\n'), ((996, 1024), 'metaspace.image_processing.colocalization', 'colocalization', (['IMG_A', 'IMG_A'], {}), '(IMG_A, IMG_A)\n', (1010, 1024), False, 'from metaspace.image_processing import clip_hotspots, colocalization, colocalization_matrix\n'), ((1051, 1079), 'metaspace.image_processing.colocalization', 'colocalization', (['IMG_A', 'IMG_B'], {}), '(IMG_A, IMG_B)\n', (1065, 1079), False, 'from metaspace.image_processing import clip_hotspots, colocalization, colocalization_matrix\n'), ((1114, 1142), 'metaspace.image_processing.colocalization', 'colocalization', (['IMG_B', 'IMG_A'], {}), '(IMG_B, IMG_A)\n', (1128, 1142), False, 'from metaspace.image_processing import clip_hotspots, colocalization, colocalization_matrix\n'), ((1177, 1205), 'metaspace.image_processing.colocalization', 'colocalization', (['IMG_A', 'IMG_C'], {}), '(IMG_A, IMG_C)\n', (1191, 1205), False, 'from metaspace.image_processing import clip_hotspots, colocalization, colocalization_matrix\n'), ((856, 902), 'numpy.isclose', 'np.isclose', (['clipped.flat[:199]', 'img.flat[:199]'], {}), '(clipped.flat[:199], img.flat[:199])\n', (866, 902), True, 'import numpy as np\n'), ((1461, 1486), 'numpy.isclose', 'np.isclose', (['mat', 'EXPECTED'], {}), '(mat, EXPECTED)\n', (1471, 1486), True, 'import numpy as np\n'), ((736, 755), 'numpy.arange', 'np.arange', (['(100)', '(201)'], {}), '(100, 201)\n', (745, 755), True, 'import numpy as np\n'), ((717, 728), 'numpy.ones', 'np.ones', (['(99)'], {}), '(99)\n', (724, 728), True, 'import numpy as np\n')]
import cv2 from cv2 import aruco import pdb import pandas as pd import numpy as np from .corner_finder import CornerFinder from .aruco_corner import ArucoCorner from .aruco_loc import ArucoLoc class ArucoHelper: """ Helper class with static functions designed to help a user review or debug images with aruco data """ @staticmethod def load_corners(file_loc, id): """ Loads corner data that was saved as a csv previously, returns an ArucoCorner obj with imported data """ # import csv df = pd.read_csv(file_loc) # TODO: should I parse the file_loc for information like id and folder loc? # get numpy array data = df.to_numpy() # reformat to aruco-style corners array data_len = len(data) # can't include the frame number that you get from pandas corners = np.reshape(data[:, 1:9], (data_len, 4, 2)) # TODO: need to double check I have right order return ArucoCorner(id, corners) @staticmethod def load_poses(file_loc, id): """ Loads pose data that was saved as a csv previously, returns an ArucoLoc obj with imported data """ df = pd.read_csv(file_loc) # TODO: should I parse the file_loc for information like id and folder loc? # convert dataframe to numpy array, format is correct data = df.to_numpy() # reformat to aruco-style corners array data_len = len(data) # can't include the frame number that you get from pandas poses = data[:, 1:9] # TODO: need to double check I have right order return ArucoLoc(id, data) @staticmethod def show_image(file_loc, include_corners=False, marker_size=3): """ Show an image, can include the detected corners as red squares """ img = cv2.imread(file_loc, cv2.IMREAD_COLOR) if include_corners: ar_dict = aruco.getPredefinedDictionary(aruco.DICT_4X4_250) ar_params = aruco.DetectorParameters_create() cf = CornerFinder("") c_data = cf._analyze_single_image(file_loc, ar_dict, ar_params) for k in c_data.keys(): for cs in c_data[k]: x1 = cs[0]-marker_size y1 = cs[1]+marker_size x2 = cs[0]+marker_size y2 = cs[1]-marker_size # TODO: enable user to set color? cv2.rectangle(img, (int(x1), int(y1)), (int(x2), int(y2)), (0,0,255), -1) cv2.imshow(f"{file_loc}", img) cv2.waitKey(0) cv2.destroyAllWindows() @staticmethod def view_data_video(acode, include_corners=False): """ Shows image stream as a video. Useful for debugging. """ try: # get folder location of the aruco code folder_loc = acode.folder_loc except: raise Exception("ArucoCorner object does not have a folder location associated with it") pass
[ "cv2.aruco.getPredefinedDictionary", "cv2.aruco.DetectorParameters_create", "pandas.read_csv", "cv2.waitKey", "cv2.destroyAllWindows", "cv2.imread", "numpy.reshape", "cv2.imshow" ]
[((553, 574), 'pandas.read_csv', 'pd.read_csv', (['file_loc'], {}), '(file_loc)\n', (564, 574), True, 'import pandas as pd\n'), ((871, 913), 'numpy.reshape', 'np.reshape', (['data[:, 1:9]', '(data_len, 4, 2)'], {}), '(data[:, 1:9], (data_len, 4, 2))\n', (881, 913), True, 'import numpy as np\n'), ((1205, 1226), 'pandas.read_csv', 'pd.read_csv', (['file_loc'], {}), '(file_loc)\n', (1216, 1226), True, 'import pandas as pd\n'), ((1855, 1893), 'cv2.imread', 'cv2.imread', (['file_loc', 'cv2.IMREAD_COLOR'], {}), '(file_loc, cv2.IMREAD_COLOR)\n', (1865, 1893), False, 'import cv2\n'), ((2586, 2616), 'cv2.imshow', 'cv2.imshow', (['f"""{file_loc}"""', 'img'], {}), "(f'{file_loc}', img)\n", (2596, 2616), False, 'import cv2\n'), ((2625, 2639), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], {}), '(0)\n', (2636, 2639), False, 'import cv2\n'), ((2648, 2671), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (2669, 2671), False, 'import cv2\n'), ((1945, 1994), 'cv2.aruco.getPredefinedDictionary', 'aruco.getPredefinedDictionary', (['aruco.DICT_4X4_250'], {}), '(aruco.DICT_4X4_250)\n', (1974, 1994), False, 'from cv2 import aruco\n'), ((2019, 2052), 'cv2.aruco.DetectorParameters_create', 'aruco.DetectorParameters_create', ([], {}), '()\n', (2050, 2052), False, 'from cv2 import aruco\n')]
import logging from collections import defaultdict import dataclasses import numpy as np import pandas as pd from scipy import stats from statsmodels.stats.contingency_tables import Table2x2 from sklearn.cluster import DBSCAN import pomegranate as pm from .io import load_model_priors logger = logging.getLogger('yanocomp') N_COMPONENTS = 2 def pca_comp1(X, standardise=True): '''Quick principal components with 1 comp''' if standardise: mu = X.mean(axis=0) sig = np.sqrt(((X - mu) ** 2.0).mean(0)) X = (X - mu) / sig u, s, v = np.linalg.svd(X, full_matrices=False) vecs = v.T i1 = np.argmax(s ** 2.0) vecs = vecs[:, i1, np.newaxis] comp1 = X.dot(vecs) return comp1.ravel() def _ks_d(data1, data2, pooled): n1 = data1.shape[0] n2 = data2.shape[0] data1 = np.sort(data1) data2 = np.sort(data2) cdf1 = np.searchsorted(data1, pooled, side='right')/(1.0 * n1) cdf2 = (np.searchsorted(data2, pooled, side='right'))/(1.0 * n2) d = np.max(np.absolute(cdf1 - cdf2)) en = np.sqrt(n1 * n2 / float(n1 + n2)) return d, en def ks_2samp(data1, data2, pooled): d, en = _ks_d(data1, data2, pooled) prob = stats.kstwobign.sf((en + 0.12 + 0.11 / en) * d) return d, prob def subsample(arr, max_size, random_state): '''If arr is longer than max_size, subsamples without replacement''' if len(arr) <= max_size: return arr else: idx = np.arange(len(arr)) idx = random_state.choice(idx, size=max_size, replace=False) return arr[idx] def pca_kstest(cntrl_data, treat_data, max_size, random_state): ''' Transform multivariate data to univariate using PCA and perform Kolmogorov-Smirnov test ''' cntrl_data = subsample(cntrl_data, max_size, random_state) treat_data = subsample(treat_data, max_size, random_state) n_cntrl = len(cntrl_data) pooled = np.concatenate([cntrl_data, treat_data]) comps = pca_comp1(pooled) ks, p_val = ks_2samp(comps[:n_cntrl], comps[n_cntrl:], comps) return ks, p_val def median_absolute_deviation(arr): '''Returns the MAD of an array''' return np.median(np.abs(arr - np.median(arr))) def kmeans_init_clusters(X, detect_outliers='mad', init_method='kmeans++', max_iter=100, stop_threshold=0.5, outlier_factor=0.5, dbscan_eps=5, dbscan_min_samples='auto'): ''' Get predictions for initialising GMM using KMeans. Outliers are detected by calculating the MAD of the distances to the nearest centroid, and then labelling all values with a dist of > outlier_factor * MAD as outliers. ''' # if using dbscan to detect outliers, we can do this first if detect_outliers == 'dbscan': if dbscan_min_samples == 'auto': dbscan_min_samples = 0.25 * len(X) dbscan = DBSCAN( eps=dbscan_eps, min_samples=dbscan_min_samples, metric='euclidean' ) outlier_mask = dbscan.fit_predict(X) == -1 if sum(outlier_mask) == len(outlier_mask): return np.full(len(outlier_mask), N_COMPONENTS, dtype=int) else: # ignore outliers in kmeans fit - should help a bit X_fit = X[~outlier_mask] else: X_fit = X kmeans = pm.Kmeans( N_COMPONENTS, init=init_method, n_init=1 if init_method == 'first-k' else 3 ) kmeans.fit(X_fit, max_iterations=max_iter, stop_threshold=stop_threshold) centroid_dists = kmeans.distance(X) init_pred = np.argmin(centroid_dists, axis=1) if detect_outliers is not None: if detect_outliers == 'mad': dists = np.min(centroid_dists, axis=1) mad = median_absolute_deviation(dists) outlier_mask = dists > outlier_factor * mad # label outliers as new cluster init_pred[outlier_mask] = N_COMPONENTS return init_pred def initialise_gmms(X, covariance='full', detect_outliers=True, init_method='kmeans++', max_iter=100, pseudocount=0.5, outlier_factor=0.5, dbscan_eps=5, dbscan_min_samples='auto'): ''' Uses K-means to initialise 2-component GMM. Optionally adds a uniform dist to account for poorly aligned reads ''' samp_sizes = [len(samp) for samp in X] X_pooled = np.concatenate(X) n_dim = X_pooled.shape[1] init_pred = kmeans_init_clusters( X_pooled, detect_outliers=detect_outliers, init_method=init_method, max_iter=max_iter, outlier_factor=outlier_factor, dbscan_eps=dbscan_eps, dbscan_min_samples=dbscan_min_samples, ) if covariance == 'full': dists = [ pm.MultivariateGaussianDistribution.from_samples(X_pooled[init_pred == i]) for i in range(N_COMPONENTS) ] elif covariance == 'diag': dists = [] for i in range(N_COMPONENTS): X_i = X_pooled[init_pred == i] if len(X_i) == 0: dists.append(pm.IndependentComponentsDistribution([ pm.NormalDistribution(0, 1) for j in range(n_dim) ])) else: dists.append(pm.IndependentComponentsDistribution([ pm.NormalDistribution(X_i[:, j].mean(), X_i[:, j].std()) for j in range(n_dim) ])) else: raise ValueError('Only full and diag covariances are supported') ncomp = N_COMPONENTS + int(detect_outliers is not None) per_samp_preds = np.array_split(init_pred, np.cumsum(samp_sizes)[:-1]) weights = [ (np.bincount(pred, minlength=ncomp) + pseudocount) / ( len(pred) + pseudocount * ncomp) for pred in per_samp_preds ] if detect_outliers is not None: outliers = X_pooled[init_pred == N_COMPONENTS] if len(outliers) == 0: # set params using all data outliers = X_pooled uniform_dist = pm.IndependentComponentsDistribution([ pm.UniformDistribution(col.min(), col.max()) for col in outliers.transpose() ]) dists.append(uniform_dist) gmms = [ pm.GeneralMixtureModel(dists, w) for w in weights ] return gmms, dists def em(X, gmms, dists, max_iterations=1e3, stop_threshold=0.1, inertia=0.01, lr_decay=1e-3, pseudocount=0.5): '''Perform expectation maximisation''' samp_sizes = [len(samp) for samp in X] initial_log_probability_sum = -np.inf iteration, improvement = 0, np.inf # perform EM while improvement > stop_threshold and iteration < max_iterations + 1: step_size = 1 - ((1 - inertia) * (2 + iteration) ** -lr_decay) if iteration: for d in dists: d.from_summaries(step_size) for gmm in gmms: if gmm.summaries.sum(): summaries = gmm.summaries + pseudocount summaries /= summaries.sum() gmm.weights[:] = np.log(summaries) gmm.summaries[:] = 0 log_probability_sum = 0 for gmm, samp in zip(gmms, X): log_probability_sum += gmm.summarize(samp) if iteration == 0: initial_log_probability_sum = log_probability_sum else: improvement = log_probability_sum - last_log_probability_sum iteration += 1 last_log_probability_sum = log_probability_sum per_samp_weights = np.array([np.exp(gmm.weights) for gmm in gmms]) return gmms, dists def fit_multisamp_gmm(X, covariance='full', detect_outliers='mad', outlier_factor=0.5, dbscan_eps=5, dbscan_min_samples='auto',): ''' Fit a gaussian mixture model to multiple samples. Each sample has its own GMM with its own weights but shares distributions with others. Returns a dists and weights both for combined data and for each sample ''' try: with np.errstate(divide='ignore'): gmms, dists = initialise_gmms( X, covariance, detect_outliers, outlier_factor=outlier_factor, dbscan_eps=dbscan_eps, dbscan_min_samples=dbscan_min_samples, ) with np.errstate(invalid='ignore', over='ignore'): gmms, dists = em(X, gmms, dists) except np.core._exceptions.UFuncTypeError: # sometimes small sample sizes cause fitting errors # actual error is caused by casting error for complex numbers # in pomegranate - see https://github.com/jmschrei/pomegranate/issues/633 raise np.linalg.LinAlgError samp_sizes = [len(samp) for samp in X] per_samp_weights = np.array([np.exp(gmm.weights) for gmm in gmms]) combined_weights = np.average(per_samp_weights, axis=0, weights=samp_sizes) return dists, combined_weights, per_samp_weights def fit_gmm(cntrl, treat, covariance='full', detect_outliers='mad', outlier_factor=0.5, max_fit_depth=1000, dbscan_eps=5, dbscan_min_samples='auto', random_state=None): ''' Fits a multivariate, two-gaussian GMM to data and measures KL divergence of the resulting distributions. ''' n_cntrl = len(cntrl) samp_sizes = np.array([len(samp) for samp in cntrl + treat]) pooled = [ subsample(samp, max_fit_depth, random_state) for samp in cntrl + treat ] dists, weights, per_samp_weights = fit_multisamp_gmm( pooled, covariance=covariance, detect_outliers=detect_outliers, outlier_factor=outlier_factor, dbscan_eps=dbscan_eps, dbscan_min_samples=dbscan_min_samples, ) if covariance == 'full': model_params = ( dists[0].mu, dists[1].mu, np.sqrt(np.diagonal(dists[0].cov)), np.sqrt(np.diagonal(dists[1].cov)) ) elif covariance == 'diag': mu_1, std_1 = zip( *[d.parameters for d in dists[0]] ) mu_2, std_2 = zip( *[d.parameters for d in dists[1]] ) model_params = [ np.array(mu_1), np.array(mu_2), np.array(std_1), np.array(std_2) ] else: raise ValueError('Only full and diag covariances are supported') # use weights to estimate per-sample mod rates preds = np.round(per_samp_weights * samp_sizes[:, np.newaxis]) cntrl_preds, treat_preds = preds[:n_cntrl], preds[n_cntrl:] gmm = pm.GeneralMixtureModel(dists, weights) return gmm, cntrl_preds, treat_preds, model_params def two_cond_g_test(counts): ''' G test, catch errors caused by rows/columns with all zeros ''' try: g_stat, p_val, *_ = stats.chi2_contingency( counts, lambda_='log-likelihood' ) return g_stat, p_val except ValueError: # one cond is empty return 0.0, 1.0 def gmm_g_test(cntrl_preds, treat_preds, p_val_threshold=0.05): ''' Perform G tests for differential modification and within-condition homogeneity ''' with np.errstate(invalid='raise'): try: het_g, p_val = two_cond_g_test([ cntrl_preds[:, :2].sum(0), treat_preds[:, :2].sum(0) ]) except FloatingPointError: # all classified as outliers! het_g = np.nan p_val = 1 if p_val < p_val_threshold: cntrl_hom_g, _, = two_cond_g_test(cntrl_preds) treat_hom_g, _, = two_cond_g_test(treat_preds) hom_g = cntrl_hom_g + treat_hom_g if hom_g >= het_g: p_val = 1 else: hom_g = np.nan return het_g, hom_g, p_val def calculate_fractional_stats(cntrl_preds, treat_preds, pseudocount=0.5, ci=95): ''' Returns the relative modification rates (ignoring outliers) for treat and cntrl samples. Also calculates log ratio of mod:unmod reads. ''' cntrl_pred = cntrl_preds.sum(0) treat_pred = treat_preds.sum(0) with np.errstate(invalid='ignore'): cntrl_frac_upper = cntrl_pred[1] / cntrl_pred[:N_COMPONENTS].sum() treat_frac_upper = treat_pred[1] / treat_pred[:N_COMPONENTS].sum() ct = Table2x2([cntrl_pred[:N_COMPONENTS], treat_pred[:N_COMPONENTS]], shift_zeros=True) log_odds = ct.log_oddsratio log_odds_ci = ct.log_oddsratio_confint(alpha=1 - ci / 100) return cntrl_frac_upper, treat_frac_upper, log_odds, *log_odds_ci def format_sm_preds(sm_preds, sm_outlier, events): '''Create a json serialisable dict of single molecule predictions''' reps = events.index.get_level_values('replicate').tolist() read_ids = events.index.get_level_values('read_idx').tolist() events = events.values.tolist() sm_preds = sm_preds.tolist() sm_outlier = sm_outlier.tolist() sm_preds_dict = {} for r_id, rep, ev, p, o in zip(read_ids, reps, events, sm_preds, sm_outlier): try: sm_preds_dict[rep]['read_ids'].append(r_id) except KeyError: sm_preds_dict[rep] = { 'read_ids': [r_id,], 'events': [], 'preds': [], 'outlier_preds': [], } sm_preds_dict[rep]['events'].append(ev) sm_preds_dict[rep]['preds'].append(p) sm_preds_dict[rep]['outlier_preds'].append(o) return sm_preds_dict def format_model(gmm): '''Create a json serialisable dict of GMM parameters''' try: model_json = { 'unmod': { 'mu': gmm.distributions[0].mu.tolist(), 'cov': gmm.distributions[0].cov.tolist(), }, 'mod': { 'mu': gmm.distributions[1].mu.tolist(), 'cov': gmm.distributions[1].cov.tolist(), }, } except AttributeError: # model is IndependentComponentsDistribution (diagonal covariance) mu_1, std_1 = zip( *[d.parameters for d in gmm.distributions[0]] ) cov_1 = np.diag(std_1 ** 2) mu_2, std_2 = zip( *[d.parameters for d in gmm.distributions[1]] ) cov_2 = np.diag(std_2 ** 2) model_json = { 'unmod': { 'mu': mu_1, 'cov': cov_1, }, 'mod': { 'mu': mu_2, 'cov': cov_2, }, } if len(gmm.distributions) == (N_COMPONENTS + 1): outlier = gmm.distributions[2] model_json['outlier'] = { 'bounds': [u.parameters for u in outlier.distributions] } model_json['weights'] = np.exp(gmm.weights).tolist() return model_json @dataclasses.dataclass class GMMTestResults: '''Class for handling results of positional_stats''' kmer: str kmers: np.ndarray centre: int log_odds: float = np.nan log_odds_lower_ci: float = np.nan log_odds_upper_ci: float = np.nan p_val: float = 1. fdr: float = 1. cntrl_frac_mod: float = np.nan treat_frac_mod: float = np.nan g_stat: float = np.nan hom_g_stat: float = np.nan dist1_means: np.ndarray = None dist1_stds: np.ndarray = None dist2_means: np.ndarray = None dist2_stds: np.ndarray = None ks_stat: float = np.nan def position_stats(cntrl, treat, kmers, opts, random_state=None): ''' Fits the GMM, estimates mod rates/changes, and performs G test ''' window_size = len(kmers) centre = window_size // 2 kmer = kmers[centre] r = GMMTestResults(kmer=kmer, kmers=kmers, centre=centre) # first test that there is actually some difference in cntrl/treat r.ks_stat, ks_p_val = pca_kstest( cntrl.values, treat.values, max_size=opts.max_fit_depth, random_state=random_state, ) if not opts.gmm: # no modelling r.p_val = ks_p_val return True, r, None # if there is we can perform the GMM fit and subsequent G test if r.ks_stat >= opts.min_ks and ks_p_val < opts.fdr_threshold: cntrl_fit_data = [c.values for _, c in cntrl.groupby('replicate', sort=False)] treat_fit_data = [t.values for _, t in treat.groupby('replicate', sort=False)] try: gmm, cntrl_preds, treat_preds, model_params = fit_gmm( cntrl_fit_data, treat_fit_data, covariance=opts.covariance_type, detect_outliers=opts.outlier_method if opts.add_uniform else None, outlier_factor=opts.outlier_factor, dbscan_eps=opts.dbscan_eps, max_fit_depth=opts.max_fit_depth, random_state=random_state, ) except np.linalg.LinAlgError: return False, r, None r.dist1_means, r.dist2_means, r.dist1_stds, r.dist2_stds = model_params r.g_stat, r.hom_g_stat, r.p_val = gmm_g_test( cntrl_preds, treat_preds, p_val_threshold=opts.fdr_threshold ) frac_stats = calculate_fractional_stats(cntrl_preds, treat_preds) ( r.cntrl_frac_mod, r.treat_frac_mod, r.log_odds, r.log_odds_lower_ci, r.log_odds_upper_ci ) = frac_stats if r.p_val < opts.fdr_threshold and opts.generate_sm_preds: cntrl_prob = gmm.predict_proba(np.concatenate(cntrl_fit_data))[:, 1:].T treat_prob = gmm.predict_proba(np.concatenate(treat_fit_data))[:, 1:].T if opts.add_uniform: cntrl_prob, cntrl_outlier = cntrl_prob treat_prob, treat_outlier = treat_prob else: cntrl_outlier = np.zeros_like(cntrl_prob) treat_outlier = np.zeros_like(treat_prob) sm_preds = { 'kmers': kmers.tolist(), 'model': format_model(gmm), 'cntrl': format_sm_preds(cntrl_prob, cntrl_outlier, cntrl), 'treat': format_sm_preds(treat_prob, treat_outlier, treat), } else: sm_preds = None return True, r, sm_preds else: return False, r, None def calculate_kmer_shift_directions(results, expected_model): results = results[['kmers', 'dist1_means', 'dist2_means']] kmer_lower_dists = defaultdict(list) kmer_upper_dists = defaultdict(list) for _, kmers, dist1_fit_means, dist2_fit_means in results.itertuples(): for k, lm, um in zip(kmers, dist1_fit_means, dist2_fit_means): if lm > um: lm, um = um, lm exp = expected_model.loc['level_mean', k] kmer_lower_dists[k].append(abs(lm - exp)) kmer_upper_dists[k].append(abs(um - exp)) kmer_shift_dirs = {} for k in kmer_lower_dists: if np.median(kmer_upper_dists[k]) > np.median(kmer_lower_dists[k]): kmer_shift_dirs[k] = 1 # upper is more likely modified else: kmer_shift_dirs[k] = 0 # lower is more likely modified return kmer_shift_dirs def dist1_is_modified(kmers, dist1_means, dist2_means, kmer_shift_dirs): ''' Predict whether dist1 or dist2 is modified using global shift directions for each kmer in kmers and the separation between dist1 and dist2 ''' diff = dist1_means - dist2_means dist1_score = 0 dist2_score = 0 for k, d in zip(kmers, diff): upper_is_mod = kmer_shift_dirs[k] d2_is_upper = d < 0 if upper_is_mod ^ d2_is_upper: dist1_score += abs(d) else: dist2_score += abs(d) # larger score is modified return dist1_score > dist2_score def assign_modified_distribution(results, sm_preds, model=load_model_priors(), sample_size=1000): ''' Given all significant kmer results, predict for each kmer which distribution is most likely to be modified using an existing model of nanopore current. ''' # corner case with no sig results if not len(results): return results, sm_preds kmer_shift_dirs = calculate_kmer_shift_directions(results, model) res_assigned = [] for i in results.index: kmers, dist1_means, dist2_means = results.loc[i, ['kmers', 'dist1_means', 'dist2_means']] if dist1_is_modified(kmers, dist1_means, dist2_means, kmer_shift_dirs): # higher is unmod, flip the values results.loc[i, 'cntrl_frac_mod'] = 1 - results.loc[i, 'cntrl_frac_mod'] results.loc[i, 'treat_frac_mod'] = 1 - results.loc[i, 'treat_frac_mod'] results.loc[i, 'log_odds'] = np.negative(results.loc[i, 'log_odds']) results.loc[i, ['log_odds_lower_ci', 'log_odds_upper_ci']] = np.negative( results.loc[i, ['log_odds_upper_ci', 'log_odds_lower_ci']] ) results.loc[i, ['dist1_means','dist2_means']] = ( results.loc[i, ['dist2_means','dist1_means']].values ) results.loc[i, ['dist1_stds','dist2_stds']] = ( results.loc[i, ['dist2_stds','dist1_stds']].values ) # also need to reverse the sm_preds: gene_id, pos = results.loc[i, ['gene_id', 'pos']] try: pos_sm_preds = sm_preds[gene_id][pos] except KeyError: continue m = pos_sm_preds['model'] m['unmod'], m['mod'] = m['mod'], m['unmod'] for cond in ['cntrl', 'treat']: for rep_sm_preds in pos_sm_preds[cond].values(): rep_sm_preds['preds'] = [ 1 - (p + o) for p, o in zip(rep_sm_preds['preds'], rep_sm_preds['outlier_preds']) ] return results, sm_preds
[ "numpy.absolute", "numpy.argmax", "numpy.negative", "numpy.argmin", "collections.defaultdict", "numpy.linalg.svd", "numpy.exp", "numpy.diag", "numpy.round", "sklearn.cluster.DBSCAN", "pomegranate.MultivariateGaussianDistribution.from_samples", "numpy.zeros_like", "scipy.stats.kstwobign.sf", ...
[((298, 327), 'logging.getLogger', 'logging.getLogger', (['"""yanocomp"""'], {}), "('yanocomp')\n", (315, 327), False, 'import logging\n'), ((571, 608), 'numpy.linalg.svd', 'np.linalg.svd', (['X'], {'full_matrices': '(False)'}), '(X, full_matrices=False)\n', (584, 608), True, 'import numpy as np\n'), ((633, 652), 'numpy.argmax', 'np.argmax', (['(s ** 2.0)'], {}), '(s ** 2.0)\n', (642, 652), True, 'import numpy as np\n'), ((832, 846), 'numpy.sort', 'np.sort', (['data1'], {}), '(data1)\n', (839, 846), True, 'import numpy as np\n'), ((859, 873), 'numpy.sort', 'np.sort', (['data2'], {}), '(data2)\n', (866, 873), True, 'import numpy as np\n'), ((1200, 1247), 'scipy.stats.kstwobign.sf', 'stats.kstwobign.sf', (['((en + 0.12 + 0.11 / en) * d)'], {}), '((en + 0.12 + 0.11 / en) * d)\n', (1218, 1247), False, 'from scipy import stats\n'), ((1918, 1958), 'numpy.concatenate', 'np.concatenate', (['[cntrl_data, treat_data]'], {}), '([cntrl_data, treat_data])\n', (1932, 1958), True, 'import numpy as np\n'), ((3353, 3443), 'pomegranate.Kmeans', 'pm.Kmeans', (['N_COMPONENTS'], {'init': 'init_method', 'n_init': "(1 if init_method == 'first-k' else 3)"}), "(N_COMPONENTS, init=init_method, n_init=1 if init_method ==\n 'first-k' else 3)\n", (3362, 3443), True, 'import pomegranate as pm\n'), ((3604, 3637), 'numpy.argmin', 'np.argmin', (['centroid_dists'], {'axis': '(1)'}), '(centroid_dists, axis=1)\n', (3613, 3637), True, 'import numpy as np\n'), ((4442, 4459), 'numpy.concatenate', 'np.concatenate', (['X'], {}), '(X)\n', (4456, 4459), True, 'import numpy as np\n'), ((8886, 8942), 'numpy.average', 'np.average', (['per_samp_weights'], {'axis': '(0)', 'weights': 'samp_sizes'}), '(per_samp_weights, axis=0, weights=samp_sizes)\n', (8896, 8942), True, 'import numpy as np\n'), ((10425, 10479), 'numpy.round', 'np.round', (['(per_samp_weights * samp_sizes[:, np.newaxis])'], {}), '(per_samp_weights * samp_sizes[:, np.newaxis])\n', (10433, 10479), True, 'import numpy as np\n'), ((10554, 10592), 'pomegranate.GeneralMixtureModel', 'pm.GeneralMixtureModel', (['dists', 'weights'], {}), '(dists, weights)\n', (10576, 10592), True, 'import pomegranate as pm\n'), ((12266, 12352), 'statsmodels.stats.contingency_tables.Table2x2', 'Table2x2', (['[cntrl_pred[:N_COMPONENTS], treat_pred[:N_COMPONENTS]]'], {'shift_zeros': '(True)'}), '([cntrl_pred[:N_COMPONENTS], treat_pred[:N_COMPONENTS]],\n shift_zeros=True)\n', (12274, 12352), False, 'from statsmodels.stats.contingency_tables import Table2x2\n'), ((18282, 18299), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (18293, 18299), False, 'from collections import defaultdict\n'), ((18323, 18340), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (18334, 18340), False, 'from collections import defaultdict\n'), ((885, 929), 'numpy.searchsorted', 'np.searchsorted', (['data1', 'pooled'], {'side': '"""right"""'}), "(data1, pooled, side='right')\n", (900, 929), True, 'import numpy as np\n'), ((953, 997), 'numpy.searchsorted', 'np.searchsorted', (['data2', 'pooled'], {'side': '"""right"""'}), "(data2, pooled, side='right')\n", (968, 997), True, 'import numpy as np\n'), ((1025, 1049), 'numpy.absolute', 'np.absolute', (['(cdf1 - cdf2)'], {}), '(cdf1 - cdf2)\n', (1036, 1049), True, 'import numpy as np\n'), ((2902, 2976), 'sklearn.cluster.DBSCAN', 'DBSCAN', ([], {'eps': 'dbscan_eps', 'min_samples': 'dbscan_min_samples', 'metric': '"""euclidean"""'}), "(eps=dbscan_eps, min_samples=dbscan_min_samples, metric='euclidean')\n", (2908, 2976), False, 'from sklearn.cluster import DBSCAN\n'), ((6314, 6346), 'pomegranate.GeneralMixtureModel', 'pm.GeneralMixtureModel', (['dists', 'w'], {}), '(dists, w)\n', (6336, 6346), True, 'import pomegranate as pm\n'), ((10795, 10851), 'scipy.stats.chi2_contingency', 'stats.chi2_contingency', (['counts'], {'lambda_': '"""log-likelihood"""'}), "(counts, lambda_='log-likelihood')\n", (10817, 10851), False, 'from scipy import stats\n'), ((11156, 11184), 'numpy.errstate', 'np.errstate', ([], {'invalid': '"""raise"""'}), "(invalid='raise')\n", (11167, 11184), True, 'import numpy as np\n'), ((12075, 12104), 'numpy.errstate', 'np.errstate', ([], {'invalid': '"""ignore"""'}), "(invalid='ignore')\n", (12086, 12104), True, 'import numpy as np\n'), ((3731, 3761), 'numpy.min', 'np.min', (['centroid_dists'], {'axis': '(1)'}), '(centroid_dists, axis=1)\n', (3737, 3761), True, 'import numpy as np\n'), ((4815, 4889), 'pomegranate.MultivariateGaussianDistribution.from_samples', 'pm.MultivariateGaussianDistribution.from_samples', (['X_pooled[init_pred == i]'], {}), '(X_pooled[init_pred == i])\n', (4863, 4889), True, 'import pomegranate as pm\n'), ((5696, 5717), 'numpy.cumsum', 'np.cumsum', (['samp_sizes'], {}), '(samp_sizes)\n', (5705, 5717), True, 'import numpy as np\n'), ((8103, 8131), 'numpy.errstate', 'np.errstate', ([], {'divide': '"""ignore"""'}), "(divide='ignore')\n", (8114, 8131), True, 'import numpy as np\n'), ((8361, 8405), 'numpy.errstate', 'np.errstate', ([], {'invalid': '"""ignore"""', 'over': '"""ignore"""'}), "(invalid='ignore', over='ignore')\n", (8372, 8405), True, 'import numpy as np\n'), ((8825, 8844), 'numpy.exp', 'np.exp', (['gmm.weights'], {}), '(gmm.weights)\n', (8831, 8844), True, 'import numpy as np\n'), ((14071, 14090), 'numpy.diag', 'np.diag', (['(std_1 ** 2)'], {}), '(std_1 ** 2)\n', (14078, 14090), True, 'import numpy as np\n'), ((14202, 14221), 'numpy.diag', 'np.diag', (['(std_2 ** 2)'], {}), '(std_2 ** 2)\n', (14209, 14221), True, 'import numpy as np\n'), ((14646, 14665), 'numpy.exp', 'np.exp', (['gmm.weights'], {}), '(gmm.weights)\n', (14652, 14665), True, 'import numpy as np\n'), ((18774, 18804), 'numpy.median', 'np.median', (['kmer_upper_dists[k]'], {}), '(kmer_upper_dists[k])\n', (18783, 18804), True, 'import numpy as np\n'), ((18807, 18837), 'numpy.median', 'np.median', (['kmer_lower_dists[k]'], {}), '(kmer_lower_dists[k])\n', (18816, 18837), True, 'import numpy as np\n'), ((20623, 20662), 'numpy.negative', 'np.negative', (["results.loc[i, 'log_odds']"], {}), "(results.loc[i, 'log_odds'])\n", (20634, 20662), True, 'import numpy as np\n'), ((20736, 20807), 'numpy.negative', 'np.negative', (["results.loc[i, ['log_odds_upper_ci', 'log_odds_lower_ci']]"], {}), "(results.loc[i, ['log_odds_upper_ci', 'log_odds_lower_ci']])\n", (20747, 20807), True, 'import numpy as np\n'), ((2186, 2200), 'numpy.median', 'np.median', (['arr'], {}), '(arr)\n', (2195, 2200), True, 'import numpy as np\n'), ((5750, 5784), 'numpy.bincount', 'np.bincount', (['pred'], {'minlength': 'ncomp'}), '(pred, minlength=ncomp)\n', (5761, 5784), True, 'import numpy as np\n'), ((7630, 7649), 'numpy.exp', 'np.exp', (['gmm.weights'], {}), '(gmm.weights)\n', (7636, 7649), True, 'import numpy as np\n'), ((9880, 9905), 'numpy.diagonal', 'np.diagonal', (['dists[0].cov'], {}), '(dists[0].cov)\n', (9891, 9905), True, 'import numpy as np\n'), ((9916, 9941), 'numpy.diagonal', 'np.diagonal', (['dists[1].cov'], {}), '(dists[1].cov)\n', (9927, 9941), True, 'import numpy as np\n'), ((10187, 10201), 'numpy.array', 'np.array', (['mu_1'], {}), '(mu_1)\n', (10195, 10201), True, 'import numpy as np\n'), ((10203, 10217), 'numpy.array', 'np.array', (['mu_2'], {}), '(mu_2)\n', (10211, 10217), True, 'import numpy as np\n'), ((10231, 10246), 'numpy.array', 'np.array', (['std_1'], {}), '(std_1)\n', (10239, 10246), True, 'import numpy as np\n'), ((10248, 10263), 'numpy.array', 'np.array', (['std_2'], {}), '(std_2)\n', (10256, 10263), True, 'import numpy as np\n'), ((17657, 17682), 'numpy.zeros_like', 'np.zeros_like', (['cntrl_prob'], {}), '(cntrl_prob)\n', (17670, 17682), True, 'import numpy as np\n'), ((17715, 17740), 'numpy.zeros_like', 'np.zeros_like', (['treat_prob'], {}), '(treat_prob)\n', (17728, 17740), True, 'import numpy as np\n'), ((7151, 7168), 'numpy.log', 'np.log', (['summaries'], {}), '(summaries)\n', (7157, 7168), True, 'import numpy as np\n'), ((17339, 17369), 'numpy.concatenate', 'np.concatenate', (['cntrl_fit_data'], {}), '(cntrl_fit_data)\n', (17353, 17369), True, 'import numpy as np\n'), ((17423, 17453), 'numpy.concatenate', 'np.concatenate', (['treat_fit_data'], {}), '(treat_fit_data)\n', (17437, 17453), True, 'import numpy as np\n'), ((5190, 5217), 'pomegranate.NormalDistribution', 'pm.NormalDistribution', (['(0)', '(1)'], {}), '(0, 1)\n', (5211, 5217), True, 'import pomegranate as pm\n')]
# -*- coding: utf-8 -*- """ DEPRECATED """ from __future__ import division, print_function import numpy as np from theano import gof import theano.tensor as tt __all__ = ["tensordotDOp"] class tensordotDOp(tt.Op): def __init__(self, func): self.func = func self._grad_op = tensordotDGradientOp(self) def make_node(self, *inputs): inputs = [tt.as_tensor_variable(i) for i in inputs] outputs = [tt.TensorType(inputs[0].dtype, (False, False))()] return gof.Apply(self, inputs, outputs) def infer_shape(self, node, shapes): return [[shapes[1][0], shapes[0][-1]]] def R_op(self, inputs, eval_points): if eval_points[0] is None: return eval_points return self.grad(inputs, eval_points) def perform(self, node, inputs, outputs): outputs[0][0] = self.func(*inputs) def grad(self, inputs, gradients): return self._grad_op(*(inputs + gradients)) class tensordotDGradientOp(tt.Op): def __init__(self, base_op): self.base_op = base_op def make_node(self, *inputs): inputs = [tt.as_tensor_variable(i) for i in inputs] outputs = [i.type() for i in inputs[:-1]] return gof.Apply(self, inputs, outputs) def infer_shape(self, node, shapes): return shapes[:-1] def perform(self, node, inputs, outputs): bM, bwta = self.base_op.func(*inputs) outputs[0][0] = np.reshape(bM, np.shape(inputs[0])) outputs[1][0] = np.reshape(bwta, np.shape(inputs[1]))
[ "theano.tensor.as_tensor_variable", "numpy.shape", "theano.gof.Apply", "theano.tensor.TensorType" ]
[((505, 537), 'theano.gof.Apply', 'gof.Apply', (['self', 'inputs', 'outputs'], {}), '(self, inputs, outputs)\n', (514, 537), False, 'from theano import gof\n'), ((1224, 1256), 'theano.gof.Apply', 'gof.Apply', (['self', 'inputs', 'outputs'], {}), '(self, inputs, outputs)\n', (1233, 1256), False, 'from theano import gof\n'), ((379, 403), 'theano.tensor.as_tensor_variable', 'tt.as_tensor_variable', (['i'], {}), '(i)\n', (400, 403), True, 'import theano.tensor as tt\n'), ((1117, 1141), 'theano.tensor.as_tensor_variable', 'tt.as_tensor_variable', (['i'], {}), '(i)\n', (1138, 1141), True, 'import theano.tensor as tt\n'), ((1458, 1477), 'numpy.shape', 'np.shape', (['inputs[0]'], {}), '(inputs[0])\n', (1466, 1477), True, 'import numpy as np\n'), ((1520, 1539), 'numpy.shape', 'np.shape', (['inputs[1]'], {}), '(inputs[1])\n', (1528, 1539), True, 'import numpy as np\n'), ((440, 486), 'theano.tensor.TensorType', 'tt.TensorType', (['inputs[0].dtype', '(False, False)'], {}), '(inputs[0].dtype, (False, False))\n', (453, 486), True, 'import theano.tensor as tt\n')]
import numpy as np from sys import stdout from sklearn.metrics import pairwise_kernels def MMD2u(K, m, n): """The MMD^2_u unbiased statistic. """ Kx = K[:m, :m] Ky = K[m:, m:] Kxy = K[:m, m:] return 1.0 / (m * (m - 1.0)) * (Kx.sum() - Kx.diagonal().sum()) + \ 1.0 / (n * (n - 1.0)) * (Ky.sum() - Ky.diagonal().sum()) - \ 2.0 / (m * n) * Kxy.sum() def compute_null_distribution(K, m, n, iterations=10000, verbose=False, random_state=None, marker_interval=1000): """Compute the bootstrap null-distribution of MMD2u. """ if type(random_state) == type(np.random.RandomState()): rng = random_state else: rng = np.random.RandomState(random_state) mmd2u_null = np.zeros(iterations) for i in range(iterations): if verbose and (i % marker_interval) == 0: print(i), stdout.flush() idx = rng.permutation(m+n) K_i = K[idx, idx[:, None]] mmd2u_null[i] = MMD2u(K_i, m, n) if verbose: print("") return mmd2u_null def compute_null_distribution_given_permutations(K, m, n, permutation, iterations=None): """Compute the bootstrap null-distribution of MMD2u given predefined permutations. Note:: verbosity is removed to improve speed. """ if iterations is None: iterations = len(permutation) mmd2u_null = np.zeros(iterations) for i in range(iterations): idx = permutation[i] K_i = K[idx, idx[:, None]] mmd2u_null[i] = MMD2u(K_i, m, n) return mmd2u_null def kernel_two_sample_test(X, Y, kernel_function='rbf', iterations=1000, verbose=False, random_state=None, **kwargs): """Compute MMD^2_u, its null distribution and the p-value of the kernel two-sample test. Note that extra parameters captured by **kwargs will be passed to pairwise_kernels() as kernel parameters. E.g. if kernel_two_sample_test(..., kernel_function='rbf', gamma=0.1), then this will result in getting the kernel through kernel_function(metric='rbf', gamma=0.1). """ m = len(X) n = len(Y) XY = np.vstack([X, Y]) K = pairwise_kernels(XY, metric=kernel_function, **kwargs) mmd2u = MMD2u(K, m, n) if verbose: print("MMD^2_u = %s" % mmd2u) print("Computing the null distribution.") mmd2u_null = compute_null_distribution(K, m, n, iterations, verbose=verbose, random_state=random_state) p_value = max(1.0/iterations, (mmd2u_null > mmd2u).sum() / float(iterations)) if verbose: print("p-value ~= %s \t (resolution : %s)" % (p_value, 1.0/iterations)) return mmd2u, mmd2u_null, p_value
[ "sklearn.metrics.pairwise_kernels", "numpy.zeros", "numpy.random.RandomState", "sys.stdout.flush", "numpy.vstack" ]
[((765, 785), 'numpy.zeros', 'np.zeros', (['iterations'], {}), '(iterations)\n', (773, 785), True, 'import numpy as np\n'), ((1459, 1479), 'numpy.zeros', 'np.zeros', (['iterations'], {}), '(iterations)\n', (1467, 1479), True, 'import numpy as np\n'), ((2223, 2240), 'numpy.vstack', 'np.vstack', (['[X, Y]'], {}), '([X, Y])\n', (2232, 2240), True, 'import numpy as np\n'), ((2249, 2303), 'sklearn.metrics.pairwise_kernels', 'pairwise_kernels', (['XY'], {'metric': 'kernel_function'}), '(XY, metric=kernel_function, **kwargs)\n', (2265, 2303), False, 'from sklearn.metrics import pairwise_kernels\n'), ((711, 746), 'numpy.random.RandomState', 'np.random.RandomState', (['random_state'], {}), '(random_state)\n', (732, 746), True, 'import numpy as np\n'), ((634, 657), 'numpy.random.RandomState', 'np.random.RandomState', ([], {}), '()\n', (655, 657), True, 'import numpy as np\n'), ((903, 917), 'sys.stdout.flush', 'stdout.flush', ([], {}), '()\n', (915, 917), False, 'from sys import stdout\n')]
import collections import numpy as np from scipy import stats from sklearn import metrics from optable.synthesis import manipulation from optable.synthesis import manipulation_candidate from optable.dataset import feature_types from optable import _core class OneHotMeanManipulation(manipulation.Manipulation): def __init__(self, path, dataset, col, value): self.__path = path self.__dataset = dataset self.__col = col self.__value = value super(OneHotMeanManipulation, self).__init__() def __repr__(self): return "One Hot Mean {} {} {}".format( self.__path, self.__col, self.__value) @property def path(self): return self.__path @property def dataset(self): return self.__dataset @property def col(self): return self.__col def calculate_priority(self): return 0.8 + 0.4 * self.path.not_deeper_count \ + 0.5 * self.path.substance_to_many_count(self.dataset, self.col) \ * self.path.to_many_path_priority(self.dataset, self.col) def meta_feature_size(): return 3 def meta_feature(self): to_many_meta = self.path.substance_to_many_count( self.dataset, self.col) \ * self.path.to_many_path_priority( self.dataset, self.col) return [1, self.path.not_deeper_count, to_many_meta] def meta_feature_name(): return [ "OneHotMean-Constant", "OneHotMean-NotDeeperCount", "OneHotMean-ToManyMeta" ] def calculate_size(self): return 1 def synthesis(self): self.__recursive_synthesis(self.__path) def __recursive_synthesis(self, path): if len(self.__path) == 0: return new_data_name = "{}OneHotMean_{}_{}_{}".format( feature_types.aggregate_processed_numerical.prefix, path, self.__col, self.__value) dst_table = self.dataset.tables[self.__path.dst] if dst_table.has_cache( ("categorical_manager", self.__col) ): categorical_manager = dst_table.get_cache( ("categorical_manager", self.__col) ) else: processing_data = \ dst_table.df[self.__col].fillna("").astype(str).values categorical_manager = \ _core.CategoricalManager(processing_data) dst_table.set_cache( ("categorical_manager", self.__col), categorical_manager ) dst_data = categorical_manager.is_array(self.__value) time_for_each_table = { table_idx: self.dataset.tables[table_name].hour_time_data for table_idx, table_name in enumerate(self.__path.table_names) if self.dataset.tables[table_name].has_time} sorted_index_for_each_table = { table_idx: self.dataset.tables[table_name].sorted_time_index for table_idx, table_name in enumerate(self.__path.table_names) if self.dataset.tables[table_name].has_time} src_id_for_each_relation = [ self.dataset.tables[rel.src].df[rel.src_id].values for rel in self.__path.relations ] dst_id_for_each_relation = [ self.dataset.tables[rel.dst].df[rel.dst_id].values for rel in self.__path.relations ] src_is_unique_for_each_relation = [ rel.type.src_is_unique for rel in self.__path.relations ] dst_is_unique_for_each_relation = [ rel.type.dst_is_unique for rel in self.__path.relations ] new_data = _core.Aggregator().aggregate( dst_data, time_for_each_table, sorted_index_for_each_table, src_id_for_each_relation, dst_id_for_each_relation, src_is_unique_for_each_relation, dst_is_unique_for_each_relation, "mean", "mean") train_size = np.isfinite(self.__dataset.target).sum() train_isfinite = np.isfinite(new_data[:train_size]) if (len(np.unique( new_data[:train_size][train_isfinite]) ) <= 1): return auc = metrics.roc_auc_score( self.__dataset.target[:train_size][train_isfinite], new_data[:train_size][train_isfinite]) if (auc < 0.5001 and auc > 0.4999): return self.__dataset.tables[self.__path.src].set_new_data( new_data, new_data_name) class OneHotMeanCandidate(manipulation_candidate.ManipulationCandidate): def search(self, path, dataset): if path.is_to_many: dst_table = dataset.tables[path.dst] ret = [] for col in dst_table.df.columns: if path.is_substance_to_one_with_col(dataset, col): continue ftype = dst_table.ftypes[col] if ftype == feature_types.categorical \ or ftype == feature_types.c_processed_categorical: dst_data = dataset.tables[path.dst].df[col].values if dst_table.has_cache( ("categorical_manager", col) ): categorical_manager = dst_table.get_cache( ("categorical_manager", col) ) else: processing_data = \ dst_table.df[col].fillna("").astype(str).values categorical_manager = \ _core.CategoricalManager(processing_data) dst_table.set_cache( ("categorical_manager", col), categorical_manager ) if dst_table.nunique[col] == 2: mode = categorical_manager.most_common(1)[0][0] ret.append(OneHotMeanManipulation( path, dataset, col, mode)) else: for value, freq in categorical_manager.most_common(5): if freq > 1: ret.append(OneHotMeanManipulation( path, dataset, col, value)) return ret else: return []
[ "optable._core.Aggregator", "numpy.isfinite", "sklearn.metrics.roc_auc_score", "optable._core.CategoricalManager", "numpy.unique" ]
[((4077, 4111), 'numpy.isfinite', 'np.isfinite', (['new_data[:train_size]'], {}), '(new_data[:train_size])\n', (4088, 4111), True, 'import numpy as np\n'), ((4252, 4368), 'sklearn.metrics.roc_auc_score', 'metrics.roc_auc_score', (['self.__dataset.target[:train_size][train_isfinite]', 'new_data[:train_size][train_isfinite]'], {}), '(self.__dataset.target[:train_size][train_isfinite],\n new_data[:train_size][train_isfinite])\n', (4273, 4368), False, 'from sklearn import metrics\n'), ((2397, 2438), 'optable._core.CategoricalManager', '_core.CategoricalManager', (['processing_data'], {}), '(processing_data)\n', (2421, 2438), False, 'from optable import _core\n'), ((3717, 3735), 'optable._core.Aggregator', '_core.Aggregator', ([], {}), '()\n', (3733, 3735), False, 'from optable import _core\n'), ((4011, 4045), 'numpy.isfinite', 'np.isfinite', (['self.__dataset.target'], {}), '(self.__dataset.target)\n', (4022, 4045), True, 'import numpy as np\n'), ((4128, 4176), 'numpy.unique', 'np.unique', (['new_data[:train_size][train_isfinite]'], {}), '(new_data[:train_size][train_isfinite])\n', (4137, 4176), True, 'import numpy as np\n'), ((5640, 5681), 'optable._core.CategoricalManager', '_core.CategoricalManager', (['processing_data'], {}), '(processing_data)\n', (5664, 5681), False, 'from optable import _core\n')]
import numpy as np import sys import os import matplotlib.pyplot as plt sys.path.append(os.path.abspath("../../gunshots")) sys.path.append(os.path.abspath("../../IoTPy/core")) sys.path.append(os.path.abspath("../../IoTPy/helper_functions")) sys.path.append(os.path.abspath("../../IoTPy/agent_types")) from stream import Stream, StreamArray from op import map_window from recent_values import recent_values from basics import map_e, map_w def window_dot_product(in_stream, out_stream, multiplicand_vector, step_size=1): """ Parameters ---------- in_stream: Stream input stream of agent out_stream: Stream output stream of agent multiplicand_vector: list or NumPy array length of multiplicand_vector must be strictly positive The dot product is applied between each sliding window and the multiplicand_vector step_size: int Must be positive The amount by which the sliding window moves on each step. Operation --------- Creates an agent which carries out the dot product of the multiplicand_vector and each sliding window. The window size is len(multiplicand_vector). """ @map_w def f(window, multiplicand_vector): return np.dot(window, multiplicand_vector) f(in_stream, out_stream, len(multiplicand_vector), step_size, multiplicand_vector=multiplicand_vector) #---------------------------------------------------------------- # TESTS #---------------------------------------------------------------- def test(): x = Stream('x') y = Stream('y') ## f(x, y, window_size=2, step_size=1, multiplicand_vector=[2, 100]) window_dot_product(x, y, multiplicand_vector=[2, 100]) x.extend(np.arange(8)) Stream.scheduler.step() assert recent_values(y) == [100, 202, 304, 406, 508, 610, 712] # y[n] = x[n]*2 + x[n+1]*100, for n = 0, 1, ..., 6 # so, y[n] = 2*n + 100*(n+1) # Note that the length of recent_values(y) is 7 rather than 8 # because the window size is 2 (i.e. the size of the multiplicand # vector). if __name__ == '__main__': test()
[ "recent_values.recent_values", "os.path.abspath", "stream.Stream.scheduler.step", "numpy.arange", "numpy.dot", "stream.Stream" ]
[((89, 122), 'os.path.abspath', 'os.path.abspath', (['"""../../gunshots"""'], {}), "('../../gunshots')\n", (104, 122), False, 'import os\n'), ((140, 175), 'os.path.abspath', 'os.path.abspath', (['"""../../IoTPy/core"""'], {}), "('../../IoTPy/core')\n", (155, 175), False, 'import os\n'), ((193, 240), 'os.path.abspath', 'os.path.abspath', (['"""../../IoTPy/helper_functions"""'], {}), "('../../IoTPy/helper_functions')\n", (208, 240), False, 'import os\n'), ((258, 300), 'os.path.abspath', 'os.path.abspath', (['"""../../IoTPy/agent_types"""'], {}), "('../../IoTPy/agent_types')\n", (273, 300), False, 'import os\n'), ((1548, 1559), 'stream.Stream', 'Stream', (['"""x"""'], {}), "('x')\n", (1554, 1559), False, 'from stream import Stream, StreamArray\n'), ((1568, 1579), 'stream.Stream', 'Stream', (['"""y"""'], {}), "('y')\n", (1574, 1579), False, 'from stream import Stream, StreamArray\n'), ((1743, 1766), 'stream.Stream.scheduler.step', 'Stream.scheduler.step', ([], {}), '()\n', (1764, 1766), False, 'from stream import Stream, StreamArray\n'), ((1233, 1268), 'numpy.dot', 'np.dot', (['window', 'multiplicand_vector'], {}), '(window, multiplicand_vector)\n', (1239, 1268), True, 'import numpy as np\n'), ((1725, 1737), 'numpy.arange', 'np.arange', (['(8)'], {}), '(8)\n', (1734, 1737), True, 'import numpy as np\n'), ((1778, 1794), 'recent_values.recent_values', 'recent_values', (['y'], {}), '(y)\n', (1791, 1794), False, 'from recent_values import recent_values\n')]