code
stringlengths
31
1.05M
apis
list
extract_api
stringlengths
97
1.91M
""" This module contains all routines for evaluating GDML and sGDML models. """ # MIT License # # Copyright (c) 2018-2020 <NAME>, <NAME> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. from __future__ import print_function import sys import logging import os import multiprocessing as mp import timeit from functools import partial try: import torch except ImportError: _has_torch = False else: _has_torch = True import numpy as np from . import __version__ from .utils.desc import Desc def share_array(arr_np): """ Return a ctypes array allocated from shared memory with data from a NumPy array of type `float`. Parameters ---------- arr_np : :obj:`numpy.ndarray` NumPy array. Returns ------- array of :obj:`ctype` """ arr = mp.RawArray('d', arr_np.ravel()) return arr, arr_np.shape def _predict_wkr( r, r_desc_d_desc, lat_and_inv, glob_id, wkr_start_stop=None, chunk_size=None ): """ Compute (part) of a prediction. Every prediction is a linear combination involving the training points used for this model. This function evalutates that combination for the range specified by `wkr_start_stop`. This workload can optionally be processed in chunks, which can be faster as it requires less memory to be allocated. Note ---- It is sufficient to provide either the parameter `r` or `r_desc_d_desc`. The other one can be set to `None`. Parameters ---------- r : :obj:`numpy.ndarray` An array of size 3N containing the Cartesian coordinates of each atom in the molecule. r_desc_d_desc : tuple of :obj:`numpy.ndarray` A tuple made up of: (1) An array of size D containing the descriptors of dimension D for the molecule. (2) An array of size D x 3N containing the descriptor Jacobian for the molecules. It has dimension D with 3N partial derivatives with respect to the 3N Cartesian coordinates of each atom. lat_and_inv : tuple of :obj:`numpy.ndarray` Tuple of 3 x 3 matrix containing lattice vectors as columns and its inverse. glob_id : int Identifier of the global namespace that this function is supposed to be using (zero if only one instance of this class exists at the same time). wkr_start_stop : tuple of int, optional Range defined by the indices of first and last (exclusive) sum element. The full prediction is generated if this parameter is not specified. chunk_size : int, optional Chunk size. The whole linear combination is evaluated in a large vector operation instead of looping over smaller chunks if this parameter is left unspecified. Returns ------- :obj:`numpy.ndarray` Partial prediction of all force components and energy (appended to array as last element). """ global globs glob = globs[glob_id] sig, n_perms = glob['sig'], glob['n_perms'] desc_func = glob['desc_func'] R_desc_perms = np.frombuffer(glob['R_desc_perms']).reshape( glob['R_desc_perms_shape'] ) R_d_desc_alpha_perms = np.frombuffer(glob['R_d_desc_alpha_perms']).reshape( glob['R_d_desc_alpha_perms_shape'] ) if 'alphas_E_lin' in glob: alphas_E_lin = np.frombuffer(glob['alphas_E_lin']).reshape( glob['alphas_E_lin_shape'] ) r_desc, r_d_desc = r_desc_d_desc or desc_func.from_R(r, lat_and_inv) n_train = int(R_desc_perms.shape[0] / n_perms) wkr_start, wkr_stop = (0, n_train) if wkr_start_stop is None else wkr_start_stop if chunk_size is None: chunk_size = n_train dim_d, dim_i = r_d_desc.shape dim_c = chunk_size * n_perms # Pre-allocate memory. diff_ab_perms = np.empty((dim_c, dim_d)) a_x2 = np.empty((dim_c,)) mat52_base = np.empty((dim_c,)) mat52_base_fact = 5.0 / (3 * sig ** 3) diag_scale_fact = 5.0 / sig sqrt5 = np.sqrt(5.0) E_F = np.zeros((dim_d + 1,)) F = E_F[1:] wkr_start *= n_perms wkr_stop *= n_perms b_start = wkr_start for b_stop in list(range(wkr_start + dim_c, wkr_stop, dim_c)) + [wkr_stop]: rj_desc_perms = R_desc_perms[b_start:b_stop, :] rj_d_desc_alpha_perms = R_d_desc_alpha_perms[b_start:b_stop, :] # Resize pre-allocated memory for last iteration, if chunk_size is not a divisor of the training set size. # Note: It's faster to process equally sized chunks. c_size = b_stop - b_start if c_size < dim_c: diff_ab_perms = diff_ab_perms[:c_size, :] a_x2 = a_x2[:c_size] mat52_base = mat52_base[:c_size] np.subtract( np.broadcast_to(r_desc, rj_desc_perms.shape), rj_desc_perms, out=diff_ab_perms, ) norm_ab_perms = sqrt5 * np.linalg.norm(diff_ab_perms, axis=1) np.exp(-norm_ab_perms / sig, out=mat52_base) mat52_base *= mat52_base_fact np.einsum( 'ji,ji->j', diff_ab_perms, rj_d_desc_alpha_perms, out=a_x2 ) # colum wise dot product F += (a_x2 * mat52_base).dot(diff_ab_perms) * diag_scale_fact mat52_base *= norm_ab_perms + sig F -= mat52_base.dot(rj_d_desc_alpha_perms) # Note: Energies are automatically predicted with a flipped sign here (because -E are trained, instead of E) E_F[0] += a_x2.dot(mat52_base) # Note: Energies are automatically predicted with a flipped sign here (because -E are trained, instead of E) if 'alphas_E_lin' in glob: K_fe = diff_ab_perms * mat52_base[:, None] F += alphas_E_lin[b_start:b_stop].dot(K_fe) K_ee = ( 1 + (norm_ab_perms / sig) * (1 + norm_ab_perms / (3 * sig)) ) * np.exp(-norm_ab_perms / sig) E_F[0] += K_ee.dot(alphas_E_lin[b_start:b_stop]) b_start = b_stop out = E_F[: dim_i + 1] # Descriptor has less entries than 3N, need to extend size of the 'E_F' array. if dim_d < dim_i: out = np.empty((dim_i + 1,)) out[0] = E_F[0] #np.dot(F, r_d_desc, out=out[1:]) out[1:] = np.dot(F, r_d_desc) return out class GDMLPredict(object): def __init__( self, model, batch_size=None, num_workers=1, max_processes=None, use_torch=False ): """ Query trained sGDML force fields. This class is used to load a trained model and make energy and force predictions for new geometries. GPU support is provided through PyTorch (requires optional `torch` dependency to be installed). Note ---- The parameters `batch_size` and `num_workers` are only relevant if this code runs on a CPU. Both can be set automatically via the function `prepare_parallel`. Note: Running calculations via PyTorch is only recommended with available GPU hardware. CPU calcuations are faster with our NumPy implementation. Parameters ---------- model : :obj:`dict` Data structure that holds all parameters of the trained model. This object is the output of `GDMLTrain.train` batch_size : int, optional Chunk size for processing parallel tasks. num_workers : int, optional Number of parallel workers. max_processes : int, optional Limit the max. number of processes. Otherwise all CPU cores are used. This parameters has no effect if `use_torch=True` use_torch : boolean, optional Use PyTorch to calculate predictions """ global globs if 'globs' not in globals(): globs = [] # Create a personal global space for this model at a new index # Note: do not call delete entries in this list, since 'self.glob_id' is # static. Instead, setting them to None conserves positions while still # freeing up memory. globs.append({}) self.glob_id = len(globs) - 1 glob = globs[self.glob_id] self.log = logging.getLogger(__name__) if 'type' not in model or not (model['type'] == 'm' or model['type'] == b'm'): self.log.critical('The provided data structure is not a valid model.') sys.exit() self.n_atoms = model['z'].shape[0] self.use_descriptor = model['use_descriptor'] # elif self.use_descriptor[0] == 'non_default_descr': # pass self.desc = Desc(self.n_atoms, max_processes=max_processes, use_descriptor=self.use_descriptor[0]) glob['desc_func'] = self.desc self.lat_and_inv = ( (model['lattice'], np.linalg.inv(model['lattice'])) if 'lattice' in model else None ) self.n_train = model['R_desc'].shape[1] glob['sig'] = model['sig'] self.std = model['std'] if 'std' in model else 1.0 self.c = model['c'] n_perms = model['perms'].shape[0] self.n_perms = n_perms glob['n_perms'] = n_perms self.tril_perms_lin = model['tril_perms_lin'] # Precompute permuted training descriptors and its first derivatives multiplied with the coefficients (only needed for cached variant). R_desc_perms = ( np.tile(model['R_desc'].T, n_perms)[:, self.tril_perms_lin] .reshape(self.n_train, n_perms, -1, order='F') .reshape(self.n_train * n_perms, -1) ) glob['R_desc_perms'], glob['R_desc_perms_shape'] = share_array(R_desc_perms) R_d_desc_alpha_perms = ( np.tile(model['R_d_desc_alpha'], n_perms)[:, self.tril_perms_lin] .reshape(self.n_train, n_perms, -1, order='F') .reshape(self.n_train * n_perms, -1) ) glob['R_d_desc_alpha_perms'], glob['R_d_desc_alpha_perms_shape'] = share_array( R_d_desc_alpha_perms ) if 'alphas_E' in model: alphas_E_lin = np.tile(model['alphas_E'][:, None], (1, n_perms)).ravel() glob['alphas_E_lin'], glob['alphas_E_lin_shape'] = share_array(alphas_E_lin) # GPU support self.use_torch = use_torch if use_torch and not _has_torch: raise ImportError( 'Optional PyTorch dependency not found! Please run \'pip install sgdml[torch]\' to install it or disable the PyTorch option.' ) self.torch_predict = None if self.use_torch: from .torchtools import GDMLTorchPredict self.torch_predict = GDMLTorchPredict(model, self.lat_and_inv)#.to(self.torch_device) # enable data parallelism n_gpu = torch.cuda.device_count() if n_gpu > 1: self.torch_predict = torch.nn.DataParallel(self.torch_predict) self.torch_device = 'cuda' if torch.cuda.is_available() else 'cpu' self.torch_predict.to(self.torch_device) # is_cuda = next(self.torch_predict.parameters()).is_cuda # if is_cuda: # self.log.info('Numbers of CUDA devices found: {:d}'.format(n_gpu)) # else: # self.log.warning( # 'No CUDA devices found! PyTorch is running on the CPU.' # ) # Parallel processing configuration self.bulk_mp = False # Bulk predictions with multiple processes? # How many parallel processes? self.max_processes = max_processes if self.max_processes is None: self.max_processes = mp.cpu_count() self.pool = None self.num_workers = 1 self._set_num_workers(num_workers) # Size of chunks in which each parallel task will be processed (unit: number of training samples) # This parameter should be as large as possible, but it depends on the size of available memory. self._set_chunk_size(batch_size) def __del__(self): global globs if hasattr(self, 'pool') and self.pool is not None: self.pool.close() if 'globs' in globals() and globs is not None and self.glob_id < len(globs): globs[self.glob_id] = None ## Public ## def set_alphas(self, R_d_desc, alphas_F, alphas_E=None): """ Reconfigure the current model with a new set of regression parameters. This is necessary when training the model iteratively. Parameters ---------- R_d_desc : :obj:`numpy.ndarray` Array containing the Jacobian of the descriptor for each training point. alphas_F : :obj:`numpy.ndarray` 1D array containing the new model parameters. alphas_F : :obj:`numpy.ndarray`, optional 1D array containing the additional new model parameters, if energy constraints are used in the kernel (`use_E_cstr=True`) """ if self.use_torch: model = self.torch_predict if isinstance(self.torch_predict, torch.nn.DataParallel): model = model.module model.set_alphas(R_d_desc, alphas_F) # TODO: E_cstr does not work on GPU! else: global globs glob = globs[self.glob_id] r_dim = R_d_desc.shape[2] R_d_desc_alpha = np.einsum( 'kji,ki->kj', R_d_desc, alphas_F.reshape(-1, r_dim) ) R_d_desc_alpha_perms_new = np.tile(R_d_desc_alpha, self.n_perms)[ :, self.tril_perms_lin ].reshape(self.n_train, self.n_perms, -1, order='F') R_d_desc_alpha_perms = np.frombuffer(glob['R_d_desc_alpha_perms']) np.copyto(R_d_desc_alpha_perms, R_d_desc_alpha_perms_new.ravel()) if alphas_E is not None: alphas_E_lin_new = np.tile(alphas_E[:, None], (1, self.n_perms)).ravel() alphas_E_lin = np.frombuffer(glob['alphas_E_lin']) np.copyto(alphas_E_lin, alphas_E_lin_new) def _set_num_workers( self, num_workers=None ): # TODO: complain if chunk or worker parameters do not fit training data (this causes issues with the caching)!! """ Set number of processes to use during prediction. If bulk_mp == True, each worker handles the whole generation of single prediction (this if for querying multiple geometries at once) If bulk_mp == False, each worker may handle only a part of a prediction (chunks are defined in 'wkr_starts_stops'). In that scenario multiple proesses are used to distribute the work of generating a single prediction This number should not exceed the number of available CPU cores. Note ---- This parameter can be optimally determined using `prepare_parallel`. Parameters ---------- num_workers : int, optional Number of processes (maximum value is set if `None`). """ if self.num_workers is not num_workers: if self.pool is not None: self.pool.close() self.pool.join() self.pool = None self.num_workers = 1 if num_workers is None or num_workers > 1: self.pool = mp.Pool(processes=num_workers) self.num_workers = self.pool._processes # Data ranges for processes if self.bulk_mp: wkr_starts = [self.n_train] else: wkr_starts = list( range( 0, self.n_train, int(np.ceil(float(self.n_train) / self.num_workers)), ) ) wkr_stops = wkr_starts[1:] + [self.n_train] self.wkr_starts_stops = list(zip(wkr_starts, wkr_stops)) def _reset_mp(self): if self.pool is not None: self.pool.close() self.pool.join() self.pool = None self.pool = mp.Pool(processes=self.num_workers) self.num_workers = self.pool._processes def _set_chunk_size(self, chunk_size=None): # TODO: complain if chunk or worker parameters do not fit training data (this causes issues with the caching)!! """ Set chunk size for each worker process. Every prediction is generated as a linear combination of the training points that the model is comprised of. If multiple workers are available (and bulk mode is disabled), each one processes an (approximatelly equal) part of those training points. Then, the chunk size determines how much of a processes workload is passed to NumPy's underlying low-level routines at once. If the chunk size is smaller than the number of points the worker is supposed to process, it processes them in multiple steps using a loop. This can sometimes be faster, depending on the available hardware. Note ---- This parameter can be optimally determined using `prepare_parallel`. Parameters ---------- chunk_size : int Chunk size (maximum value is set if `None`). """ if chunk_size is None: chunk_size = self.n_train self.chunk_size = chunk_size def _set_batch_size(self, batch_size=None): # deprecated """ Warning ------- Deprecated! Please use the function `_set_chunk_size` in future projects. Set chunk size for each worker process. A chunk is a subset of the training data points whose linear combination needs to be evaluated in order to generate a prediction. The chunk size determines how much of a processes workload will be passed to Python's underlying low-level routines at once. This parameter is highly hardware dependent. Note ---- This parameter can be optimally determined using `prepare_parallel`. Parameters ---------- batch_size : int Chunk size (maximum value is set if `None`). """ self._set_chunk_size(batch_size) def _set_bulk_mp(self, bulk_mp=False): """ Toggles bulk prediction mode. If bulk prediction is enabled, the prediction is parallelized accross input geometries, i.e. each worker generates the complete prediction for one query. Otherwise (depending on the number of available CPU cores) the input geometries are process sequentially, but every one of them may be processed by multiple workers at once (in chunks). Note ---- This parameter can be optimally determined using `prepare_parallel`. Parameters ---------- bulk_mp : bool, optional Enable or disable bulk prediction mode. """ bulk_mp = bool(bulk_mp) if self.bulk_mp is not bulk_mp: self.bulk_mp = bulk_mp # Reset data ranges for processes stored in 'wkr_starts_stops' self._set_num_workers(self.num_workers) def set_opt_num_workers_and_batch_size_fast(self, n_bulk=1, n_reps=1): # deprecated """ Warning ------- Deprecated! Please use the function `prepare_parallel` in future projects. Parameters ---------- n_bulk : int, optional Number of geometries that will be passed to the `predict` function in each call (performance will be optimized for that exact use case). n_reps : int, optional Number of repetitions (bigger value: more accurate, but also slower). Returns ------- int Force and energy prediciton speed in geometries per second. """ self.prepare_parallel(n_bulk, n_reps) def prepare_parallel( self, n_bulk=1, n_reps=1, return_is_from_cache=False ): # noqa: C901 """ Find and set the optimal parallelization parameters for the currently loaded model, running on a particular system. The result also depends on the number of geometries `n_bulk` that will be passed at once when calling the `predict` function. This function runs a benchmark in which the prediction routine is repeatedly called `n_reps`-times (default: 1) with varying parameter configurations, while the runtime is measured for each one. The optimal parameters are then cached for fast retrival in future calls of this function. We recommend calling this function after initialization of this class, as it will drastically increase the performance of the `predict` function. Note ---- Depending on the parameter `n_reps`, this routine may take some seconds/minutes to complete. However, once a statistically significant number of benchmark results has been gathered for a particular configuration, it starts returning almost instantly. Parameters ---------- n_bulk : int, optional Number of geometries that will be passed to the `predict` function in each call (performance will be optimized for that exact use case). n_reps : int, optional Number of repetitions (bigger value: more accurate, but also slower). return_is_from_cache : bool, optional If enabled, this function returns a second value indicating if the returned results were obtained from cache. Returns ------- int Force and energy prediciton speed in geometries per second. boolean, optional Return, whether this function obtained the results from cache. """ global globs glob = globs[self.glob_id] n_perms = glob['n_perms'] # No benchmarking necessary if prediction is running on GPUs. if self.use_torch: self.log.info( 'Skipping multi-CPU benchmark, since torch is enabled.' ) # TODO: clarity! return # Retrieve cached benchmark results, if available. bmark_result = self._load_cached_bmark_result(n_bulk) if bmark_result is not None: num_workers, chunk_size, bulk_mp, gps = bmark_result self._set_chunk_size(chunk_size) self._set_num_workers(num_workers) self._set_bulk_mp(bulk_mp) if return_is_from_cache: is_from_cache = True return gps, is_from_cache else: return gps best_results = [] last_i = None best_gps = 0 gps_min = 0.0 best_params = None r_dummy = np.random.rand(n_bulk, self.n_atoms * 3) def _dummy_predict(): self.predict(r_dummy) bulk_mp_rng = [True, False] if n_bulk > 1 else [False] for bulk_mp in bulk_mp_rng: self._set_bulk_mp(bulk_mp) if bulk_mp is False: last_i = 0 num_workers_rng = ( list(range(self.max_processes, 1, -1)) if bulk_mp else list(range(1, self.max_processes + 1)) ) # num_workers_rng_sizes = [batch_size for batch_size in batch_size_rng if min_batch_size % batch_size == 0] # for num_workers in range(min_num_workers,self.max_processes+1): for num_workers in num_workers_rng: if not bulk_mp and self.n_train % num_workers != 0: continue self._set_num_workers(num_workers) best_gps = 0 gps_rng = (np.inf, 0.0) # min and max per num_workers min_chunk_size = ( min(self.n_train, n_bulk) if bulk_mp else int(np.ceil(self.n_train / num_workers)) ) chunk_size_rng = list(range(min_chunk_size, 0, -1)) # for i in range(0,min_batch_size): chunk_size_rng_sizes = [ chunk_size for chunk_size in chunk_size_rng if min_chunk_size % chunk_size == 0 ] # print('batch_size_rng_sizes ' + str(bulk_mp)) # print(batch_size_rng_sizes) i_done = 0 i_dir = 1 i = 0 if last_i is None else last_i # i = 0 # print(batch_size_rng_sizes) while i >= 0 and i < len(chunk_size_rng_sizes): chunk_size = chunk_size_rng_sizes[i] self._set_chunk_size(chunk_size) i_done += 1 gps = n_bulk * n_reps / timeit.timeit(_dummy_predict, number=n_reps) # print( # '{:2d}@{:d} {:d} | {:7.2f} gps'.format( # num_workers, chunk_size, bulk_mp, gps # ) # ) gps_rng = ( min(gps_rng[0], gps), max(gps_rng[1], gps), ) # min and max per num_workers # gps_min_max = min(gps_min_max[0], gps), max(gps_min_max[1], gps) # print(' best_gps ' + str(best_gps)) # NEW # if gps > best_gps and gps > gps_min: # gps is still going up, everything is good # best_gps = gps # best_params = num_workers, batch_size, bulk_mp # else: # break # if gps > best_gps: # gps is still going up, everything is good # best_gps = gps # best_params = num_workers, batch_size, bulk_mp # else: # gps did not go up wrt. to previous step # # can we switch the search direction? # # did we already? # # we checked two consecutive configurations # # are bigger batch sizes possible? # print(batch_size_rng_sizes) # turn_search_dir = i_dir > 0 and i_done == 2 and batch_size != batch_size_rng_sizes[1] # # only turn, if the current gps is not lower than the lowest overall # if turn_search_dir and gps >= gps_min: # i -= 2 * i_dir # i_dir = -1 # print('><') # continue # else: # print('>>break ' + str(i_done)) # break # NEW # gps still going up? # AND: gps not lower than the lowest overall? # if gps < best_gps and gps >= gps_min: if gps < best_gps: if ( i_dir > 0 and i_done == 2 and chunk_size != chunk_size_rng_sizes[ 1 ] # there is no point in turning if this is the second batch size in the range ): # do we turn? i -= 2 * i_dir i_dir = -1 # print('><') continue else: if chunk_size == chunk_size_rng_sizes[1]: i -= 1 * i_dir # print('>>break ' + str(i_done)) break else: best_gps = gps best_params = num_workers, chunk_size, bulk_mp if ( not bulk_mp and n_bulk > 1 ): # stop search early when multiple cpus are available and the 1 cpu case is tested if ( gps < gps_min ): # if the batch size run is lower than the lowest overall, stop right here # print('breaking here') break i += 1 * i_dir last_i = i - 1 * i_dir i_dir = 1 if len(best_results) > 0: overall_best_gps = max(best_results, key=lambda x: x[1])[1] if best_gps < overall_best_gps: # print('breaking, because best of last test was worse than overall best so far') break # if best_gps < gps_min: # print('breaking here3') # break gps_min = gps_rng[0] # FIX me: is this the overall min? # print ('gps_min ' + str(gps_min)) # print ('best_gps') # print (best_gps) best_results.append( (best_params, best_gps) ) # best results per num_workers (num_workers, chunk_size, bulk_mp), gps = max(best_results, key=lambda x: x[1]) # Cache benchmark results. self._save_cached_bmark_result(n_bulk, num_workers, chunk_size, bulk_mp, gps) self._set_chunk_size(chunk_size) self._set_num_workers(num_workers) self._set_bulk_mp(bulk_mp) if return_is_from_cache: is_from_cache = False return gps, is_from_cache else: return gps def _save_cached_bmark_result(self, n_bulk, num_workers, chunk_size, bulk_mp, gps): pkg_dir = os.path.dirname(os.path.abspath(__file__)) bmark_file = '_bmark_cache.npz' bmark_path = os.path.join(pkg_dir, bmark_file) bkey = '{}-{}-{}-{}'.format( self.n_atoms, self.n_train, n_bulk, self.max_processes ) if os.path.exists(bmark_path): with np.load(bmark_path, allow_pickle=True) as bmark: bmark = dict(bmark) bmark['runs'] = np.append(bmark['runs'], bkey) bmark['num_workers'] = np.append(bmark['num_workers'], num_workers) bmark['batch_size'] = np.append(bmark['batch_size'], chunk_size) bmark['bulk_mp'] = np.append(bmark['bulk_mp'], bulk_mp) bmark['gps'] = np.append(bmark['gps'], gps) else: bmark = { 'code_version': __version__, 'runs': [bkey], 'gps': [gps], 'num_workers': [num_workers], 'batch_size': [chunk_size], 'bulk_mp': [bulk_mp], } np.savez_compressed(bmark_path, **bmark) def _load_cached_bmark_result(self, n_bulk): pkg_dir = os.path.dirname(os.path.abspath(__file__)) bmark_file = '_bmark_cache.npz' bmark_path = os.path.join(pkg_dir, bmark_file) bkey = '{}-{}-{}-{}'.format( self.n_atoms, self.n_train, n_bulk, self.max_processes ) if not os.path.exists(bmark_path): return None with np.load(bmark_path, allow_pickle=True) as bmark: # Keep collecting benchmark runs, until we have at least three. run_idxs = np.where(bmark['runs'] == bkey)[0] if len(run_idxs) >= 3: config_keys = [] for run_idx in run_idxs: config_keys.append( '{}-{}-{}'.format( bmark['num_workers'][run_idx], bmark['batch_size'][run_idx], bmark['bulk_mp'][run_idx], ) ) values, uinverse = np.unique(config_keys, return_index=True) best_mean = -1 best_gps = 0 for i, config_key in enumerate(zip(values, uinverse)): mean_gps = np.mean( bmark['gps'][ np.where(np.array(config_keys) == config_key[0])[0] ] ) if best_gps == 0 or best_gps < mean_gps: best_mean = i best_gps = mean_gps best_idx = run_idxs[uinverse[best_mean]] num_workers = bmark['num_workers'][best_idx] chunk_size = bmark['batch_size'][best_idx] bulk_mp = bmark['bulk_mp'][best_idx] return num_workers, chunk_size, bulk_mp, best_gps return None def get_GPU_batch(self): """ Get batch size used by the GPU implementation to process bulk predictions (predictions for multiple input geometries at once). This value is determined on-the-fly depending on the available GPU memory. """ if self.use_torch: model = self.torch_predict if isinstance(self.torch_predict, torch.nn.DataParallel): model = model.module return model._batch_size() def predict(self, R, R_desc=None, R_d_desc=None): """ Predict energy and forces for multiple geometries. This function can run on the GPU, if the optional PyTorch dependency is installed and `use_torch=True` was speciefied during initialization of this class. Optionally, the descriptors and descriptor Jacobians for the same geometries can be provided, if already available from some previous calculations. Note ---- The order of the atoms in `R` is not arbitrary and must be the same as used for training the model. Parameters ---------- R : :obj:`numpy.ndarray` An 2D array of size M x 3N containing the Cartesian coordinates of each atom of M molecules. R_desc : :obj:`numpy.ndarray`, optional An 2D array of size M x D containing the descriptors of dimension D for M molecules. R_d_desc : :obj:`numpy.ndarray`, optional A 2D array of size M x D x 3N containing of the descriptor Jacobians for M molecules. The descriptor has dimension D with 3N partial derivatives with respect to the 3N Cartesian coordinates of each atom. Returns ------- :obj:`numpy.ndarray` Energies stored in an 1D array of size M. :obj:`numpy.ndarray` Forces stored in an 2D arry of size M x 3N. """ # Use precomputed descriptors in training mode. train_mode = R_desc is not None and R_d_desc is not None # Add singleton dimension if input is (,3N). if R.ndim == 1: R = R[None, :] if self.use_torch: # multi-GPU (or CPU if no GPUs are available) n_train = R.shape[0] R_torch = torch.from_numpy(R.reshape(n_train, -1, 3)).to(self.torch_device) E_torch, F_torch = self.torch_predict.forward(R_torch) E = E_torch.cpu().numpy() F = F_torch.cpu().numpy().reshape(n_train, -1) else: # multi-CPU n_pred, dim_i = R.shape E_F = np.empty((n_pred, dim_i + 1)) if self.bulk_mp: # One whole prediction per worker (and multiple workers). _predict_wo_r_or_desc = partial( _predict_wkr, lat_and_inv=self.lat_and_inv, glob_id=self.glob_id, wkr_start_stop=None, chunk_size=self.chunk_size, ) for i, e_f in enumerate( self.pool.imap( partial(_predict_wo_r_or_desc, None) if train_mode else partial(_predict_wo_r_or_desc, r_desc_d_desc=None), zip(R_desc, R_d_desc) if train_mode else R, ) ): E_F[i, :] = e_f else: # Multiple workers per prediction (or just one worker). for i, r in enumerate(R): if train_mode: r_desc, r_d_desc = R_desc[i], R_d_desc[i] else: r_desc, r_d_desc = self.desc.from_R(r, self.lat_and_inv) _predict_wo_wkr_starts_stops = partial( _predict_wkr, None, (r_desc, r_d_desc), self.lat_and_inv, self.glob_id, chunk_size=self.chunk_size, ) if self.num_workers == 1: E_F[i, :] = _predict_wo_wkr_starts_stops() else: E_F[i, :] = sum( self.pool.imap_unordered( _predict_wo_wkr_starts_stops, self.wkr_starts_stops ) ) E_F *= self.std F = E_F[:, 1:] E = E_F[:, 0] + self.c return E, F
[ "numpy.load", "numpy.empty", "numpy.einsum", "torch.cuda.device_count", "numpy.savez_compressed", "numpy.linalg.norm", "numpy.exp", "numpy.tile", "timeit.timeit", "os.path.join", "numpy.unique", "multiprocessing.cpu_count", "os.path.abspath", "os.path.exists", "numpy.append", "functool...
[((5221, 5245), 'numpy.empty', 'np.empty', (['(dim_c, dim_d)'], {}), '((dim_c, dim_d))\n', (5229, 5245), True, 'import numpy as np\n'), ((5257, 5275), 'numpy.empty', 'np.empty', (['(dim_c,)'], {}), '((dim_c,))\n', (5265, 5275), True, 'import numpy as np\n'), ((5293, 5311), 'numpy.empty', 'np.empty', (['(dim_c,)'], {}), '((dim_c,))\n', (5301, 5311), True, 'import numpy as np\n'), ((5400, 5412), 'numpy.sqrt', 'np.sqrt', (['(5.0)'], {}), '(5.0)\n', (5407, 5412), True, 'import numpy as np\n'), ((5424, 5446), 'numpy.zeros', 'np.zeros', (['(dim_d + 1,)'], {}), '((dim_d + 1,))\n', (5432, 5446), True, 'import numpy as np\n'), ((7617, 7636), 'numpy.dot', 'np.dot', (['F', 'r_d_desc'], {}), '(F, r_d_desc)\n', (7623, 7636), True, 'import numpy as np\n'), ((6344, 6388), 'numpy.exp', 'np.exp', (['(-norm_ab_perms / sig)'], {'out': 'mat52_base'}), '(-norm_ab_perms / sig, out=mat52_base)\n', (6350, 6388), True, 'import numpy as np\n'), ((6435, 6504), 'numpy.einsum', 'np.einsum', (['"""ji,ji->j"""', 'diff_ab_perms', 'rj_d_desc_alpha_perms'], {'out': 'a_x2'}), "('ji,ji->j', diff_ab_perms, rj_d_desc_alpha_perms, out=a_x2)\n", (6444, 6504), True, 'import numpy as np\n'), ((7517, 7539), 'numpy.empty', 'np.empty', (['(dim_i + 1,)'], {}), '((dim_i + 1,))\n', (7525, 7539), True, 'import numpy as np\n'), ((9789, 9816), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (9806, 9816), False, 'import logging\n'), ((17832, 17867), 'multiprocessing.Pool', 'mp.Pool', ([], {'processes': 'self.num_workers'}), '(processes=self.num_workers)\n', (17839, 17867), True, 'import multiprocessing as mp\n'), ((25206, 25246), 'numpy.random.rand', 'np.random.rand', (['n_bulk', '(self.n_atoms * 3)'], {}), '(n_bulk, self.n_atoms * 3)\n', (25220, 25246), True, 'import numpy as np\n'), ((32453, 32486), 'os.path.join', 'os.path.join', (['pkg_dir', 'bmark_file'], {}), '(pkg_dir, bmark_file)\n', (32465, 32486), False, 'import os\n'), ((32614, 32640), 'os.path.exists', 'os.path.exists', (['bmark_path'], {}), '(bmark_path)\n', (32628, 32640), False, 'import os\n'), ((33400, 33440), 'numpy.savez_compressed', 'np.savez_compressed', (['bmark_path'], {}), '(bmark_path, **bmark)\n', (33419, 33440), True, 'import numpy as np\n'), ((33614, 33647), 'os.path.join', 'os.path.join', (['pkg_dir', 'bmark_file'], {}), '(pkg_dir, bmark_file)\n', (33626, 33647), False, 'import os\n'), ((4473, 4508), 'numpy.frombuffer', 'np.frombuffer', (["glob['R_desc_perms']"], {}), "(glob['R_desc_perms'])\n", (4486, 4508), True, 'import numpy as np\n'), ((4586, 4629), 'numpy.frombuffer', 'np.frombuffer', (["glob['R_d_desc_alpha_perms']"], {}), "(glob['R_d_desc_alpha_perms'])\n", (4599, 4629), True, 'import numpy as np\n'), ((6151, 6195), 'numpy.broadcast_to', 'np.broadcast_to', (['r_desc', 'rj_desc_perms.shape'], {}), '(r_desc, rj_desc_perms.shape)\n', (6166, 6195), True, 'import numpy as np\n'), ((6297, 6334), 'numpy.linalg.norm', 'np.linalg.norm', (['diff_ab_perms'], {'axis': '(1)'}), '(diff_ab_perms, axis=1)\n', (6311, 6334), True, 'import numpy as np\n'), ((10000, 10010), 'sys.exit', 'sys.exit', ([], {}), '()\n', (10008, 10010), False, 'import sys\n'), ((12408, 12433), 'torch.cuda.device_count', 'torch.cuda.device_count', ([], {}), '()\n', (12431, 12433), False, 'import torch\n'), ((13279, 13293), 'multiprocessing.cpu_count', 'mp.cpu_count', ([], {}), '()\n', (13291, 13293), True, 'import multiprocessing as mp\n'), ((15421, 15464), 'numpy.frombuffer', 'np.frombuffer', (["glob['R_d_desc_alpha_perms']"], {}), "(glob['R_d_desc_alpha_perms'])\n", (15434, 15464), True, 'import numpy as np\n'), ((32365, 32390), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (32380, 32390), False, 'import os\n'), ((33526, 33551), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (33541, 33551), False, 'import os\n'), ((33779, 33805), 'os.path.exists', 'os.path.exists', (['bmark_path'], {}), '(bmark_path)\n', (33793, 33805), False, 'import os\n'), ((33845, 33883), 'numpy.load', 'np.load', (['bmark_path'], {'allow_pickle': '(True)'}), '(bmark_path, allow_pickle=True)\n', (33852, 33883), True, 'import numpy as np\n'), ((38204, 38233), 'numpy.empty', 'np.empty', (['(n_pred, dim_i + 1)'], {}), '((n_pred, dim_i + 1))\n', (38212, 38233), True, 'import numpy as np\n'), ((4743, 4778), 'numpy.frombuffer', 'np.frombuffer', (["glob['alphas_E_lin']"], {}), "(glob['alphas_E_lin'])\n", (4756, 4778), True, 'import numpy as np\n'), ((7253, 7281), 'numpy.exp', 'np.exp', (['(-norm_ab_perms / sig)'], {}), '(-norm_ab_perms / sig)\n', (7259, 7281), True, 'import numpy as np\n'), ((10398, 10429), 'numpy.linalg.inv', 'np.linalg.inv', (["model['lattice']"], {}), "(model['lattice'])\n", (10411, 10429), True, 'import numpy as np\n'), ((12497, 12538), 'torch.nn.DataParallel', 'torch.nn.DataParallel', (['self.torch_predict'], {}), '(self.torch_predict)\n', (12518, 12538), False, 'import torch\n'), ((12582, 12607), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (12605, 12607), False, 'import torch\n'), ((15703, 15738), 'numpy.frombuffer', 'np.frombuffer', (["glob['alphas_E_lin']"], {}), "(glob['alphas_E_lin'])\n", (15716, 15738), True, 'import numpy as np\n'), ((15755, 15796), 'numpy.copyto', 'np.copyto', (['alphas_E_lin', 'alphas_E_lin_new'], {}), '(alphas_E_lin, alphas_E_lin_new)\n', (15764, 15796), True, 'import numpy as np\n'), ((17124, 17154), 'multiprocessing.Pool', 'mp.Pool', ([], {'processes': 'num_workers'}), '(processes=num_workers)\n', (17131, 17154), True, 'import multiprocessing as mp\n'), ((32660, 32698), 'numpy.load', 'np.load', (['bmark_path'], {'allow_pickle': '(True)'}), '(bmark_path, allow_pickle=True)\n', (32667, 32698), True, 'import numpy as np\n'), ((32778, 32808), 'numpy.append', 'np.append', (["bmark['runs']", 'bkey'], {}), "(bmark['runs'], bkey)\n", (32787, 32808), True, 'import numpy as np\n'), ((32848, 32892), 'numpy.append', 'np.append', (["bmark['num_workers']", 'num_workers'], {}), "(bmark['num_workers'], num_workers)\n", (32857, 32892), True, 'import numpy as np\n'), ((32931, 32973), 'numpy.append', 'np.append', (["bmark['batch_size']", 'chunk_size'], {}), "(bmark['batch_size'], chunk_size)\n", (32940, 32973), True, 'import numpy as np\n'), ((33009, 33045), 'numpy.append', 'np.append', (["bmark['bulk_mp']", 'bulk_mp'], {}), "(bmark['bulk_mp'], bulk_mp)\n", (33018, 33045), True, 'import numpy as np\n'), ((33077, 33105), 'numpy.append', 'np.append', (["bmark['gps']", 'gps'], {}), "(bmark['gps'], gps)\n", (33086, 33105), True, 'import numpy as np\n'), ((33994, 34025), 'numpy.where', 'np.where', (["(bmark['runs'] == bkey)"], {}), "(bmark['runs'] == bkey)\n", (34002, 34025), True, 'import numpy as np\n'), ((34478, 34519), 'numpy.unique', 'np.unique', (['config_keys'], {'return_index': '(True)'}), '(config_keys, return_index=True)\n', (34487, 34519), True, 'import numpy as np\n'), ((38364, 38490), 'functools.partial', 'partial', (['_predict_wkr'], {'lat_and_inv': 'self.lat_and_inv', 'glob_id': 'self.glob_id', 'wkr_start_stop': 'None', 'chunk_size': 'self.chunk_size'}), '(_predict_wkr, lat_and_inv=self.lat_and_inv, glob_id=self.glob_id,\n wkr_start_stop=None, chunk_size=self.chunk_size)\n', (38371, 38490), False, 'from functools import partial\n'), ((11699, 11748), 'numpy.tile', 'np.tile', (["model['alphas_E'][:, None]", '(1, n_perms)'], {}), "(model['alphas_E'][:, None], (1, n_perms))\n", (11706, 11748), True, 'import numpy as np\n'), ((39389, 39501), 'functools.partial', 'partial', (['_predict_wkr', 'None', '(r_desc, r_d_desc)', 'self.lat_and_inv', 'self.glob_id'], {'chunk_size': 'self.chunk_size'}), '(_predict_wkr, None, (r_desc, r_d_desc), self.lat_and_inv, self.\n glob_id, chunk_size=self.chunk_size)\n', (39396, 39501), False, 'from functools import partial\n'), ((15242, 15279), 'numpy.tile', 'np.tile', (['R_d_desc_alpha', 'self.n_perms'], {}), '(R_d_desc_alpha, self.n_perms)\n', (15249, 15279), True, 'import numpy as np\n'), ((15617, 15662), 'numpy.tile', 'np.tile', (['alphas_E[:, None]', '(1, self.n_perms)'], {}), '(alphas_E[:, None], (1, self.n_perms))\n', (15624, 15662), True, 'import numpy as np\n'), ((26341, 26376), 'numpy.ceil', 'np.ceil', (['(self.n_train / num_workers)'], {}), '(self.n_train / num_workers)\n', (26348, 26376), True, 'import numpy as np\n'), ((27257, 27301), 'timeit.timeit', 'timeit.timeit', (['_dummy_predict'], {'number': 'n_reps'}), '(_dummy_predict, number=n_reps)\n', (27270, 27301), False, 'import timeit\n'), ((11015, 11050), 'numpy.tile', 'np.tile', (["model['R_desc'].T", 'n_perms'], {}), "(model['R_desc'].T, n_perms)\n", (11022, 11050), True, 'import numpy as np\n'), ((11324, 11365), 'numpy.tile', 'np.tile', (["model['R_d_desc_alpha']", 'n_perms'], {}), "(model['R_d_desc_alpha'], n_perms)\n", (11331, 11365), True, 'import numpy as np\n'), ((38708, 38744), 'functools.partial', 'partial', (['_predict_wo_r_or_desc', 'None'], {}), '(_predict_wo_r_or_desc, None)\n', (38715, 38744), False, 'from functools import partial\n'), ((38812, 38862), 'functools.partial', 'partial', (['_predict_wo_r_or_desc'], {'r_desc_d_desc': 'None'}), '(_predict_wo_r_or_desc, r_desc_d_desc=None)\n', (38819, 38862), False, 'from functools import partial\n'), ((34767, 34788), 'numpy.array', 'np.array', (['config_keys'], {}), '(config_keys)\n', (34775, 34788), True, 'import numpy as np\n')]
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Unit tests for op_callback.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.python import keras from tensorflow.python.eager import context from tensorflow.python.eager import test from tensorflow.python.framework import op_callbacks from tensorflow.python.framework import ops from tensorflow.python.framework import test_util from tensorflow.python.ops import script_ops from tensorflow.python.util import compat # Keep all the hard-coded op type strings in one place so they are easy to # change all at once in the face of any possible future op type name changes. _ENTER_OP = b"Enter" _EXIT_OP = b"Exit" _IDENTITY_OP = b"Identity" _IF_OP = b"If" _MERGE_OP = b"Merge" _NEXT_ITERATION_OP = b"NextIteration" _PLACEHOLDER_OP = b"Placeholder" _STATELESS_IF_OP = b"StatelessIf" _SWITCH_OP = b"Switch" _VAR_HANDLE_OP = b"VarHandleOp" _WHILE_OP = b"While" class _NumpyFunctionCallback(object): def __init__(self, instrument_graph_ops=True, float_only=False): self.instrument_graph_ops = instrument_graph_ops self._float_only = float_only self.reset() def callback(self, op_type, inputs, attrs, outputs, op_name=None, graph=None): is_eager = not graph if is_eager: self.eager_op_types.append( compat.as_bytes(op_type) if op_type else op_type) self.eager_op_names.append( compat.as_bytes(op_name) if op_name else op_name) self.eager_attrs.append(attrs) self.eager_graphs.append(graph) self.eager_inputs.append(inputs) else: self.graph_op_types.append( compat.as_bytes(op_type) if op_type else op_type) self.graph_op_names.append( compat.as_bytes(op_name) if op_name else op_name) self.graph_attrs.append(attrs) self.graph_graphs.append(graph) self.graph_graph_versions.append(graph.version) self.graph_inputs.append(inputs) if not self.instrument_graph_ops: return outputs # Instrument the graph with numpy_function. instrumented_outputs = [] for output in outputs: if compat.as_bytes(op_type) in (_ENTER_OP, _EXIT_OP, _IF_OP, _MERGE_OP, _NEXT_ITERATION_OP, _STATELESS_IF_OP, _SWITCH_OP, _WHILE_OP, _IDENTITY_OP, _VAR_HANDLE_OP, _PLACEHOLDER_OP): # TODO(cais): Overriding the output of StatelessIf, If and While ops # currently fails with error. Investigate (b/139668453). # Avoid instrumenting Identity ops as well, as they are inserted # by tf.function/AutoGraph for marshalling outputs. instrumented_output = output else: def record(ndarray_value): if compat.as_bytes(op_name) not in self.graph_internal_ndarrays: self.graph_internal_ndarrays[compat.as_bytes(op_name)] = [] self.graph_internal_ndarrays[compat.as_bytes(op_name)].append( ndarray_value) return ndarray_value if self._float_only and not output.dtype.is_floating: instrumented_output = output else: instrumented_output = script_ops.numpy_function( record, [output], output.dtype) instrumented_output.set_shape(output.shape) instrumented_outputs.append(instrumented_output) return instrumented_outputs def reset(self): self.eager_op_types = [] self.eager_op_names = [] self.eager_attrs = [] self.eager_graphs = [] self.eager_inputs = [] self.graph_op_types = [] self.graph_op_names = [] self.graph_attrs = [] self.graph_graphs = [] self.graph_graph_versions = [] self.graph_inputs = [] # A dict mapping tensor name (e.g., "MatMut_10") to a list of ndarrays. # The list is the history of the tensor's computation result inside # `tf.Graph`s (`FuncGraph`s). # For an op with multiple output tensors, the outputs are interleaved in # the list. self.graph_internal_ndarrays = {} class OpCallbacksTest(test_util.TensorFlowTestCase): def tearDown(self): op_callbacks.clear_op_callbacks() super(OpCallbacksTest, self).tearDown() @test_util.run_in_graph_and_eager_modes def testKerasLSTMPredict(self): instrument = _NumpyFunctionCallback(float_only=True) op_callbacks.add_op_callback(instrument.callback) model = keras.Sequential() model.add(keras.layers.LSTM(1, input_shape=(2, 4))) model.compile(loss="mse", optimizer="sgd") xs = np.zeros([8, 2, 4], dtype=np.float32) ys = model.predict(xs) self.assertAllClose(ys, np.zeros([8, 1])) # We avoid asserting on the internal details of the LSTM implementation. # Instead, we just assert that some graph-internal execution states are # recorded by the callback. self.assertTrue(instrument.graph_internal_ndarrays) @test_util.run_in_graph_and_eager_modes def testKeraModelFit(self): # TODO(cais): The purely PyFunc (numpy_function) based instrumentation # doesn't work for the entire Keras model and its fit() call, due to some # shape inference limitations. Use tfdbg's gen_debug_ops for testing # instead (b/139668469). instrument = _NumpyFunctionCallback(instrument_graph_ops=False) op_callbacks.add_op_callback(instrument.callback) model = keras.Sequential() model.add(keras.layers.Dense(10, input_shape=(8,), activation="relu")) model.add(keras.layers.BatchNormalization()) model.add(keras.layers.Dense(1, activation="linear")) model.compile(loss="mse", optimizer="adam") batch_size = 4 xs = np.ones([batch_size, 8]) ys = np.zeros([batch_size, 1]) history = model.fit(xs, ys, epochs=2, verbose=0) # Simply assert that the training proceeded as expected and that # op callbacks are invoked. We prefer not to assert on the details of the # graph construction and the execution, in order to avoid future # maintenance cost. self.assertEqual(len(history.history["loss"]), 2) self.assertTrue(instrument.graph_op_types) self.assertEqual(len(instrument.graph_op_types), len(instrument.graph_op_names)) if context.executing_eagerly(): self.assertTrue(instrument.eager_op_types) if __name__ == "__main__": ops.enable_eager_execution() test.main()
[ "tensorflow.python.keras.layers.Dense", "tensorflow.python.framework.op_callbacks.add_op_callback", "tensorflow.python.eager.test.main", "tensorflow.python.util.compat.as_bytes", "tensorflow.python.framework.op_callbacks.clear_op_callbacks", "numpy.zeros", "numpy.ones", "tensorflow.python.keras.layers...
[((7089, 7117), 'tensorflow.python.framework.ops.enable_eager_execution', 'ops.enable_eager_execution', ([], {}), '()\n', (7115, 7117), False, 'from tensorflow.python.framework import ops\n'), ((7120, 7131), 'tensorflow.python.eager.test.main', 'test.main', ([], {}), '()\n', (7129, 7131), False, 'from tensorflow.python.eager import test\n'), ((4906, 4939), 'tensorflow.python.framework.op_callbacks.clear_op_callbacks', 'op_callbacks.clear_op_callbacks', ([], {}), '()\n', (4937, 4939), False, 'from tensorflow.python.framework import op_callbacks\n'), ((5123, 5172), 'tensorflow.python.framework.op_callbacks.add_op_callback', 'op_callbacks.add_op_callback', (['instrument.callback'], {}), '(instrument.callback)\n', (5151, 5172), False, 'from tensorflow.python.framework import op_callbacks\n'), ((5186, 5204), 'tensorflow.python.keras.Sequential', 'keras.Sequential', ([], {}), '()\n', (5202, 5204), False, 'from tensorflow.python import keras\n'), ((5318, 5355), 'numpy.zeros', 'np.zeros', (['[8, 2, 4]'], {'dtype': 'np.float32'}), '([8, 2, 4], dtype=np.float32)\n', (5326, 5355), True, 'import numpy as np\n'), ((6071, 6120), 'tensorflow.python.framework.op_callbacks.add_op_callback', 'op_callbacks.add_op_callback', (['instrument.callback'], {}), '(instrument.callback)\n', (6099, 6120), False, 'from tensorflow.python.framework import op_callbacks\n'), ((6134, 6152), 'tensorflow.python.keras.Sequential', 'keras.Sequential', ([], {}), '()\n', (6150, 6152), False, 'from tensorflow.python import keras\n'), ((6412, 6436), 'numpy.ones', 'np.ones', (['[batch_size, 8]'], {}), '([batch_size, 8])\n', (6419, 6436), True, 'import numpy as np\n'), ((6446, 6471), 'numpy.zeros', 'np.zeros', (['[batch_size, 1]'], {}), '([batch_size, 1])\n', (6454, 6471), True, 'import numpy as np\n'), ((6980, 7007), 'tensorflow.python.eager.context.executing_eagerly', 'context.executing_eagerly', ([], {}), '()\n', (7005, 7007), False, 'from tensorflow.python.eager import context\n'), ((5219, 5259), 'tensorflow.python.keras.layers.LSTM', 'keras.layers.LSTM', (['(1)'], {'input_shape': '(2, 4)'}), '(1, input_shape=(2, 4))\n', (5236, 5259), False, 'from tensorflow.python import keras\n'), ((5412, 5428), 'numpy.zeros', 'np.zeros', (['[8, 1]'], {}), '([8, 1])\n', (5420, 5428), True, 'import numpy as np\n'), ((6167, 6226), 'tensorflow.python.keras.layers.Dense', 'keras.layers.Dense', (['(10)'], {'input_shape': '(8,)', 'activation': '"""relu"""'}), "(10, input_shape=(8,), activation='relu')\n", (6185, 6226), False, 'from tensorflow.python import keras\n'), ((6242, 6275), 'tensorflow.python.keras.layers.BatchNormalization', 'keras.layers.BatchNormalization', ([], {}), '()\n', (6273, 6275), False, 'from tensorflow.python import keras\n'), ((6291, 6333), 'tensorflow.python.keras.layers.Dense', 'keras.layers.Dense', (['(1)'], {'activation': '"""linear"""'}), "(1, activation='linear')\n", (6309, 6333), False, 'from tensorflow.python import keras\n'), ((2028, 2052), 'tensorflow.python.util.compat.as_bytes', 'compat.as_bytes', (['op_type'], {}), '(op_type)\n', (2043, 2052), False, 'from tensorflow.python.util import compat\n'), ((2122, 2146), 'tensorflow.python.util.compat.as_bytes', 'compat.as_bytes', (['op_name'], {}), '(op_name)\n', (2137, 2146), False, 'from tensorflow.python.util import compat\n'), ((2340, 2364), 'tensorflow.python.util.compat.as_bytes', 'compat.as_bytes', (['op_type'], {}), '(op_type)\n', (2355, 2364), False, 'from tensorflow.python.util import compat\n'), ((2434, 2458), 'tensorflow.python.util.compat.as_bytes', 'compat.as_bytes', (['op_name'], {}), '(op_name)\n', (2449, 2458), False, 'from tensorflow.python.util import compat\n'), ((2839, 2863), 'tensorflow.python.util.compat.as_bytes', 'compat.as_bytes', (['op_type'], {}), '(op_type)\n', (2854, 2863), False, 'from tensorflow.python.util import compat\n'), ((3956, 4013), 'tensorflow.python.ops.script_ops.numpy_function', 'script_ops.numpy_function', (['record', '[output]', 'output.dtype'], {}), '(record, [output], output.dtype)\n', (3981, 4013), False, 'from tensorflow.python.ops import script_ops\n'), ((3525, 3549), 'tensorflow.python.util.compat.as_bytes', 'compat.as_bytes', (['op_name'], {}), '(op_name)\n', (3540, 3549), False, 'from tensorflow.python.util import compat\n'), ((3630, 3654), 'tensorflow.python.util.compat.as_bytes', 'compat.as_bytes', (['op_name'], {}), '(op_name)\n', (3645, 3654), False, 'from tensorflow.python.util import compat\n'), ((3702, 3726), 'tensorflow.python.util.compat.as_bytes', 'compat.as_bytes', (['op_name'], {}), '(op_name)\n', (3717, 3726), False, 'from tensorflow.python.util import compat\n')]
import pytesseract import cv2 import numpy as np from matplotlib import pyplot as plt from scipy.ndimage import interpolation as inter class SimpleProcessor: """ Preprocess images using OpenCV processing methods """ def get_grayscale(self, image): """ Convert image to greyscale. Uses COLOR_BGR2GRAY color space conversion code Parameters: ----------- - image: dtype('uint8') with 3 channels Image loaded with OpenCV imread method or other similar method Returns: -------- - greyscale_image: dtype('uint8') with a single channel Greyscale image """ return cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) def thresholding(self, image, threshold=127): """ Applies threshold with THRESH_TRUNC type Parameters: ----------- - threshold: int, default to 127 Returns: -------- - dst: dtype('uint8') with single channel Image with applied threshold """ return cv2.threshold(image, threshold, 255, cv2.THRESH_TRUNC)[1] def adaptative_thresholding(self, image, maxValue=255): """ Applies adaptative threshold with ADAPTIVE_THRESH_GAUSSIAN_C type Parameters: ----------- - maxValue: int, default to 255 Returns: -------- - dst: dtype('uint8') with single channel Image with applied threshold """ return cv2.adaptiveThreshold(image, maxValue, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 3) def correct_skew(self, image, delta=1, limit=5): """ Corrects wrong image skew. This function is based on Python Skew correction from https://stackoverflow.com/questions/57964634/python-opencv-skew-correction-for-ocr Parameters: ----------- - image: dtype('uint8') with 3 channels Image loaded with OpenCV imread method or other similar method - delta: int, optional Possible variation of correction angle - limit: int, optional A limit for rotation angle Returns: -------- - rotated: dtype('uint8') with single channel Image with skew corrected based in best angle found by algorithm """ def determine_score(arr, angle): data = inter.rotate(arr, angle, reshape=False, order=0) histogram = np.sum(data, axis=1) score = np.sum((histogram[1:] - histogram[:-1]) ** 2) return histogram, score scores = [] angles = np.arange(-limit, limit + delta, delta) for angle in angles: histogram, score = determine_score(image, angle) scores.append(score) best_angle = angles[scores.index(max(scores))] (h, w) = image.shape[:2] center = (w // 2, h // 2) M = cv2.getRotationMatrix2D(center, best_angle, 1.0) rotated = cv2.warpAffine(image, M, (w, h), flags=cv2.INTER_CUBIC, \ borderMode=cv2.BORDER_REPLICATE) return rotated def noise_removal(self, image): """ Applies image denoising using Non-local Means Denoising algorithm. Parameters: ----------- - image: dtype('uint8') with 3 channels Greyscale image Returns: -------- - dst: dtype('uint8') with single channel Denoised image """ img_shape = image.shape dst = np.zeros(img_shape) return cv2.fastNlMeansDenoising(image, dst, h=5, block_size=7, search_window=21) def erode(self, image, kernel_size=5, iterations=1): """ Tries to thin image edges using based on a kernel size using CV2 erode method Parameters: ----------- - image: dtype('uint8') with 3 channels Greyscale image - kernel_size: int, optional, default to 5 Size of image erode kernel - iterations: int, optional, default to 1 Number of kernel iteractions over the image Returns: -------- - image: dtype('uint8') with single channel Image with thin edges """ kernel = np.zeros((kernel_size, kernel_size), np.uint8) return cv2.erode(image, kernel, iterations) def preprocess(self, image): """ Executes Simple Processos image correction pipeline in 4 steps: 1) Binarization; 2) Noise Removal 3) Skew Correction 4) Thinning and Skeletonization Parameters: ----------- - image: dtype('uint8') with 3 channels Colored Image Returns: -------- - image: dtype('uint8') with single channel Binarized greyscale image with image corrections and noise removal actions applied """ # 1) Binarization grayscale = self.get_grayscale(image) # thresh = self.thresholding(grayscale) adaptative_thresh = self.adaptative_thresholding(thresh) # 2) Noise Removal denoised = self.noise_removal(adaptative_thresh) # 3) Skew Correction corrected_skew_image = self.correct_skew(denoised) # 4) Thinning and Skeletonization ts = self.erode(denoised, 2, 3) return corrected_skew_image
[ "numpy.sum", "cv2.cvtColor", "cv2.threshold", "numpy.zeros", "scipy.ndimage.interpolation.rotate", "cv2.adaptiveThreshold", "cv2.fastNlMeansDenoising", "cv2.warpAffine", "numpy.arange", "cv2.erode", "cv2.getRotationMatrix2D" ]
[((682, 721), 'cv2.cvtColor', 'cv2.cvtColor', (['image', 'cv2.COLOR_BGR2GRAY'], {}), '(image, cv2.COLOR_BGR2GRAY)\n', (694, 721), False, 'import cv2\n'), ((1525, 1626), 'cv2.adaptiveThreshold', 'cv2.adaptiveThreshold', (['image', 'maxValue', 'cv2.ADAPTIVE_THRESH_GAUSSIAN_C', 'cv2.THRESH_BINARY', '(11)', '(3)'], {}), '(image, maxValue, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.\n THRESH_BINARY, 11, 3)\n', (1546, 1626), False, 'import cv2\n'), ((2661, 2700), 'numpy.arange', 'np.arange', (['(-limit)', '(limit + delta)', 'delta'], {}), '(-limit, limit + delta, delta)\n', (2670, 2700), True, 'import numpy as np\n'), ((2960, 3008), 'cv2.getRotationMatrix2D', 'cv2.getRotationMatrix2D', (['center', 'best_angle', '(1.0)'], {}), '(center, best_angle, 1.0)\n', (2983, 3008), False, 'import cv2\n'), ((3027, 3120), 'cv2.warpAffine', 'cv2.warpAffine', (['image', 'M', '(w, h)'], {'flags': 'cv2.INTER_CUBIC', 'borderMode': 'cv2.BORDER_REPLICATE'}), '(image, M, (w, h), flags=cv2.INTER_CUBIC, borderMode=cv2.\n BORDER_REPLICATE)\n', (3041, 3120), False, 'import cv2\n'), ((3585, 3604), 'numpy.zeros', 'np.zeros', (['img_shape'], {}), '(img_shape)\n', (3593, 3604), True, 'import numpy as np\n'), ((3620, 3693), 'cv2.fastNlMeansDenoising', 'cv2.fastNlMeansDenoising', (['image', 'dst'], {'h': '(5)', 'block_size': '(7)', 'search_window': '(21)'}), '(image, dst, h=5, block_size=7, search_window=21)\n', (3644, 3693), False, 'import cv2\n'), ((4326, 4372), 'numpy.zeros', 'np.zeros', (['(kernel_size, kernel_size)', 'np.uint8'], {}), '((kernel_size, kernel_size), np.uint8)\n', (4334, 4372), True, 'import numpy as np\n'), ((4388, 4424), 'cv2.erode', 'cv2.erode', (['image', 'kernel', 'iterations'], {}), '(image, kernel, iterations)\n', (4397, 4424), False, 'import cv2\n'), ((1071, 1125), 'cv2.threshold', 'cv2.threshold', (['image', 'threshold', '(255)', 'cv2.THRESH_TRUNC'], {}), '(image, threshold, 255, cv2.THRESH_TRUNC)\n', (1084, 1125), False, 'import cv2\n'), ((2427, 2475), 'scipy.ndimage.interpolation.rotate', 'inter.rotate', (['arr', 'angle'], {'reshape': '(False)', 'order': '(0)'}), '(arr, angle, reshape=False, order=0)\n', (2439, 2475), True, 'from scipy.ndimage import interpolation as inter\n'), ((2500, 2520), 'numpy.sum', 'np.sum', (['data'], {'axis': '(1)'}), '(data, axis=1)\n', (2506, 2520), True, 'import numpy as np\n'), ((2541, 2586), 'numpy.sum', 'np.sum', (['((histogram[1:] - histogram[:-1]) ** 2)'], {}), '((histogram[1:] - histogram[:-1]) ** 2)\n', (2547, 2586), True, 'import numpy as np\n')]
""" This code is extended from Hengyuan Hu's repository. https://github.com/hengyuan-hu/bottom-up-attention-vqa """ from __future__ import print_function import errno import os import re import collections import numpy as np import operator import functools from PIL import Image import torch import torch.nn as nn import torch.nn.functional as F from torch._six import string_classes from torch.utils.data.dataloader import default_collate EPS = 1e-7 def assert_eq(real, expected): assert real == expected, '%s (true) vs %s (expected)' % (real, expected) def assert_array_eq(real, expected): assert (np.abs(real-expected) < EPS).all(), \ '%s (true) vs %s (expected)' % (real, expected) def assert_tensor_eq(real, expected, eps=EPS): assert (torch.abs(real-expected) < eps).all(), \ '%s (true) vs %s (expected)' % (real, expected) def load_folder(folder, suffix): imgs = [] for f in sorted(os.listdir(folder)): if f.endswith(suffix): imgs.append(os.path.join(folder, f)) return imgs def load_imageid(folder): images = load_folder(folder, 'png') img_ids = set() for img in images: img_id = int(img.split('/')[-1].split('.')[0].split('_')[-1]) img_ids.add(img_id) return img_ids def pil_loader(path): with open(path, 'rb') as f: with Image.open(f) as img: return img.convert('RGB') def weights_init(m): """custom weights initialization.""" cname = m.__class__ if cname == nn.Linear or cname == nn.Conv2d or cname == nn.ConvTranspose2d: m.weight.data.normal_(0.0, 0.02) elif cname == nn.BatchNorm2d: m.weight.data.normal_(1.0, 0.02) m.bias.data.fill_(0) else: print('%s is not initialized.' % cname) def init_net(net, net_file): if net_file: net.load_state_dict(torch.load(net_file)) else: net.apply(weights_init) def create_dir(path): if not os.path.exists(path): try: os.makedirs(path) except OSError as exc: if exc.errno != errno.EEXIST: raise def print_model(model, logger): print(model) nParams = 0 for w in model.parameters(): nParams += functools.reduce(operator.mul, w.size(), 1) if logger: logger.write('nParams=\t'+str(nParams)) def save_model(path, model, epoch, optimizer=None): model_dict = { 'epoch': epoch, 'model_state': model.state_dict() } if optimizer is not None: model_dict['optimizer_state'] = optimizer.state_dict() torch.save(model_dict, path) # Select the indices given by `lengths` in the second dimension # As a result, # of dimensions is shrinked by one # @param pad(Tensor) # @param len(list[int]) def rho_select(pad, lengths): # Index of the last output for each sequence. idx_ = (lengths-1).view(-1,1).expand(pad.size(0), pad.size(2)).unsqueeze(1) extracted = pad.gather(1, idx_).squeeze(1) return extracted def trim_collate(batch): "Puts each data field into a tensor with outer dimension batch size" _use_shared_memory = True error_msg = "batch must contain tensors, numbers, dicts or lists; found {}" elem_type = type(batch[0]) if torch.is_tensor(batch[0]): out = None if 1 < batch[0].dim(): # image features max_num_boxes = max([x.size(0) for x in batch]) if _use_shared_memory: # If we're in a background process, concatenate directly into a # shared memory tensor to avoid an extra copy numel = len(batch) * max_num_boxes * batch[0].size(-1) storage = batch[0].storage()._new_shared(numel) out = batch[0].new(storage) # warning: F.pad returns Variable! return torch.stack([F.pad(x, (0,0,0,max_num_boxes-x.size(0))).data for x in batch], 0, out=out) else: if _use_shared_memory: # If we're in a background process, concatenate directly into a # shared memory tensor to avoid an extra copy numel = sum([x.numel() for x in batch]) storage = batch[0].storage()._new_shared(numel) out = batch[0].new(storage) return torch.stack(batch, 0, out=out) elif elem_type.__module__ == 'numpy' and elem_type.__name__ != 'str_' \ and elem_type.__name__ != 'string_': elem = batch[0] if elem_type.__name__ == 'ndarray': # array of string classes and object if re.search('[SaUO]', elem.dtype.str) is not None: raise TypeError(error_msg.format(elem.dtype)) return torch.stack([torch.from_numpy(b) for b in batch], 0) if elem.shape == (): # scalars py_type = float if elem.dtype.name.startswith('float') else int return numpy_type_map[elem.dtype.name](list(map(py_type, batch))) elif isinstance(batch[0], int): return torch.LongTensor(batch) elif isinstance(batch[0], float): return torch.DoubleTensor(batch) elif isinstance(batch[0], string_classes): return batch elif isinstance(batch[0], collections.Mapping): return {key: default_collate([d[key] for d in batch]) for key in batch[0]} elif isinstance(batch[0], collections.Sequence): transposed = zip(*batch) return [trim_collate(samples) for samples in transposed] raise TypeError((error_msg.format(type(batch[0])))) class Logger(object): def __init__(self, output_name): dirname = os.path.dirname(output_name) if not os.path.exists(dirname): os.mkdir(dirname) self.log_file = open(output_name, 'w') self.infos = {} def append(self, key, val): vals = self.infos.setdefault(key, []) vals.append(val) def log(self, extra_msg=''): msgs = [extra_msg] for key, vals in self.infos.iteritems(): msgs.append('%s %.6f' % (key, np.mean(vals))) msg = '\n'.join(msgs) self.log_file.write(msg + '\n') self.log_file.flush() self.infos = {} return msg def write(self, msg): self.log_file.write(msg + '\n') self.log_file.flush() print(msg) def create_glove_embedding_init(idx2word, glove_file): word2emb = {} with open(glove_file, 'r', encoding='utf-8') as f: entries = f.readlines() emb_dim = len(entries[0].split(' ')) - 1 print('embedding dim is %d' % emb_dim) weights = np.zeros((len(idx2word), emb_dim), dtype=np.float32) for entry in entries: vals = entry.split(' ') word = vals[0] vals = list(map(float, vals[1:])) word2emb[word] = np.array(vals) for idx, word in enumerate(idx2word): if word not in word2emb: continue weights[idx] = word2emb[word] return weights, word2emb # Remove Flickr30K Entity annotations in a string def remove_annotations(s): return re.sub(r'\[[^ ]+ ','',s).replace(']', '') def get_sent_data(file_path): phrases = [] with open(file_path, 'r', encoding='utf-8') as f: for sent in f: str = remove_annotations(sent.strip()) phrases.append(str) return phrases # Find position of a given sublist # return the index of the last token def find_sublist(arr, sub): sublen = len(sub) first = sub[0] indx = -1 while True: try: indx = arr.index(first, indx + 1) except ValueError: break if sub == arr[indx: indx + sublen]: return indx + sublen - 1 return -1 def calculate_iou(obj1, obj2): area1 = calculate_area(obj1) area2 = calculate_area(obj2) intersection = get_intersection(obj1, obj2) area_int = calculate_area(intersection) return area_int / (area1 + area2 - area_int) def calculate_area(obj): return (obj[2] - obj[0]) * (obj[3] - obj[1]) def get_intersection(obj1, obj2): left = obj1[0] if obj1[0] > obj2[0] else obj2[0] top = obj1[1] if obj1[1] > obj2[1] else obj2[1] right = obj1[2] if obj1[2] < obj2[2] else obj2[2] bottom = obj1[3] if obj1[3] < obj2[3] else obj2[3] if left > right or top > bottom: return [0, 0, 0, 0] return [left, top, right, bottom] def get_match_index(src_bboxes, dst_bboxes): indices = set() for src_bbox in src_bboxes: for i, dst_bbox in enumerate(dst_bboxes): iou = calculate_iou(src_bbox, dst_bbox) if iou >= 0.5: indices.add(i) return list(indices) # Batched index_select def batched_index_select(t, dim, inds): dummy = inds.unsqueeze(2).expand(inds.size(0), inds.size(1), t.size(2)) out = t.gather(dim, dummy) # b x e x f return out
[ "os.mkdir", "numpy.abs", "numpy.mean", "os.path.join", "os.path.dirname", "torch.load", "os.path.exists", "torch.DoubleTensor", "torch.is_tensor", "re.search", "re.sub", "torch.utils.data.dataloader.default_collate", "os.listdir", "torch.from_numpy", "os.makedirs", "torch.stack", "to...
[((2597, 2625), 'torch.save', 'torch.save', (['model_dict', 'path'], {}), '(model_dict, path)\n', (2607, 2625), False, 'import torch\n'), ((3263, 3288), 'torch.is_tensor', 'torch.is_tensor', (['batch[0]'], {}), '(batch[0])\n', (3278, 3288), False, 'import torch\n'), ((936, 954), 'os.listdir', 'os.listdir', (['folder'], {}), '(folder)\n', (946, 954), False, 'import os\n'), ((1956, 1976), 'os.path.exists', 'os.path.exists', (['path'], {}), '(path)\n', (1970, 1976), False, 'import os\n'), ((5612, 5640), 'os.path.dirname', 'os.path.dirname', (['output_name'], {}), '(output_name)\n', (5627, 5640), False, 'import os\n'), ((6780, 6794), 'numpy.array', 'np.array', (['vals'], {}), '(vals)\n', (6788, 6794), True, 'import numpy as np\n'), ((1350, 1363), 'PIL.Image.open', 'Image.open', (['f'], {}), '(f)\n', (1360, 1363), False, 'from PIL import Image\n'), ((1857, 1877), 'torch.load', 'torch.load', (['net_file'], {}), '(net_file)\n', (1867, 1877), False, 'import torch\n'), ((2003, 2020), 'os.makedirs', 'os.makedirs', (['path'], {}), '(path)\n', (2014, 2020), False, 'import os\n'), ((4302, 4332), 'torch.stack', 'torch.stack', (['batch', '(0)'], {'out': 'out'}), '(batch, 0, out=out)\n', (4313, 4332), False, 'import torch\n'), ((5656, 5679), 'os.path.exists', 'os.path.exists', (['dirname'], {}), '(dirname)\n', (5670, 5679), False, 'import os\n'), ((5693, 5710), 'os.mkdir', 'os.mkdir', (['dirname'], {}), '(dirname)\n', (5701, 5710), False, 'import os\n'), ((7047, 7073), 're.sub', 're.sub', (['"""\\\\[[^ ]+ """', '""""""', 's'], {}), "('\\\\[[^ ]+ ', '', s)\n", (7053, 7073), False, 'import re\n'), ((616, 639), 'numpy.abs', 'np.abs', (['(real - expected)'], {}), '(real - expected)\n', (622, 639), True, 'import numpy as np\n'), ((770, 796), 'torch.abs', 'torch.abs', (['(real - expected)'], {}), '(real - expected)\n', (779, 796), False, 'import torch\n'), ((1012, 1035), 'os.path.join', 'os.path.join', (['folder', 'f'], {}), '(folder, f)\n', (1024, 1035), False, 'import os\n'), ((5019, 5042), 'torch.LongTensor', 'torch.LongTensor', (['batch'], {}), '(batch)\n', (5035, 5042), False, 'import torch\n'), ((4590, 4625), 're.search', 're.search', (['"""[SaUO]"""', 'elem.dtype.str'], {}), "('[SaUO]', elem.dtype.str)\n", (4599, 4625), False, 'import re\n'), ((5096, 5121), 'torch.DoubleTensor', 'torch.DoubleTensor', (['batch'], {}), '(batch)\n', (5114, 5121), False, 'import torch\n'), ((4734, 4753), 'torch.from_numpy', 'torch.from_numpy', (['b'], {}), '(b)\n', (4750, 4753), False, 'import torch\n'), ((6039, 6052), 'numpy.mean', 'np.mean', (['vals'], {}), '(vals)\n', (6046, 6052), True, 'import numpy as np\n'), ((5263, 5303), 'torch.utils.data.dataloader.default_collate', 'default_collate', (['[d[key] for d in batch]'], {}), '([d[key] for d in batch])\n', (5278, 5303), False, 'from torch.utils.data.dataloader import default_collate\n')]
import os import numpy as np import cv2 from io import BytesIO from time import sleep from picamera import PiCamera def calibrate_chessboard(imgs_path="./images", width=6, height=9, mode="RT"): """Estimate the intrinsic and extrinsic properties of a camera. This code is written according to: 1- OpenCV Documentation # https://docs.opencv.org/3.4/dc/dbb/tutorial_py_calibration.html 2- Fernando Souza codes # https://medium.com/vacatronics/3-ways-to-calibrate-your-camera-using-opencv-and-python-395528a51615 Parameters ---------- imgs_path: str The path directory of chessboard images. width: int Number of corners (from top-to-bottom). height: int Number of corners (from left-to-right). mode: str Mode of calibration, when `RT` the calibration and capturing images are done at the same time, in a real-time manner. Returns ------- ret: np.ndarray The root mean square (RMS) re-projection error. mtx: np.ndarray 3x3 floating-point camera intrinsic matrix. dist: np.ndarray Vector of distortion coefficients. rvecs: np.ndarray Vector of rotation vectors (Rodrigues ) estimated for each pattern view. tvecs: np.ndarray Vector of translation vectors estimated for each pattern view. """ try: os.makedirs(os.path.join(imgs_path, "cimages")) except FileExistsError: pass camera = PiCamera() camera.resolution = (1024, 768) # cunstruct a stream to hold image data image_stream = BytesIO() # termination criteria criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001) # prepare object points, like (0,0,0), (1,0,0), (2,0,0) ....,(6,5,0) objp = np.zeros((width * height, 3), np.float32) objp[:, :2] = np.mgrid[0:6, 0:9].T.reshape(-1, 2) # Arrays to store object points and image points from all the images. objpoints = [] # 3d point in real world space imgpoints = [] # 2d points in image plane. if mode == "RT": counter = 0 while counter < 20: camera.start_preview() sleep(3) camera.capture(image_stream, format="jpeg") image_stream.seek(0) file_bytes = np.asarray(bytearray(image_stream.read()), dtype=np.uint8) img = cv2.imdecode(file_bytes, cv2.IMREAD_COLOR) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) image_stream.seek(0) image_stream.truncate() # Find the chess board corners ret, corners = cv2.findChessboardCorners(gray, (width, height), None) # If found, add object points, image points (after refining them) if ret == True: print(f"Image #{counter:02d} is captured.") cv2.imwrite(f'images/img-{counter:02d}.jpeg', img) objpoints.append(objp) corners2 = cv2.cornerSubPix(gray, corners, (11, 11), (-1, -1), criteria) imgpoints.append(corners2) # Draw and display the corners exit cv2.drawChessboardCorners(img, (width, height), corners2, ret) cv2.imwrite(f'{imgs_path}/cimages/cimg-{counter:02d}.jpeg', img) counter += 1 camera.stop_preview() else: images = [] for root, dirs, files in os.walk(imgs_path): for file in files: if file.endswith(".jpeg"): images.append(os.path.join(root, file)) for fname in images: img = cv2.imread(fname) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Find the chess board corners ret, corners = cv2.findChessboardCorners(gray, (width, height), None) # If found, add object points, image points (after refining them) if ret == True: print(f"Image {fname} is captured.") objpoints.append(objp) corners2 = cv2.cornerSubPix(gray, corners, (11, 11), (-1, -1), criteria) imgpoints.append(corners2) # Draw and display the cornersexit cv2.drawChessboardCorners(img, (width, height), corners2, ret) cv2.imwrite(f'{imgs_path}/cimages/c{fname.split("/")[-1].split(".")[0]}.jpeg', img) ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, gray.shape[::-1], None, None) rvecs = [arr.T for arr in rvecs] tvecs = [arr.T for arr in tvecs] rvecs = np.concatenate(rvecs, axis=0) tvecs = np.concatenate(tvecs, axis=0) print("Re-projection error estimation:") mean_error = 0 for idx, objpoint in enumerate(objpoints): imgpoints2, _ = cv2.projectPoints(objpoint, rvecs[idx], tvecs[idx], mtx, dist) error = cv2.norm(imgpoints[idx], imgpoints2, cv2.NORM_L2) / len(imgpoints2) mean_error += error print(f"Total error: {mean_error / len(objpoints):.4f}") return (ret, mtx, dist, rvecs, tvecs)
[ "io.BytesIO", "cv2.findChessboardCorners", "cv2.cvtColor", "cv2.imwrite", "os.walk", "numpy.zeros", "cv2.projectPoints", "cv2.imdecode", "time.sleep", "cv2.cornerSubPix", "cv2.imread", "cv2.calibrateCamera", "cv2.norm", "cv2.drawChessboardCorners", "os.path.join", "numpy.concatenate", ...
[((1473, 1483), 'picamera.PiCamera', 'PiCamera', ([], {}), '()\n', (1481, 1483), False, 'from picamera import PiCamera\n'), ((1584, 1593), 'io.BytesIO', 'BytesIO', ([], {}), '()\n', (1591, 1593), False, 'from io import BytesIO\n'), ((1786, 1827), 'numpy.zeros', 'np.zeros', (['(width * height, 3)', 'np.float32'], {}), '((width * height, 3), np.float32)\n', (1794, 1827), True, 'import numpy as np\n'), ((4520, 4591), 'cv2.calibrateCamera', 'cv2.calibrateCamera', (['objpoints', 'imgpoints', 'gray.shape[::-1]', 'None', 'None'], {}), '(objpoints, imgpoints, gray.shape[::-1], None, None)\n', (4539, 4591), False, 'import cv2\n'), ((4678, 4707), 'numpy.concatenate', 'np.concatenate', (['rvecs'], {'axis': '(0)'}), '(rvecs, axis=0)\n', (4692, 4707), True, 'import numpy as np\n'), ((4720, 4749), 'numpy.concatenate', 'np.concatenate', (['tvecs'], {'axis': '(0)'}), '(tvecs, axis=0)\n', (4734, 4749), True, 'import numpy as np\n'), ((3487, 3505), 'os.walk', 'os.walk', (['imgs_path'], {}), '(imgs_path)\n', (3494, 3505), False, 'import os\n'), ((4891, 4953), 'cv2.projectPoints', 'cv2.projectPoints', (['objpoint', 'rvecs[idx]', 'tvecs[idx]', 'mtx', 'dist'], {}), '(objpoint, rvecs[idx], tvecs[idx], mtx, dist)\n', (4908, 4953), False, 'import cv2\n'), ((1382, 1416), 'os.path.join', 'os.path.join', (['imgs_path', '"""cimages"""'], {}), "(imgs_path, 'cimages')\n", (1394, 1416), False, 'import os\n'), ((2174, 2182), 'time.sleep', 'sleep', (['(3)'], {}), '(3)\n', (2179, 2182), False, 'from time import sleep\n'), ((2388, 2430), 'cv2.imdecode', 'cv2.imdecode', (['file_bytes', 'cv2.IMREAD_COLOR'], {}), '(file_bytes, cv2.IMREAD_COLOR)\n', (2400, 2430), False, 'import cv2\n'), ((2450, 2487), 'cv2.cvtColor', 'cv2.cvtColor', (['img', 'cv2.COLOR_BGR2GRAY'], {}), '(img, cv2.COLOR_BGR2GRAY)\n', (2462, 2487), False, 'import cv2\n'), ((2653, 2707), 'cv2.findChessboardCorners', 'cv2.findChessboardCorners', (['gray', '(width, height)', 'None'], {}), '(gray, (width, height), None)\n', (2678, 2707), False, 'import cv2\n'), ((3689, 3706), 'cv2.imread', 'cv2.imread', (['fname'], {}), '(fname)\n', (3699, 3706), False, 'import cv2\n'), ((3726, 3763), 'cv2.cvtColor', 'cv2.cvtColor', (['img', 'cv2.COLOR_BGR2GRAY'], {}), '(img, cv2.COLOR_BGR2GRAY)\n', (3738, 3763), False, 'import cv2\n'), ((3834, 3888), 'cv2.findChessboardCorners', 'cv2.findChessboardCorners', (['gray', '(width, height)', 'None'], {}), '(gray, (width, height), None)\n', (3859, 3888), False, 'import cv2\n'), ((4970, 5019), 'cv2.norm', 'cv2.norm', (['imgpoints[idx]', 'imgpoints2', 'cv2.NORM_L2'], {}), '(imgpoints[idx], imgpoints2, cv2.NORM_L2)\n', (4978, 5019), False, 'import cv2\n'), ((2891, 2941), 'cv2.imwrite', 'cv2.imwrite', (['f"""images/img-{counter:02d}.jpeg"""', 'img'], {}), "(f'images/img-{counter:02d}.jpeg', img)\n", (2902, 2941), False, 'import cv2\n'), ((3025, 3086), 'cv2.cornerSubPix', 'cv2.cornerSubPix', (['gray', 'corners', '(11, 11)', '(-1, -1)', 'criteria'], {}), '(gray, corners, (11, 11), (-1, -1), criteria)\n', (3041, 3086), False, 'import cv2\n'), ((3215, 3277), 'cv2.drawChessboardCorners', 'cv2.drawChessboardCorners', (['img', '(width, height)', 'corners2', 'ret'], {}), '(img, (width, height), corners2, ret)\n', (3240, 3277), False, 'import cv2\n'), ((3294, 3358), 'cv2.imwrite', 'cv2.imwrite', (['f"""{imgs_path}/cimages/cimg-{counter:02d}.jpeg"""', 'img'], {}), "(f'{imgs_path}/cimages/cimg-{counter:02d}.jpeg', img)\n", (3305, 3358), False, 'import cv2\n'), ((4132, 4193), 'cv2.cornerSubPix', 'cv2.cornerSubPix', (['gray', 'corners', '(11, 11)', '(-1, -1)', 'criteria'], {}), '(gray, corners, (11, 11), (-1, -1), criteria)\n', (4148, 4193), False, 'import cv2\n'), ((4321, 4383), 'cv2.drawChessboardCorners', 'cv2.drawChessboardCorners', (['img', '(width, height)', 'corners2', 'ret'], {}), '(img, (width, height), corners2, ret)\n', (4346, 4383), False, 'import cv2\n'), ((3615, 3639), 'os.path.join', 'os.path.join', (['root', 'file'], {}), '(root, file)\n', (3627, 3639), False, 'import os\n')]
# coding=utf-8 # Copyright 2022 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse from typing import List import numpy as np import torch from torch.utils.data import DataLoader import evaluate from accelerate import Accelerator, DistributedType from datasets import DatasetDict, load_dataset # New Code # # We'll be using StratifiedKFold for this example from sklearn.model_selection import StratifiedKFold from transformers import ( AdamW, AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed, ) ######################################################################## # This is a fully working simple example to use Accelerate, # specifically showcasing how to perform Cross Validation, # and builds off the `nlp_example.py` script. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To help focus on the differences in the code, building `DataLoaders` # was refactored into its own function. # New additions from the base script can be found quickly by # looking for the # New Code # tags # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## MAX_GPU_BATCH_SIZE = 16 EVAL_BATCH_SIZE = 32 # New Code # # We need a different `get_dataloaders` function that will build dataloaders by indexs def get_fold_dataloaders( accelerator: Accelerator, dataset: DatasetDict, train_idxs: List[int], valid_idxs: List[int], batch_size: int = 16 ): """ Gets a set of train, valid, and test dataloaders for a particular fold Args: accelerator (`Accelerator`): The main `Accelerator` object train_idxs (list of `int`): The split indicies for the training dataset valid_idxs (list of `int`): The split indicies for the validation dataset batch_size (`int`): The size of the minibatch. Default is 16 """ tokenizer = AutoTokenizer.from_pretrained("bert-base-cased") datasets = DatasetDict( { "train": dataset["train"].select(train_idxs), "validation": dataset["train"].select(valid_idxs), "test": dataset["validation"], } ) def tokenize_function(examples): # max_length=None => use the model max length (it's actually the default) outputs = tokenizer(examples["sentence1"], examples["sentence2"], truncation=True, max_length=None) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset tokenized_datasets = datasets.map( tokenize_function, batched=True, remove_columns=["idx", "sentence1", "sentence2"], ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library tokenized_datasets = tokenized_datasets.rename_column("label", "labels") def collate_fn(examples): # On TPU it's best to pad everything to the same length or training will be very slow. if accelerator.distributed_type == DistributedType.TPU: return tokenizer.pad(examples, padding="max_length", max_length=128, return_tensors="pt") return tokenizer.pad(examples, padding="longest", return_tensors="pt") # Instantiate dataloaders. train_dataloader = DataLoader( tokenized_datasets["train"], shuffle=True, collate_fn=collate_fn, batch_size=batch_size ) eval_dataloader = DataLoader( tokenized_datasets["validation"], shuffle=False, collate_fn=collate_fn, batch_size=EVAL_BATCH_SIZE ) test_dataloader = DataLoader( tokenized_datasets["test"], shuffle=False, collate_fn=collate_fn, batch_size=EVAL_BATCH_SIZE ) return train_dataloader, eval_dataloader, test_dataloader def training_function(config, args): # New Code # test_labels = None test_predictions = [] # Download the dataset datasets = load_dataset("glue", "mrpc") # Create our splits kfold = StratifiedKFold(n_splits=int(args.num_folds)) # Initialize accelerator accelerator = Accelerator(cpu=args.cpu, mixed_precision=args.mixed_precision) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs lr = config["lr"] num_epochs = int(config["num_epochs"]) correct_bias = config["correct_bias"] seed = int(config["seed"]) batch_size = int(config["batch_size"]) metric = evaluate.load("glue", "mrpc") # If the batch size is too big we use gradient accumulation gradient_accumulation_steps = 1 if batch_size > MAX_GPU_BATCH_SIZE: gradient_accumulation_steps = batch_size // MAX_GPU_BATCH_SIZE batch_size = MAX_GPU_BATCH_SIZE set_seed(seed) # New Code # # Create our folds: folds = kfold.split(np.zeros(datasets["train"].num_rows), datasets["train"]["label"]) # Iterate over them for train_idxs, valid_idxs in folds: train_dataloader, eval_dataloader, test_dataloader = get_fold_dataloaders( accelerator, datasets, train_idxs, valid_idxs, ) if test_labels is None: test_labels = datasets["validation"]["label"] # Instantiate the model (we build the model here so that the seed also control new weights initialization) model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", return_dict=True) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). model = model.to(accelerator.device) # Instantiate optimizer optimizer = AdamW(params=model.parameters(), lr=lr, correct_bias=correct_bias) # Instantiate scheduler lr_scheduler = get_linear_schedule_with_warmup( optimizer=optimizer, num_warmup_steps=100, num_training_steps=(len(train_dataloader) * num_epochs) // gradient_accumulation_steps, ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare( model, optimizer, train_dataloader, eval_dataloader, lr_scheduler ) # Now we train the model for epoch in range(num_epochs): model.train() for step, batch in enumerate(train_dataloader): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device) outputs = model(**batch) loss = outputs.loss loss = loss / gradient_accumulation_steps accelerator.backward(loss) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(eval_dataloader): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device) with torch.no_grad(): outputs = model(**batch) predictions = outputs.logits.argmax(dim=-1) predictions, references = accelerator.gather((predictions, batch["labels"])) metric.add_batch( predictions=predictions, references=references, ) eval_metric = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f"epoch {epoch}:", eval_metric) # New Code # # We also run predictions on the test set at the very end fold_predictions = [] for step, batch in enumerate(test_dataloader): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device) with torch.no_grad(): outputs = model(**batch) predictions = outputs.logits predictions, references = accelerator.gather((predictions, batch["labels"])) fold_predictions.append(predictions.cpu()) metric.add_batch( predictions=predictions.argmax(dim=-1), references=references, ) test_metric = metric.compute() # Use accelerator.print to print only on the main process. test_predictions.append(torch.cat(fold_predictions, dim=0)) # We now need to release all our memory and get rid of the current model, optimizer, etc accelerator.free_memory() # New Code # # Finally we check the accuracy of our folded results: preds = torch.stack(test_predictions, dim=0).sum(dim=0).div(int(config["n_splits"])).argmax(dim=-1) test_metric = metric.compute(predictions=preds, references=test_labels) accelerator.print("Average test metrics from all folds:", test_metric) def main(): parser = argparse.ArgumentParser(description="Simple example of training script.") parser.add_argument( "--mixed_precision", type=str, default="no", choices=["no", "fp16", "bf16"], help="Whether to use mixed precision. Choose" "between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10." "and an Nvidia Ampere GPU.", ) parser.add_argument("--cpu", action="store_true", help="If passed, will train on the CPU.") # New Code # parser.add_argument("--num_folds", type=int, default=3, help="The number of splits to perform across the dataset") args = parser.parse_args() config = {"lr": 2e-5, "num_epochs": 3, "correct_bias": True, "seed": 42, "batch_size": 16} training_function(config, args) if __name__ == "__main__": main()
[ "datasets.load_dataset", "argparse.ArgumentParser", "torch.utils.data.DataLoader", "torch.stack", "accelerate.Accelerator", "numpy.zeros", "torch.cat", "evaluate.load", "transformers.set_seed", "transformers.AutoTokenizer.from_pretrained", "transformers.AutoModelForSequenceClassification.from_pr...
[((2841, 2889), 'transformers.AutoTokenizer.from_pretrained', 'AutoTokenizer.from_pretrained', (['"""bert-base-cased"""'], {}), "('bert-base-cased')\n", (2870, 2889), False, 'from transformers import AdamW, AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed\n'), ((4246, 4349), 'torch.utils.data.DataLoader', 'DataLoader', (["tokenized_datasets['train']"], {'shuffle': '(True)', 'collate_fn': 'collate_fn', 'batch_size': 'batch_size'}), "(tokenized_datasets['train'], shuffle=True, collate_fn=collate_fn,\n batch_size=batch_size)\n", (4256, 4349), False, 'from torch.utils.data import DataLoader\n'), ((4382, 4497), 'torch.utils.data.DataLoader', 'DataLoader', (["tokenized_datasets['validation']"], {'shuffle': '(False)', 'collate_fn': 'collate_fn', 'batch_size': 'EVAL_BATCH_SIZE'}), "(tokenized_datasets['validation'], shuffle=False, collate_fn=\n collate_fn, batch_size=EVAL_BATCH_SIZE)\n", (4392, 4497), False, 'from torch.utils.data import DataLoader\n'), ((4530, 4638), 'torch.utils.data.DataLoader', 'DataLoader', (["tokenized_datasets['test']"], {'shuffle': '(False)', 'collate_fn': 'collate_fn', 'batch_size': 'EVAL_BATCH_SIZE'}), "(tokenized_datasets['test'], shuffle=False, collate_fn=collate_fn,\n batch_size=EVAL_BATCH_SIZE)\n", (4540, 4638), False, 'from torch.utils.data import DataLoader\n'), ((4859, 4887), 'datasets.load_dataset', 'load_dataset', (['"""glue"""', '"""mrpc"""'], {}), "('glue', 'mrpc')\n", (4871, 4887), False, 'from datasets import DatasetDict, load_dataset\n'), ((5017, 5080), 'accelerate.Accelerator', 'Accelerator', ([], {'cpu': 'args.cpu', 'mixed_precision': 'args.mixed_precision'}), '(cpu=args.cpu, mixed_precision=args.mixed_precision)\n', (5028, 5080), False, 'from accelerate import Accelerator, DistributedType\n'), ((5362, 5391), 'evaluate.load', 'evaluate.load', (['"""glue"""', '"""mrpc"""'], {}), "('glue', 'mrpc')\n", (5375, 5391), False, 'import evaluate\n'), ((5649, 5663), 'transformers.set_seed', 'set_seed', (['seed'], {}), '(seed)\n', (5657, 5663), False, 'from transformers import AdamW, AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed\n'), ((10337, 10410), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Simple example of training script."""'}), "(description='Simple example of training script.')\n", (10360, 10410), False, 'import argparse\n'), ((5730, 5766), 'numpy.zeros', 'np.zeros', (["datasets['train'].num_rows"], {}), "(datasets['train'].num_rows)\n", (5738, 5766), True, 'import numpy as np\n'), ((6271, 6362), 'transformers.AutoModelForSequenceClassification.from_pretrained', 'AutoModelForSequenceClassification.from_pretrained', (['"""bert-base-cased"""'], {'return_dict': '(True)'}), "('bert-base-cased',\n return_dict=True)\n", (6321, 6362), False, 'from transformers import AdamW, AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed\n'), ((9812, 9846), 'torch.cat', 'torch.cat', (['fold_predictions'], {'dim': '(0)'}), '(fold_predictions, dim=0)\n', (9821, 9846), False, 'import torch\n'), ((9292, 9307), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (9305, 9307), False, 'import torch\n'), ((8431, 8446), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (8444, 8446), False, 'import torch\n'), ((10067, 10103), 'torch.stack', 'torch.stack', (['test_predictions'], {'dim': '(0)'}), '(test_predictions, dim=0)\n', (10078, 10103), False, 'import torch\n')]
""" Convert ZDF point cloud to TXT format without Zivid Software. Note: ZIVID_DATA needs to be set to the location of Zivid Sample Data files. """ from pathlib import Path import os import numpy as np from netCDF4 import Dataset def _main(): filename_zdf = Path() / f"{str(os.environ['ZIVID_DATA'])}/Zivid3D.zdf" filename_txt = "Zivid3D.txt" print(f"Reading {filename_zdf} point cloud") with Dataset(filename_zdf) as data: # Extracting the point cloud xyz = data["data"]["pointcloud"][:, :, :] # Extracting the RGB image rgb = data["data"]["rgba_image"][:, :, :3] # Extracting the contrast image contrast = data["data"]["contrast"][:, :] # Getting the point cloud point_cloud = np.dstack([xyz, rgb, contrast]) # Flattening the point cloud flattened_point_cloud = point_cloud.reshape(-1, 7) # Just the points without color and contrast # pc = np.dstack([xyz]) # flattened_point_cloud = pc.reshape(-1,3) # Removing nans flattened_point_cloud = flattened_point_cloud[ ~np.isnan(flattened_point_cloud[:, 0]), : ] print(f"Saving the frame to {filename_txt}") np.savetxt(filename_txt, flattened_point_cloud, delimiter=" ", fmt="%.3f") if __name__ == "__main__": _main()
[ "numpy.dstack", "netCDF4.Dataset", "numpy.savetxt", "numpy.isnan", "pathlib.Path" ]
[((758, 789), 'numpy.dstack', 'np.dstack', (['[xyz, rgb, contrast]'], {}), '([xyz, rgb, contrast])\n', (767, 789), True, 'import numpy as np\n'), ((1184, 1258), 'numpy.savetxt', 'np.savetxt', (['filename_txt', 'flattened_point_cloud'], {'delimiter': '""" """', 'fmt': '"""%.3f"""'}), "(filename_txt, flattened_point_cloud, delimiter=' ', fmt='%.3f')\n", (1194, 1258), True, 'import numpy as np\n'), ((265, 271), 'pathlib.Path', 'Path', ([], {}), '()\n', (269, 271), False, 'from pathlib import Path\n'), ((413, 434), 'netCDF4.Dataset', 'Dataset', (['filename_zdf'], {}), '(filename_zdf)\n', (420, 434), False, 'from netCDF4 import Dataset\n'), ((1083, 1120), 'numpy.isnan', 'np.isnan', (['flattened_point_cloud[:, 0]'], {}), '(flattened_point_cloud[:, 0])\n', (1091, 1120), True, 'import numpy as np\n')]
import warnings import numpy as np import pandas as pd import numpy.random rg = numpy.random.default_rng() import scipy.optimize import scipy.stats as st import tqdm import bebi103 try: import multiprocess except: import multiprocessing as multiprocess def CDF_double_exp(beta_1, beta_2, t): frac = beta_1 * beta_2 / (beta_2 - beta_1) b1 = (1 - np.exp(-beta_1 * t)) / beta_1 b2 = (1 - np.exp(-beta_2 * t)) / beta_2 return frac * (b1 - b2) def log_likelihood(n, beta_1, d_beta): like = [] for t in n: p1 = np.log(beta_1 * (beta_1 + d_beta) / d_beta) p2 = -beta_1 * t p3 = np.log(1 - np.exp(-d_beta * t)) like.append(p1 + p2 + p3) return like def gen_microtubule(b1, db, size, rg): beta_1 = b1 beta_2 = db + b1 return rg.exponential(1/beta_1, size=size) + rg.exponential(1/beta_2, size=size) def log_like_microtubule(params, n): """Log likelihood for the microtubule time to catastrophe measurements, parametrized by beta_1, d_beta.""" beta_1, d_beta = params # limits: # beta_1 >= 0 # d_beta >= 0 if beta_1 < 0 or d_beta < 0: return -np.inf return np.sum(log_likelihood(n, beta_1, d_beta)) def mle_microtubule(n): """Perform maximum likelihood estimates for parameters for the microtubule time to catastrophe measurements, parametrized by beta_1, d_beta""" with warnings.catch_warnings(): warnings.simplefilter("ignore") res = scipy.optimize.minimize( fun=lambda params, n: -log_like_microtubule(params, n), x0=np.array([3, 3]), args=(n,), method='Powell' ) if res.success: return res.x else: raise RuntimeError('Convergence failed with message', res.message)
[ "warnings.simplefilter", "numpy.log", "numpy.array", "numpy.exp", "warnings.catch_warnings" ]
[((547, 590), 'numpy.log', 'np.log', (['(beta_1 * (beta_1 + d_beta) / d_beta)'], {}), '(beta_1 * (beta_1 + d_beta) / d_beta)\n', (553, 590), True, 'import numpy as np\n'), ((1406, 1431), 'warnings.catch_warnings', 'warnings.catch_warnings', ([], {}), '()\n', (1429, 1431), False, 'import warnings\n'), ((1441, 1472), 'warnings.simplefilter', 'warnings.simplefilter', (['"""ignore"""'], {}), "('ignore')\n", (1462, 1472), False, 'import warnings\n'), ((362, 381), 'numpy.exp', 'np.exp', (['(-beta_1 * t)'], {}), '(-beta_1 * t)\n', (368, 381), True, 'import numpy as np\n'), ((406, 425), 'numpy.exp', 'np.exp', (['(-beta_2 * t)'], {}), '(-beta_2 * t)\n', (412, 425), True, 'import numpy as np\n'), ((640, 659), 'numpy.exp', 'np.exp', (['(-d_beta * t)'], {}), '(-d_beta * t)\n', (646, 659), True, 'import numpy as np\n'), ((1596, 1612), 'numpy.array', 'np.array', (['[3, 3]'], {}), '([3, 3])\n', (1604, 1612), True, 'import numpy as np\n')]
# Create cover permeability layer # Script written in Python 3.7 import config as config import numpy as np import pandas as pd from scipy import ndimage from soil_merger import readHeader import importlib importlib.reload(config) # ====================================================================================================================== # ======================================================================= # Load data # ======================================================================= # Imports # ================================ # Stands stands_path = str(config.cover_type_velma) cover_key = pd.read_csv(str(config.cover_type_velma.parents[0] / 'cover_type_key.csv')) stands = np.loadtxt(stands_path, skiprows=6) outfile = config.cover_type_velma.parents[0] / 'permeability.asc' # ================================ # NOAA C-CAP ccap_path = str(config.noaa_ccap_velma) ccap = np.loadtxt(ccap_path, skiprows=6) ccap = ccap + 100 # CCAP class values ccap_NA = 100 ccap_herby = 101 ccap_dirt = 102 ccap_developed = 103 ccap_water = 104 ccap_forest = 105 ccap_shrub = 106 # ================================ # NLCD nlcd_path = str(config.nlcd_velma) nlcd = np.loadtxt(nlcd_path, skiprows=6) nlcd = nlcd + 100 # NLCD class values nlcd_open_water = 111 nlcd_dev_openspace = 121 nlcd_dev_low = 122 nlcd_dev_med = 123 nlcd_dev_high = 124 nlcd_barren = 131 nlcd_forest_decid = 141 nlcd_forest_evergreen = 142 nlcd_forest_mixed = 143 nlcd_shrub = 152 nlcd_herby = 171 nlcd_woody_wet = 190 nlcd_emerg_herb_wet = 195 # Erode NLCD roads by 1 pixel - they look to be about 10-20m, not 30m road_mask = (nlcd == nlcd_dev_openspace) + (nlcd == nlcd_dev_low) roads = ndimage.binary_erosion(road_mask, iterations=1) # Combine CCAP developed with NLCD roads roads_merge = roads + (ccap == ccap_developed) + (ccap == ccap_dirt) # Convert to % permeability perm_fraction = 0.5 # % permeability of roads perm = np.invert(roads_merge) * 1 perm = np.where(perm == 0, 0.5, perm) header = readHeader(nlcd_path) f = open(outfile, "w") f.write(header) np.savetxt(f, perm, fmt="%f") f.close()
[ "scipy.ndimage.binary_erosion", "numpy.invert", "numpy.savetxt", "soil_merger.readHeader", "importlib.reload", "numpy.where", "numpy.loadtxt" ]
[((208, 232), 'importlib.reload', 'importlib.reload', (['config'], {}), '(config)\n', (224, 232), False, 'import importlib\n'), ((710, 745), 'numpy.loadtxt', 'np.loadtxt', (['stands_path'], {'skiprows': '(6)'}), '(stands_path, skiprows=6)\n', (720, 745), True, 'import numpy as np\n'), ((908, 941), 'numpy.loadtxt', 'np.loadtxt', (['ccap_path'], {'skiprows': '(6)'}), '(ccap_path, skiprows=6)\n', (918, 941), True, 'import numpy as np\n'), ((1186, 1219), 'numpy.loadtxt', 'np.loadtxt', (['nlcd_path'], {'skiprows': '(6)'}), '(nlcd_path, skiprows=6)\n', (1196, 1219), True, 'import numpy as np\n'), ((1685, 1732), 'scipy.ndimage.binary_erosion', 'ndimage.binary_erosion', (['road_mask'], {'iterations': '(1)'}), '(road_mask, iterations=1)\n', (1707, 1732), False, 'from scipy import ndimage\n'), ((1961, 1991), 'numpy.where', 'np.where', (['(perm == 0)', '(0.5)', 'perm'], {}), '(perm == 0, 0.5, perm)\n', (1969, 1991), True, 'import numpy as np\n'), ((2002, 2023), 'soil_merger.readHeader', 'readHeader', (['nlcd_path'], {}), '(nlcd_path)\n', (2012, 2023), False, 'from soil_merger import readHeader\n'), ((2063, 2092), 'numpy.savetxt', 'np.savetxt', (['f', 'perm'], {'fmt': '"""%f"""'}), "(f, perm, fmt='%f')\n", (2073, 2092), True, 'import numpy as np\n'), ((1927, 1949), 'numpy.invert', 'np.invert', (['roads_merge'], {}), '(roads_merge)\n', (1936, 1949), True, 'import numpy as np\n')]
# Code for "ActionCLIP: ActionCLIP: A New Paradigm for Action Recognition" # arXiv: # <NAME>, <NAME>, <NAME> import numpy as np import pytest import torch from PIL import Image import clip @pytest.mark.parametrize('model_name', clip.available_models()) def test_consistency(model_name): device = "cpu" jit_model, transform = clip.load(model_name, device=device) py_model, _ = clip.load(model_name, device=device, jit=False) image = transform(Image.open("CLIP.png")).unsqueeze(0).to(device) text = clip.tokenize(["a diagram", "a dog", "a cat"]).to(device) with torch.no_grad(): logits_per_image, _ = jit_model(image, text) jit_probs = logits_per_image.softmax(dim=-1).cpu().numpy() logits_per_image, _ = py_model(image, text) py_probs = logits_per_image.softmax(dim=-1).cpu().numpy() assert np.allclose(jit_probs, py_probs, atol=0.01, rtol=0.1)
[ "clip.available_models", "numpy.allclose", "clip.tokenize", "clip.load", "PIL.Image.open", "torch.no_grad" ]
[((337, 373), 'clip.load', 'clip.load', (['model_name'], {'device': 'device'}), '(model_name, device=device)\n', (346, 373), False, 'import clip\n'), ((392, 439), 'clip.load', 'clip.load', (['model_name'], {'device': 'device', 'jit': '(False)'}), '(model_name, device=device, jit=False)\n', (401, 439), False, 'import clip\n'), ((858, 911), 'numpy.allclose', 'np.allclose', (['jit_probs', 'py_probs'], {'atol': '(0.01)', 'rtol': '(0.1)'}), '(jit_probs, py_probs, atol=0.01, rtol=0.1)\n', (869, 911), True, 'import numpy as np\n'), ((232, 255), 'clip.available_models', 'clip.available_models', ([], {}), '()\n', (253, 255), False, 'import clip\n'), ((590, 605), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (603, 605), False, 'import torch\n'), ((522, 568), 'clip.tokenize', 'clip.tokenize', (["['a diagram', 'a dog', 'a cat']"], {}), "(['a diagram', 'a dog', 'a cat'])\n", (535, 568), False, 'import clip\n'), ((463, 485), 'PIL.Image.open', 'Image.open', (['"""CLIP.png"""'], {}), "('CLIP.png')\n", (473, 485), False, 'from PIL import Image\n')]
import numpy as np top1 = 0 top5 = 0 top1_wc = 0 top5_wc = 0 top1_cnt = 0 num_act = 0 num_cnt = 0 dataset = 'gtea2salad' for n_split in range(5, 6): n_split = str(n_split) corr_numact = [0, 0, 0, 0, 0, 0, 0] num_numact = [0, 0, 0, 0, 0, 0, 0] corr_1 = 0 corr_5 = 0 corr_1_wcnt = 0 corr_5_wcnt = 0 corr_1_cnt = 0 final_act_1 = np.load("./prompt_test/"+dataset+"/split"+n_split+"/final_act_1.npy") final_act_5 = np.load("./prompt_test/"+dataset+"/split"+n_split+"/final_act_5.npy") final_cnt = np.load("./prompt_test/"+dataset+"/split"+n_split+"/final_cnt_1.npy") gt_act = np.load("./prompt_test/"+dataset+"/split"+n_split+"/gt_act.npy") gt_cnt = gt_act >= 0 gt_cnt = np.sum(gt_cnt, axis=1) num_cnt += len(gt_cnt) for i in range(len(gt_cnt)): num_act += gt_cnt[i] num_numact[gt_cnt[i]] += gt_cnt[i] corr_now = 0 for k in range(gt_cnt[i]): if final_act_1[i][k] == gt_act[i][k]: corr_1 += 1 corr_now += 1 if gt_act[i][k] in final_act_5[i][k]: corr_5 += 1 corr_numact[gt_cnt[i]] += corr_now for k in range(final_cnt[i][0]): if final_act_1[i][k] == gt_act[i][k]: corr_1_wcnt += 1 if gt_act[i][k] in final_act_5[i][k]: corr_5_wcnt += 1 for i in range(len(gt_cnt)): if final_cnt[i][0] == gt_cnt[i]: corr_1_cnt += 1 top1 += float(corr_1) top5 += float(corr_5) top1_wc += float(corr_1_wcnt) top5_wc += float(corr_5_wcnt) top1_cnt += float(corr_1_cnt) num_numact = [i if i != 0 else 1 for i in num_numact] top1_numact = [float(corr_numact[i]) / num_numact[i] * 100 for i in range(1, len(num_numact))] top1 /= num_act top5 /= num_act top1_wc /= num_act top5_wc /= num_act top1_cnt /= num_cnt print('Top1: {}/{}, Top5: {}/{}, Top1_cnt: {}'.format(top1, top1_wc, top5, top5_wc, top1_cnt))
[ "numpy.load", "numpy.sum" ]
[((363, 440), 'numpy.load', 'np.load', (["('./prompt_test/' + dataset + '/split' + n_split + '/final_act_1.npy')"], {}), "('./prompt_test/' + dataset + '/split' + n_split + '/final_act_1.npy')\n", (370, 440), True, 'import numpy as np\n'), ((451, 528), 'numpy.load', 'np.load', (["('./prompt_test/' + dataset + '/split' + n_split + '/final_act_5.npy')"], {}), "('./prompt_test/' + dataset + '/split' + n_split + '/final_act_5.npy')\n", (458, 528), True, 'import numpy as np\n'), ((537, 614), 'numpy.load', 'np.load', (["('./prompt_test/' + dataset + '/split' + n_split + '/final_cnt_1.npy')"], {}), "('./prompt_test/' + dataset + '/split' + n_split + '/final_cnt_1.npy')\n", (544, 614), True, 'import numpy as np\n'), ((620, 692), 'numpy.load', 'np.load', (["('./prompt_test/' + dataset + '/split' + n_split + '/gt_act.npy')"], {}), "('./prompt_test/' + dataset + '/split' + n_split + '/gt_act.npy')\n", (627, 692), True, 'import numpy as np\n'), ((723, 745), 'numpy.sum', 'np.sum', (['gt_cnt'], {'axis': '(1)'}), '(gt_cnt, axis=1)\n', (729, 745), True, 'import numpy as np\n')]
# standard library imports import os import re # third party import numpy as np # local application imports from pygsm import utilities from .base_lot import Lot from .file_options import File_Options class BAGEL(Lot): def __init__(self,options): super(BAGEL,self).__init__(options) print(" making folder scratch/{}".format(self.node_id)) os.system('mkdir -p scratch/{}'.format(self.node_id)) # regular options self.file_options.set_active('basis','6-31g',str,'') self.file_options.set_active('df_basis','svp-jkfit',str,'') self.file_options.set_active('maxiter',200,int,'') # CASSCF self.file_options.set_active('casscf',None,bool,'') self.file_options.set_active('nstate',None,int,'') self.file_options.set_active('nact',None,int,'') self.file_options.set_active('nclosed',None,int,'') # CASPT2 options self.file_options.set_active('caspt2',None,bool,'',depend=(self.file_options.casscf),msg='casscf must be True') self.file_options.set_active('ms',True,bool,'',depend=(self.file_options.caspt2),msg='') self.file_options.set_active('xms',True,bool,'',depend=(self.file_options.caspt2),msg='') self.file_options.set_active('sssr',False,bool,'',depend=(self.file_options.caspt2),msg='') self.file_options.set_active('shift',0.3,float,'',depend=(self.file_options.caspt2),msg='') self.file_options.set_active('frozen',True,bool,'',depend=(self.file_options.caspt2),msg='') keys_to_del=[] for key,value in self.file_options.ActiveOptions.items(): if value is None: keys_to_del.append(key) for key in keys_to_del: self.file_options.deactivate(key) if "casscf" in self.file_options.ActiveOptions: for key in ['nstate','nact','nclosed']: if key not in self.file_options.ActiveOptions: raise RuntimeError keys_to_del=[] if "caspt2" not in self.file_options.ActiveOptions: for key in ['ms','xms','sssr','shift','frozen']: print('deactivating key ',key) keys_to_del.append(key) for key in keys_to_del: self.file_options.deactivate(key) guess_file='scratch/{}/orbs'.format(self.node_id) self.file_options.set_active('load_ref',guess_file,str,doc='guess', depend=(os.path.isfile(guess_file+'.archive')),msg='ref does not exist or not needed, deactivating for now...') if self.node_id==0: for line in self.file_options.record(): print(line) # set all active values to self for easy access for key in self.file_options.ActiveOptions: setattr(self, key, self.file_options.ActiveOptions[key]) @classmethod def copy(cls,lot,options,copy_wavefunction=True): # Get node id for new struct node_id = options.get('node_id',1) print(" making folder scratch/{}".format(node_id)) os.system('mkdir -p scratch/{}'.format(node_id)) file_options = File_Options.copy(lot.file_options) options['file_options'] = file_options if node_id != lot.node_id and copy_wavefunction: old_path = 'scratch/{}/orbs.archive'.format(lot.node_id) new_path = 'scratch/{}/orbs.archive'.format(node_id) cmd = 'cp -r ' + old_path +' ' + new_path print(" copying scr files\n {}".format(cmd)) os.system(cmd) os.system('wait') return cls(lot.options.copy().set_values(options)) def write_input(self,geom,runtype='gradient'): # filenames inpfilename = 'scratch/{}/bagel.json'.format(self.node_id) inpfile = open(inpfilename,'w') # Header inpfile.write('{ "bagel" : [\n\n') # molecule section inpfile.write(('{\n' ' "title" : "molecule",\n')) # basis set inpfile.write(' "basis" : "{}",\n'.format(self.basis)) inpfile.write(' "df_basis" : "{}",\n'.format(self.df_basis)) inpfile.write('"angstrom" : true,\n') # write geometry inpfile.write(' "geometry" : [\n') for atom in geom[:-1]: inpfile.write(' { "atom" : "%s", "xyz" : [ %14.6f, %14.6f, %14.6f ] },\n' % ( atom[0], atom[1], atom[2], atom[3], )) inpfile.write(' { "atom" : "%s", "xyz" : [ %14.6f, %14.6f, %14.6f ] }\n' % ( geom[-1][0], geom[-1][1], geom[-1][2], geom[-1][3], )) inpfile.write(']\n') inpfile.write('},\n') # Load reference if 'load_ref' in self.file_options.ActiveOptions: inpfile.write(('{{ \n' ' "title" : "load_ref", \n' ' "file" : "scratch/{}/orbs", \n' ' "continue_geom" : false \n}},\n'.format(self.node_id))) if "casscf" in self.file_options.ActiveOptions: inpfile.write(('{{\n' ' "title" : "casscf", \n' ' "nstate" : {}, \n' ' "nact" : {}, \n' ' "nclosed" : {}, \n' ' "maxiter": {} \n' ' }},\n\n'.format(self.nstate,self.nact,self.nclosed,self.maxiter))) else: print(" only casscf implemented now") raise NotImplementedError if runtype=="gradient": inpfile.write(('{\n' ' "title" : "forces",\n')) inpfile.write(' "grads" : [\n') num_states = len(self.gradient_states) for i,state in enumerate(self.gradient_states): if i+1==num_states: inpfile.write(' {{ "title" : "force", "target" : {} }}\n'.format(state[1])) else: inpfile.write(' {{ "title" : "force", "target" : {} }},\n'.format(state[1])) inpfile.write(' \n],\n') elif runtype=="gh": inpfile.write(('{\n' ' "title" : "forces",\n')) inpfile.write(' "grads" : [\n') num_states = len(self.gradient_states) for i,state in enumerate(self.gradient_states): inpfile.write(' {{ "title" : "force", "target" : {} }},\n'.format(state[1])) inpfile.write(' {{ "title" : "nacme", "target1" : {}, "tartet2": {}, "nacmtype" : "full" }}\n'.format(self.coupling_states[0],self.coupling_states[1])) inpfile.write(' ],\n') if "caspt2" in self.file_options.ActiveOptions and (runtype=='gh' or runtype=='gradient'): inpfile.write((' "method" : [ {{\n' ' "title" : "caspt2",\n' ' "smith" : {{\n' ' "method" : "caspt2",\n' ' "ms" : "{}",\n' ' "xms" : "{}",\n' ' "sssr" : "{}",\n' ' "shift" : {},\n' ' "frozen" : "{}"\n' ' }},\n' ' "nstate" : {},\n' ' "nact" : {},\n' ' "nclosed" : {},\n' ' "charge" : 0\n' ' }} ]\n' '}},\n'.format(self.ms,self.xms,self.sssr,self.shift,self.frozen,self.nstate,self.nact,self.nclosed))) elif runtype=='energy': pass else: print("only caspt2 gradient implemented") raise NotImplementedError inpfile.write(('{{\n' '"title" : "save_ref",\n' '"file" : "scratch/{}/orbs"\n' '}}\n'.format(self.node_id))) inpfile.write(']}') inpfile.close() def parse(self,geom,runtype='gradient'): self.Gradients={} self.Energies = {} self.Couplings = {} # Parse the output for Energies tempfileout='scratch/{}/output.dat'.format(self.node_id) tmp =[] if "caspt2" in self.file_options.ActiveOptions: pattern = re.compile(r'\s. MS-CASPT2 energy : state \d \s* ([-+]?[0-9]*\.?[0-9]+)') for line in open(tempfileout): for match in re.finditer(pattern,line): tmp.append(float(match.group(1))) else: print("CASSCF not currently enabled") for i in self.states: tmp.append(0.0) for E,state in zip(tmp,self.states): self._Energies[state] = self.Energy(E,'Hartree') # Save to file self.write_E_to_file() # Parse the output for Gradients if runtype=="gradient" or runtype=='gh': tmpgrada=[] tmpgrad = [] tmpcoup = [] count=1 with open(tempfileout,"r") as f: for line in f: if line.startswith("* Nuclear energy gradient",2) and count<3: next(f) for i in range((len(geom)*4)): findline = next(f,'').strip() if findline.startswith("o Atom"): pass else: mobj = re.match(r'. \s* ([-+]?[0-9]*\.?[0-9]+)', findline) tmpgrad.append(float(mobj.group(1))) tmpgrada.append(np.asarray(tmpgrad)) tmpgrad = [] count+=1 elif line.startswith("* Nuclear energy gradient",2) and count==3 and runtype=='gh': next(f) for i in range((len(geom)*4)): findline = next(f,'').strip() if findline.startswith("o Atom"): pass else: mobj = re.match(r'. \s* ([-+]?[0-9]*\.?[0-9]+)', findline) tmpcoup.append(float(mobj.group(1))) self.Couplings[self.coupling_states] = self.Coupling(np.asarray(tmpcoup),'Hartree/Bohr') break for tup,tmpgrad in zip(self.gradient_states,tmpgrada): self._Gradients[tup] = self.Gradient(tmpgrad,'Hartree/Bohr') def run(self,geom,runtype='gradient'): # first write the file, run it, and the read the output inpfilename = 'scratch/{}/bagel.json'.format(self.node_id) outfilename = 'scratch/{}/output.dat'.format(self.node_id) # Write self.write_input(geom,runtype) # Run BAGEL ### RUN THE CALCULATION ### cmd = "BAGEL {} > {}".format(inpfilename,outfilename) os.system(cmd) os.system('wait') # Parse the output for Energies self.parse(geom,runtype) # Turn on guess for calculations after running if 'load_ref' not in self.file_options.ActiveOptions: self.file_options.set_active('load_ref','scratch/{}/orbs'.format(self.node_id),str,'') return def runall(self,geom,runtype=None): ''' calculate all states with BAGEL ''' tempfileout='scratch/{}/output.dat'.format(self.node_id) if (not self.gradient_states and not self.coupling_states) or runtype=='energy': print(" only calculating energies") # TODO what about multiple multiplicities? tup = self.states[0] self.run(geom,'energy') # make grada all None for tup in self.states: self._Gradients[tup] = self.Gradients(None,None) elif self.gradient_states and self.coupling_states or runtype=='gh': self.run(geom,'gh') elif self.gradient_states and not self.coupling_states or runtype=='gradient': self.run(geom,'gradient') else: raise RuntimeError self.hasRanForCurrentCoords=True return if __name__=="__main__": geom=utilities.manage_xyz.read_xyz('../../data/ethylene.xyz') #,units.ANGSTROM_TO_AU) B = BAGEL.from_options(states=[(1,0),(1,1)],gradient_states=[(1,0),(1,1)],coupling_states=(0,1),geom=geom,lot_inp_file='bagel.txt',node_id=0) coords = utilities.manage_xyz.xyz_to_np(geom) E0 = B.get_energy(coords,1,0) E1 = B.get_energy(coords,1,1) g0 = B.get_gradient(coords,1,0) g1 = B.get_gradient(coords,1,1) c = B.get_coupling(coords,1,0,1) print(E0,E1) print(g0.T) print(g1.T) print(c.T) #for line in B.file_options.record(): # print(line) #for key,value in B.file_options.ActiveOptions.items(): # print(key,value)
[ "re.finditer", "numpy.asarray", "pygsm.utilities.manage_xyz.xyz_to_np", "os.system", "re.match", "os.path.isfile", "pygsm.utilities.manage_xyz.read_xyz", "re.compile" ]
[((11988, 12044), 'pygsm.utilities.manage_xyz.read_xyz', 'utilities.manage_xyz.read_xyz', (['"""../../data/ethylene.xyz"""'], {}), "('../../data/ethylene.xyz')\n", (12017, 12044), False, 'from pygsm import utilities\n'), ((12229, 12265), 'pygsm.utilities.manage_xyz.xyz_to_np', 'utilities.manage_xyz.xyz_to_np', (['geom'], {}), '(geom)\n', (12259, 12265), False, 'from pygsm import utilities\n'), ((10716, 10730), 'os.system', 'os.system', (['cmd'], {}), '(cmd)\n', (10725, 10730), False, 'import os\n'), ((10739, 10756), 'os.system', 'os.system', (['"""wait"""'], {}), "('wait')\n", (10748, 10756), False, 'import os\n'), ((3540, 3554), 'os.system', 'os.system', (['cmd'], {}), '(cmd)\n', (3549, 3554), False, 'import os\n'), ((3567, 3584), 'os.system', 'os.system', (['"""wait"""'], {}), "('wait')\n", (3576, 3584), False, 'import os\n'), ((8026, 8103), 're.compile', 're.compile', (['"""\\\\s. MS-CASPT2 energy : state \\\\d \\\\s* ([-+]?[0-9]*\\\\.?[0-9]+)"""'], {}), "('\\\\s. MS-CASPT2 energy : state \\\\d \\\\s* ([-+]?[0-9]*\\\\.?[0-9]+)')\n", (8036, 8103), False, 'import re\n'), ((2458, 2497), 'os.path.isfile', 'os.path.isfile', (["(guess_file + '.archive')"], {}), "(guess_file + '.archive')\n", (2472, 2497), False, 'import os\n'), ((8173, 8199), 're.finditer', 're.finditer', (['pattern', 'line'], {}), '(pattern, line)\n', (8184, 8199), False, 'import re\n'), ((9368, 9387), 'numpy.asarray', 'np.asarray', (['tmpgrad'], {}), '(tmpgrad)\n', (9378, 9387), True, 'import numpy as np\n'), ((9207, 9259), 're.match', 're.match', (['""". \\\\s* ([-+]?[0-9]*\\\\.?[0-9]+)"""', 'findline'], {}), "('. \\\\s* ([-+]?[0-9]*\\\\.?[0-9]+)', findline)\n", (9215, 9259), False, 'import re\n'), ((10078, 10097), 'numpy.asarray', 'np.asarray', (['tmpcoup'], {}), '(tmpcoup)\n', (10088, 10097), True, 'import numpy as np\n'), ((9880, 9932), 're.match', 're.match', (['""". \\\\s* ([-+]?[0-9]*\\\\.?[0-9]+)"""', 'findline'], {}), "('. \\\\s* ([-+]?[0-9]*\\\\.?[0-9]+)', findline)\n", (9888, 9932), False, 'import re\n')]
import os import pdb import h5py import pickle import numpy as np from scipy.io import loadmat import cv2 import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from PIL import Image from PIL import ImageFont from PIL import ImageDraw import csv import matplotlib as mpl import matplotlib.cm as cm import tensorflow as tf # from bilateral_filter import bilateral_filter from tools import * def read_csv(path): with open(path, mode='r') as csv_file: csv_reader = csv.DictReader(csv_file) line_count = 0 for row in csv_reader: if line_count == 0: print(f'Column names are {", ".join(row)}') line_count += 1 import pdb; pdb.set_trace() line_count += 1 print(f'Processed {line_count} lines.') def debug_convert(): img_path = '/home/jiatian/dataset/tum/sequence_01/000001.jpg' img = tf.read_file(img_path) img_gray = tf.image.decode_jpeg(img) img_v1 = tf.image.decode_jpeg(img, channels=3) img_v2 = tf.image.grayscale_to_rgb(img_gray) with tf.Session() as sess: np_img_v1 = sess.run(img_v1) np_img_v2 = sess.run(img_v2) def read_imu_data(): data_path = '/home/jiatian/dataset/office_kitchen_0001a/a-1315403270.593277-3849079182.dump' # with open(data_path, 'rb') as f: # data = pickle.load(f) f = open(data_path, 'r') pdb.set_trace() def resave_imu_data(): dataset = '/freezer/nyudepthV2_raw' seqs = os.listdir(dataset) for seq in seqs: seq_dir = dataset + '/' + seq for data in os.listdir(seq_dir): if data[0] == 'a': imu_data_path = seq_dir + '/' + data resave_imu_data_path = seq_dir + '/' + data[:-4] + '.txt' call_resave_imu(imu_data_path, resave_imu_data_path) def call_resave_imu(orig_path, resave_path): command = './resave_imu ' + orig_path + ' ' + resave_path os.system(command) def collect_acc_data(folder): data_list = [] for file in os.listdir(folder): if file[0] == 'a' and file[-1] == 't': data_list.append(folder + '/' + file) return sorted(data_list) def get_acc_timestamp(path): return float(path.split('-')[1]) def read_acc_data(file_path): timestamp = get_acc_timestamp(file_path) file = open(file_path, 'r') data = file.read().split(',') for i in range(len(data)): data[i] = float(data[i]) data.insert(0, timestamp) return data def plot_acc_data(folder): acc_path = collect_acc_data(folder) x = [] y = [] z = [] for path in acc_path: data = read_acc_data(path) x.append(data[1]) y.append(data[2]) z.append(data[3]) plt.plot(x) plt.plot(y) plt.plot(z) plt.show() def compute_acc_vel_pos(acc_data_1, acc_data_2, v_1, p_1): t1 = acc_data_1[0] t2 = acc_data_2[0] t_delta = t2 - t1 acc_xyz_1 = np.array(acc_data_1[1:4]) acc_xyz_2 = np.array(acc_data_2[1:4]) a_avg = (acc_xyz_1 + acc_xyz_2) / 2. v_2 = v_1 + a_avg * t_delta p_2 = p_1 + v_1 * t_delta + a_avg * t_delta * t_delta / 2. # pdb.set_trace() return v_2, p_2 def plot_imu_traj(folder): acc_path = collect_acc_data(folder) p_x = [] p_y = [] p_z = [] v_cur = np.array([0., 0., 0.]) p_cur = np.array([0., 0., 0.]) N = len(acc_path) for idx in range(N-1): p_x.append(p_cur[0]) p_y.append(p_cur[1]) p_z.append(p_cur[2]) acc_1 = read_acc_data(acc_path[idx]) acc_2 = read_acc_data(acc_path[idx + 1]) v_cur, p_cur = compute_acc_vel_pos(acc_1, acc_2, v_cur, p_cur) fig = plt.figure() ax = fig.add_subplot(111, projection='3d') #ax.scatter(p_x[:], p_y[:], p_z[:0]) ax.plot(p_x[:-1], p_y[:-1], p_z[:-1]) ax.set_xlabel('X Label') ax.set_ylabel('Y Label') ax.set_zlabel('Z Label') plt.show() # plt.plot(p_x) # plt.plot(p_y) # plt.plot(p_z) # plt.show() def read_amazon_data(data_file_name): data = open(data_file_name, "rb") rgbd = pickle.load(data) rgb = rgbd['rgb'] rgb_new = np.zeros(rgb.shape, dtype=np.uint8) xx, yy = np.meshgrid(np.arange(0, 640, 1), np.arange(0, 480, 1), sparse=False) for i in range(0, 640, 1): for j in range(0, 480, 1): x_std, y_std = wrap_pixel(float(i), float(j)) x_std = round(x_std) y_std = round(y_std) if x_std >= 0 and x_std <= (640 - 1) and y_std >= 0 and y_std <= (480 - 1): rgb_new[y_std, x_std, :] = rgb[j, i, :] plt.imshow(np.hstack((rgb, rgb_new))) plt.show(block=True) def wrap_pixel(x, y): [fx_orig, fy_orig, cx_orig, cy_orig] = [ 400.516317, 400.410970, 320.171183, 243.274495] [fx_std, fy_std, cx_std, cy_std] = [ 518.857901, 519.469611, 325.582449, 253.736166] x_norm = (x - cx_orig) / fx_orig y_norm = (y - cy_orig) / fy_orig x_std = fx_std * x_norm + cx_std y_std = fy_std * y_norm + cy_std return x_std, y_std def vis_depth(depth_map): vmax = np.percentile(depth_map, 90) vmin = depth_map.min() normalizer = mpl.colors.Normalize(vmin=vmin, vmax=vmax) mapper = mpl.cm.ScalarMappable(norm=normalizer, cmap='viridis') colormapped_im = (mapper.to_rgba(depth_map)[ :, :, :3][:, :, ::-1] * 255).astype(np.uint8) return colormapped_im[:, :, ::-1] def vis_float_image(folder): seqs = sorted(os.listdir(folder)) idx = 0 for seq in seqs: if 'yml' in seq and idx >= 0: image_path = folder + '/' + seq # image = np.array(Image.open(image_path), dtype=np.float) fs = cv2.FileStorage(image_path, cv2.FILE_STORAGE_READ) image = fs.getNode('depth_map').mat() rgb_image = np.array(Image.open( '/home/jiatianwu/eval/eval_data/' + seq[:-4] + '.jpg')) # image_bf = bilateral_filter(rgb_image, image) image_bf = image depth_image = vis_depth(image_bf) image_save = np.vstack((rgb_image, depth_image)) Image.fromarray(image_save).save( '/home/jiatianwu/eval/eval_comp/' + seq[:-4] + '.jpg') # plt.imshow(vis_depth(image)) # plt.show() idx += 1 def vis_zcu_image(folder): seqs = sorted(os.listdir(folder)) idx = 0 for seq in seqs: data_path = folder + '/' + seq data = open(data_path, "rb") rgbd = pickle.load(data) rgb = rgbd['rgb'] depth_image = rgbd['depth'] depth_tflite_image = rgbd['tflite'] depth_vitis_image = rgbd['vitis'] image_show = np.vstack( (rgb, depth_image, depth_tflite_image, depth_vitis_image)) img = Image.fromarray(image_show) draw = ImageDraw.Draw(img) font = ImageFont.truetype("Agane.ttf", 32) draw.text((0, 0), "RGB Image", (255, 0, 0), font=font) draw.text((0, 480), "Depth Image before Quantization", (255, 0, 0), font=font) draw.text((0, 960), "Depth Image post-quantization \n EdgeTPU", (255, 0, 0), font=font) draw.text((0, 1440), "Depth Image post-quantization \n DPU", (255, 0, 0), font=font) img.save('saved_images/' + str(idx).zfill(6) + '.jpg') # plt.imshow(image_show) # plt.show(block=False) # plt.pause(0.001) # plt.clf() idx += 1 def process_tello(folder): seqs = sorted(os.listdir(folder)) for idx in range(0, len(seqs), 5): data_path = folder + '/' + str(idx).zfill(6) + '.jpg' image = Image.open(data_path).resize((640, 480)) image.save('/home/jiatianwu/dataset/tello_vga/' + str(int(idx/5)).zfill(6) + '.jpg') data_dict = {'rgb': np.array(image)} dict_file_name = '/home/jiatianwu/dataset/tello_pickle/' + \ str(int(idx/5)).zfill(6) + '.pkl' f = open(dict_file_name, "wb") pickle.dump(data_dict, f) f.close() def vis_pickle_image(data_path): data = open(data_path, "rb") rgbd = pickle.load(data) rgb = rgbd['rgb'] depth_image = rgbd['depth'] depth_image_zcu = rgbd['tflite'] image_show = np.vstack((rgb, depth_image, depth_image_zcu)) img = Image.fromarray(image_show) draw = ImageDraw.Draw(img) # font = ImageFont.truetype(<font-file>, <font-size>) font = ImageFont.truetype("Agane.ttf", 32) # draw.text((x, y),"Sample Text",(r,g,b)) draw.text((0, 0), "Sample Text", (255, 0, 0), font=font) draw.text((0, 480), "Sample Text", (255, 0, 0), font=font) draw.text((0, 960), "Sample Text", (255, 0, 0), font=font) img.save('sample-out.jpg') # plt.imshow(image_show) # plt.show(block=True) def vis_folder(folder): dirlist = sorted(os.listdir(folder)) for seq in dirlist: image_path = folder + '/' + seq image = np.array(Image.open(image_path)) plt.imshow(image) plt.show(block=True) plt.pause(0.001) plt.clf() plt.close() def vis_image(path): image = Image.open(path) image = image.crop((0, 0, 1223, 699)).resize((608, 352)) image = np.array(image) plt.imshow(image) plt.show(block=True) plt.close() def vis_image_crop(path): image = Image.open(path) image = image.crop((0, 100, 1500, 900)) image = np.array(image) plt.imshow(image) plt.show(block=True) plt.close() def rename_folder(folder): dirlist = sorted(os.listdir(folder)) for seq in dirlist: if '_CAM' in seq: continue else: os.rename(folder + '/' + seq, folder + '/' + seq + '_CAM_FRONT') def rename_folder_util(folder): dirlist = sorted(os.listdir(folder)) idx = 0 for seq in dirlist: os.rename(folder + '/' + seq, folder + '/' + str(idx).zfill(6) + '.jpg') idx += 1 def rename_folder_image(folder): dirlist = sorted(os.listdir(folder)) idx = 0 for seq in dirlist: Image.open(folder + '/' + seq).save(folder + '/' + str(idx).zfill(6) + '.jpg') idx += 1 def convert_rgb_folder(folder): dirlist = sorted(os.listdir(folder)) for seq in dirlist: print('Processing: ', seq) imglist = sorted(os.listdir(folder + '/' + seq)) for img in imglist: if '.jpg' in img: img_path = folder + '/' + seq + '/' + img Image.open(img_path).convert('RGB').save(img_path) def plot_trajectory(data_file_name): data = open(data_file_name,"rb") poses_log = pickle.load(data) poses_mat_log = [] import torch for i in range(len(poses_log.keys())): pose = poses_log[i] pose = np.expand_dims(pose, axis=0) pose = np.expand_dims(pose, axis=0) pose_mat = transformation_from_parameters(torch.tensor(pose[:, :, :3]).float(), torch.tensor(pose[:, :, 3:]).float(), False) poses_mat_log.append(pose_mat.numpy()) xyzs = np.array(dump_xyz(poses_mat_log)) # save_path = '/home/nod/datasets/kitti_eval_1/2011_09_26_drive_0022_sync_02/xyz_log.npy' # np.save(save_path, xyzs) # xyzs = np.load( # '/home/nod/datasets/kitti_eval_1/2011_09_26_drive_0022_sync_02/xyz_log.npy') xs = [] ys = [] zs = [] for i in range(xyzs.shape[0]): xs.append(xyzs[i][0]) ys.append(xyzs[i][1]) zs.append(xyzs[i][2]) plt.plot(xs, ys) plt.savefig( '/home/jiatian/dataset/rs_eval/pose/' + str(i).zfill(6) + '.jpg') def vis_depth_pose(folder_depth, folder_pose): for i in range(792): depth_image = np.array(Image.open( folder_depth + '/' + str(i).zfill(6) + '.jpg')) pose_image = np.array(Image.open( folder_pose + '/' + str(i).zfill(6) + '.jpg')) tosave_image = np.vstack((depth_image, pose_image)) Image.fromarray(tosave_image).save( '/home/nod/datasets/kitti_eval_1/save_images/' + '/' + str(i).zfill(6) + '.jpg') def save_nyu_indoor_images(folder): dirlist = sorted(os.listdir(folder)) step = 0 for seq in dirlist: image_path = folder + '/' + seq image = Image.open(image_path).crop((0, 0, 640, 480)) image.save('/home/nod/tmp/' + str(step).zfill(6) + '.jpg') step += 1 def viz_resize(folder): dirlist = sorted(os.listdir(folder)) step = 0 for seq in dirlist: image_path = folder + '/' + seq image = Image.open(image_path).resize((320, 240)) image_dist = Image.open(image_path).resize((320, 200)) plt.imshow(np.vstack((np.array(image), np.array(image_dist)))) plt.show(block=True) def read_process_nyu_data(path): hf = h5py.File(path, 'r') images = np.array(hf.get('images')) depths = np.array(hf.get('depths')) return images, depths batch_size = depths.shape[0] for idx in range(batch_size): image = images[idx] depth = depths[idx] image = np.transpose(image, (2, 1, 0)) depth = np.transpose(depth, (1, 0)) data_dict = {'rgb': image, 'depth_gt': depth} data_file_name = '/home/nod/datasets/nyudepthV2/rgbd_data_gt/' + \ str(idx).zfill(6) + '.pkl' f = open(data_file_name, "wb") pickle.dump(data_dict, f) f.close() def generate_pointcloud(rgb, depth, intrinsics=None, ply_file=None): points = [] if intrinsics is not None: fx = intrinsics[0, 0] fy = intrinsics[1, 1] cx = intrinsics[0, 2] cy = intrinsics[1, 2] for v in range(rgb.shape[0]): for u in range(rgb.shape[1]): color = rgb[v, u, :] Z = depth[v, u] if Z == 0: continue if intrinsics is not None: X = (u - cx) * Z / fx Y = (v - cy) * Z / fy else: X = u Y = v points.append("%f %f %f %d %d %d 0\n" % (X, Y, Z, color[0], color[1], color[2])) file = open(ply_file, "w") file.write('''ply format ascii 1.0 element vertex %d property float x property float y property float z property uchar red property uchar green property uchar blue property uchar alpha end_header %s ''' % (len(points), "".join(points))) file.close() def generate_pc_nyudepth(input_folder, output_folder): P_rect = np.eye(3, 3) P_rect[0, 0] = 5.1885790117450188e+02 P_rect[0, 2] = 3.2558244941119034e+02 P_rect[1, 1] = 5.1946961112127485e+02 P_rect[1, 2] = 2.5373616633400465e+02 build_output_dir(output_folder) dirlist = sorted(os.listdir(input_folder)) step = 0 for seq in dirlist: print('Processing idx: ', step) data_path = input_folder + '/' + seq data = open(data_path, "rb") data_dict = pickle.load(data) rgb = data_dict['rgb'] depth_pred = data_dict['depth_pred'] * 0.002505729166737338 depth_gt = data_dict['depth_gt'] # pc_pred_path = output_folder + '/' + str(step).zfill(6) + '.ply' pc_gt_path = output_folder + '/' + str(step).zfill(6) + '_gt.ply' # generate_pointcloud(rgb, depth_pred, P_rect, ply_file=pc_pred_path) generate_pointcloud(rgb, depth_gt, P_rect, ply_file=pc_gt_path) step += 1 def generate_pc_media(input_folder, output_folder): build_output_dir(output_folder) dirlist = sorted(os.listdir(input_folder)) step = 1 for seq in dirlist: print('Processing idx: ', step) data_path = input_folder + '/' + seq data = open(data_path, "rb") data_dict = pickle.load(data) rgb = data_dict['rgb'] depth_pred = data_dict['depth'] pc_pred_path = output_folder + '/' + str(step).zfill(6) + '.ply' generate_pointcloud(rgb, depth_pred, intrinsics=None, ply_file=pc_pred_path) step += 1 def generate_pc_media_intrinsics(input_folder, output_folder): P_rect = np.eye(3, 3) P_rect[0, 0] = 296.91973631 P_rect[0, 2] = 321.97504478 P_rect[1, 1] = 297.37056543 P_rect[1, 2] = 225.25890346 build_output_dir(output_folder) dirlist = sorted(os.listdir(input_folder)) step = 0 for seq in dirlist: print('Processing idx: ', step) data_path = input_folder + '/' + seq data = open(data_path, "rb") data_dict = pickle.load(data) rgb = data_dict['rgb'] depth_pred = data_dict['depth'] pc_pred_path = output_folder + '/' + str(step).zfill(6) + '.ply' generate_pointcloud( rgb, depth_pred, intrinsics=P_rect, ply_file=pc_pred_path) step += 1 def generate_pc_kinect(input_folder, output_folder): P_rect = np.eye(3, 3) P_rect[0, 0] = 400.516317 P_rect[0, 2] = 320.171183 P_rect[1, 1] = 400.410970 P_rect[1, 2] = 243.274495 # build_output_dir(output_folder) # dirlist = sorted(os.listdir(input_folder)) # step = 0 # for seq in dirlist: # print('Processing idx: ', step) # data_path = input_folder + '/' + seq # data = open(data_path,"rb") # data_dict = pickle.load(data) # rgb = data_dict['rgb'] # depth_pred = data_dict['depth_pred'] * 1000 # depth_gt = data_dict['depth_gt'] # pc_pred_path = output_folder + '/' + str(step).zfill(6) + '.ply' # pc_gt_path = output_folder + '/' + str(step).zfill(6) + '_gt.ply' # generate_pointcloud(rgb, depth_pred, P_rect, ply_file=pc_pred_path) # generate_pointcloud(rgb, depth_gt, P_rect, ply_file=pc_gt_path) # step += 1 rgb = np.array(Image.open('/home/nod/project/dso/build/sample/00068.jpg')) depth_pred = np.array(Image.open( '/home/nod/project/dso/build/sample/00023.png')) * 6.66 pc_pred_path = '/home/nod/project/dso/build/sample/00068.ply' generate_pointcloud(rgb, depth_pred, intrinsics=P_rect, ply_file=pc_pred_path) def build_output_dir(output_dir): try: os.makedirs(output_dir, exist_ok=False) except: os.makedirs(output_dir, exist_ok=True) return output_dir def crop_folder(folder, output_dir): idx = 0 dirlist = sorted(os.listdir(folder)) for seq in dirlist: image_path = folder + '/' + seq image = Image.open(image_path) # kinect # image = image.crop((210, 110, 1700, 710)) image = image.crop((0, 100, 1500, 900)) # plt.imshow(image) # plt.show(block=True) # plt.pause(0.001) # plt.clf() image.save(output_dir + '/' + str(idx).zfill(6) + '.jpg') idx += 1 # plt.close() def readmat(filepath): annots = loadmat(filepath) import pdb pdb.set_trace() def save_nyu_eval_image(filepath): f = h5py.File(filepath) for k, v in f.items(): if k == 'images': image_source = np.array(v) batch_size = image_source.shape[0] for idx in range(batch_size): image = image_source[idx] image = np.transpose(image, (2, 1, 0)) Image.fromarray(image).save( '/home/nod/datasets/nyudepthV2/eval_data/' + str(idx).zfill(6) + '.jpg') def comp_nod_sgm(nod_folder, sgm_folder): nod_dirlist = sorted(os.listdir(nod_folder)) sgm_dirlist = sorted(os.listdir(sgm_folder)) batch_size = len(nod_dirlist) for idx in range(1900, batch_size): print('Processing ', idx) nod_image = np.array(Image.open(nod_folder + '/' + nod_dirlist[idx])) sgm_image = np.array(Image.open(sgm_folder + '/' + sgm_dirlist[idx])) nod_pred_image = nod_image[:, 640:, :] sgm_rgb_image = sgm_image[:, :1280, :] sgm_depth_image = sgm_image[:, 1280:, :] toshow_image = np.vstack( (sgm_rgb_image, np.hstack((nod_pred_image, sgm_depth_image)))) img = Image.fromarray(toshow_image) draw = ImageDraw.Draw(img) # font = ImageFont.truetype(<font-file>, <font-size>) font = ImageFont.truetype("Agane.ttf", 36) # draw.text((x, y),"Sample Text",(r,g,b)) draw.text((0, 0), "RGB Left", (255, 0, 0), font=font) draw.text((640, 0), "RGB Right", (255, 0, 0), font=font) draw.text((0, 480), "Nod Depth", (255, 0, 0), font=font) draw.text((640, 480), "SGBM", (255, 0, 0), font=font) img.save('/home/nod/datasets/weanhall/comp/' + str(idx).zfill(6) + '.jpg') def rename_folder_weanhall(folder): dirlist = sorted(os.listdir(folder)) idx = 0 for seq in dirlist: os.rename(folder + '/' + seq, folder + '/' + str(idx).zfill(6) + '.jpg') idx += 1 def rename_folder_tum(folder): dirlist = sorted(os.listdir(folder)) idx = 0 for seq in dirlist: os.rename(folder + '/' + seq, folder + '/' + str(idx).zfill(5) + '.jpg') idx += 1 def add_metrics_weanhall(nod_folder, sgm_folder, image_folder=None): path = image_folder image_left_path_list = [] image_right_path_list = [] image_list = sorted(os.listdir(path)) for image in image_list: if 'left' in image: image_left_path_list.append(path + '/' + image) else: image_right_path_list.append(path + '/' + image) dirlist = sorted(os.listdir(nod_folder)) batch_size = len(dirlist) cover_text = False for idx in range(1900, batch_size): nod_data_path = nod_folder + '/' + str(idx).zfill(6) + '.pkl' sgm_data_path = sgm_folder + '/' + str(idx).zfill(6) + '.pkl' nod_data = open(nod_data_path, "rb") nod_data_dict = pickle.load(nod_data) nod_depth = nod_data_dict['depth'] sgm_data = open(sgm_data_path, "rb") sgm_data_dict = pickle.load(sgm_data) sgm_depth = sgm_data_dict['depth'] image_left_path = image_left_path_list[idx] image_right_path = image_right_path_list[idx] image_left = np.array(Image.open(image_left_path)) image_right = np.array(Image.open(image_right_path)) nod_depth_image = vis_depth(nod_depth) sgm_depth_image = vis_depth(sgm_depth, percent=70) toshow_image = np.vstack((np.hstack((image_left, image_right)), np.hstack( (nod_depth_image, sgm_depth_image)))) res_dict = eval_depth_nod(nod_depth, sgm_depth, 0.1, 10) s_gt_cover_ratio = 'SGM cover ratio: ' + \ str(res_dict['gt_depth_cover_ratio']) + '%\n' s_pred_cover_ratio = 'NodDepth cover ratio: ' + \ str(res_dict['pred_depth_cover_ratio']) + '%\n' s_abs_rel = 'Absolute relative error: ' + \ '{:f}'.format(res_dict['abs_rel']) + '\n' s_sq_rel = 'Square relative error: ' + \ '{:f}'.format(res_dict['sq_rel']) + 'm\n' s_rms_99 = '99% Root mean squred error: ' + \ '{:f}'.format(res_dict['rms_99']) + 'm\n' s_rms_95 = '95% Root mean squred error: ' + \ '{:f}'.format(res_dict['rms_95']) + 'm\n' s_viz = s_gt_cover_ratio + s_pred_cover_ratio + \ s_abs_rel + s_sq_rel + s_rms_99 + s_rms_95 img = Image.fromarray(toshow_image) draw = ImageDraw.Draw(img) # font = ImageFont.truetype(<font-file>, <font-size>) font = ImageFont.truetype("Agane.ttf", 36) # draw.text((x, y),"Sample Text",(r,g,b)) draw.text((0, 0), "RGB Left", (255, 0, 0), font=font) draw.text((640, 0), "RGB Right", (255, 0, 0), font=font) draw.text((0, 480), "Nod Depth", (255, 0, 0), font=font) draw.text((640, 480), "SGBM", (255, 0, 0), font=font) plt.imshow(np.array(img)) plt.text(-550, 200, s_viz, fontsize=14) plt.axis('off') # plt.title(' Kinect Raw Input Nod Depth Kinect Depth', fontsize=24, loc='left') plt.show(block=False) plt.pause(0.01) plt.savefig('/home/nod/datasets/weanhall/eval_metrics/' + str(idx).zfill(6) + '.jpg') plt.clf() # image.save('/home/nod/datasets/weanhall/comp_metrics_v2/' + str(idx - 1900).zfill(6) + '.jpg') def viz_rgbd(folder): dirlist = sorted(os.listdir(folder)) for seq in dirlist: data_path = folder + '/' + seq data = open(data_path, "rb") data_dict = pickle.load(data) rgb = data_dict['rgb'] depth = data_dict['depth_pred'] * 1000 depth_gt = data_dict['depth_gt'] # r = rgb[:, :, 0] toshow_image = np.hstack((depth, depth_gt)) plt.imshow(toshow_image) plt.show(block=True) def save_rgb(folder): dirlist = sorted(os.listdir(folder)) idx = 0 for seq in dirlist: data_path = folder + '/' + seq data = open(data_path, "rb") data_dict = pickle.load(data) rgb = data_dict['rgb'] Image.fromarray(rgb).save( '/home/nod/datasets/robot/20200611/dso/images/' + str(idx).zfill(5) + '.jpg') idx += 1 def save_depth(folder): dirlist = sorted(os.listdir(folder)) idx = 0 for seq in dirlist: data_path = folder + '/' + seq data = open(data_path, "rb") data_dict = pickle.load(data) depth = np.uint16(data_dict['depth_pred'] * 1000) Image.fromarray(depth).save( '/home/nod/tmp/' + str(idx).zfill(5) + '.png') idx += 1 def process_kitti_data(folder): dirlist = sorted(os.listdir(folder)) for seq in dirlist: seq_path = folder + '/' + seq imglist = sorted(os.listdir(seq_path)) for file in imglist: if '.jpg' in file: image_path = seq_path + '/' + file image = np.array(Image.open(image_path))[:, 640:1280, :] Image.fromarray(image).save(image_path) def merge_pickle_data(folder_1, folder_2): dirlist = sorted(os.listdir(folder_1)) for file in dirlist: data_path_1 = folder_1 + '/' + file data_path_2 = folder_2 + '/' + file data_1 = open(data_path_1, "rb") data_dict_1 = pickle.load(data_1) rgb = data_dict_1['rgb'] depth_pred = data_dict_1['depth'] data_2 = open(data_path_2, "rb") data_dict_2 = pickle.load(data_2) depth_gt = data_dict_2['depth_gt'][:, 640:1280] data_dict = {'rgb': rgb, 'depth_pred': depth_pred, 'depth_gt': depth_gt} dict_file_name = '/home/nod/datasets/robot/20200611/rgbd_gt_data/' + file f = open(dict_file_name, "wb") pickle.dump(data_dict, f) f.close() def flip_array(image_path): image = np.array(Image.open(image_path)) image_flip_lr = np.fliplr(image) plt.imshow(np.vstack((image, image_flip_lr))) plt.show(block=True) def read_confidence(image_path): image = np.array(Image.open(image_path)) def read_depth(image_path): image = np.array(Image.open(image_path)) # image = cv2.imread(image_path, cv2.IMREAD_UNCHANGED) import pdb pdb.set_trace() def process_dso(data_path): data = open(data_path, "rb") data_dict = pickle.load(data) rgb = data_dict['rgb'] depth_pred = data_dict['depth_pred'] * 1000 depth_gt = data_dict['depth_gt'] depth_dso = np.array(Image.open( '/home/nod/project/dso/build/sample/00023.png')) # toshow_image = np.hstack((depth_dso, depth_gt)) # plt.imshow(toshow_image) # plt.show(block = True) # Scalar matching, scalar is 4.257004157652051 # scalar_dso # 4.257004157652051 # scalar_pred # 0.7131490173152352 mask_gt = np.logical_and(depth_gt > 10, depth_gt < 2000) mask_pred = np.logical_and(depth_pred > 100, depth_pred < 10000) mask_dso = np.logical_and(depth_dso > 10, depth_dso < 2000) scalar_dso = np.mean(depth_gt[mask_gt]) / np.mean(depth_dso[mask_dso]) scalar_pred = np.mean(depth_gt[mask_gt]) / np.mean(depth_pred[mask_pred]) # depth_dso_image = vis_depth(depth_dso * scalar_dso) # depth_pred_image = vis_depth(depth_pred * scalar_pred) # Image.fromarray(depth_dso_image).save('/home/nod/project/dso/build/sample/depth_dso.png') # Image.fromarray(depth_pred_image).save('/home/nod/project/dso/build/sample/depth_pred.png') def eval_densify(data_path): data = open(data_path, "rb") data_dict = pickle.load(data) # pdb.set_trace() rgb = data_dict['rgb'] depth_pred = data_dict['depth_pred'] depth_dso = data_dict['depth_dso'] depth_gt = data_dict['depth_gt'] depth_densify = data_dict['depth_densify'] depth_pred_image = vis_depth(depth_pred) depth_dso_image = vis_depth(depth_dso) depth_densify_image = vis_depth(depth_densify) depth_gt_image = vis_depth(depth_gt) # plt.title(' Nod Depth DSO Depth Densified DSO Kinect Depth', fontsize=20, loc='left') # plt.imshow(np.hstack((depth_pred_image, depth_dso_image, depth_densify_image, depth_gt_image))) plt.title(' Nod Depth Densified DSO Kinect Depth', fontsize=12, loc='left') plt.imshow(np.hstack((depth_pred, depth_densify, depth_gt))) plt.show(block=True) min_depth = 0.1 max_depth = 10 print('------------------EVAL Depth Model------------------') eval_pred_dict = eval_depth_nod( depth_pred, depth_gt, min_depth, max_depth, 1.0) print_eval_dict(eval_pred_dict) print('------------------EVAL DSO------------------') eval_dso_dict = eval_depth_nod( depth_dso, depth_gt, min_depth, max_depth, 1.0) print_eval_dict(eval_dso_dict) print('------------------EVAL Densified DSO------------------') eval_densify_dict = eval_depth_nod( depth_densify, depth_gt, min_depth, max_depth, 1.0) print_eval_dict(eval_densify_dict) def vis_rgbd_pickle_image(folder_1, folder_2): dirlist_1 = sorted(os.listdir(folder_1)) dirlist_2 = sorted(os.listdir(folder_2)) for idx in range(len(dirlist_1)): datapath_1 = open(folder_1 + '/' + dirlist_1[idx], "rb") data_1 = pickle.load(datapath_1) rgb = data_1['rgb'] depth_image_tpu = vis_depth(data_1['depth_pred']) depth_image_gt = vis_depth(data_1['depth_gt']) datapath_2 = open(folder_2 + '/' + dirlist_2[idx], "rb") depth_image_dpu = np.array(Image.open(datapath_2))[480:, :, :] image_show = np.hstack( (rgb, depth_image_gt, depth_image_dpu, depth_image_tpu)) img = Image.fromarray(image_show) img.save('/home/nod/datasets/nyudepthV2/rgbd_tpu_dpu/' + dirlist_2[idx]) def convert_16bit_rgb(folder_1, folder_2): dirlist_1 = sorted(os.listdir(folder_1)) for idx in range(len(dirlist_1)): datapath_1 = folder_1 + '/' + dirlist_1[idx] image_1 = plt.imread(datapath_1) plt.imsave(folder_2 + '/' + dirlist_1[idx], image_1) print(idx) def resize_folder(folder): dirlist = sorted(os.listdir(folder)) for idx in range(len(dirlist)): datapath = folder + '/' + dirlist[idx] Image.open(datapath).resize((896, 896)).save( '/home/jiatian/project/Zooming-Slow-Mo-CVPR-2020/tmp' + '/' + dirlist[idx]) print(idx) def delete_folder(folder, num): dirlist = sorted(os.listdir(folder)) num_total = len(dirlist) for idx in range(num): datapath = folder + '/' + dirlist[idx] os.remove(datapath) for idx in range(num_total - num, num_total): datapath = folder + '/' + dirlist[idx] os.remove(datapath) def vis_rgb_pose_image(folder_1, folder_2): dirlist_1 = sorted(os.listdir(folder_1)) dirlist_2 = sorted(os.listdir(folder_2)) for idx in range(len(dirlist_1)): data_1 = Image.open(folder_1 + '/' + dirlist_1[idx]).convert('RGB') data_2 = Image.open(folder_2 + '/' + dirlist_2[idx]).convert('RGB') image_show = np.hstack((np.array(data_1), np.array(data_2))) img = Image.fromarray(image_show) img.save('/home/jiatian/dataset/rs_eval/comp/' + dirlist_2[idx]) if __name__ == "__main__": vis_rgb_pose_image('/home/jiatian/dataset/recordvi/402-000-undistort', '/home/jiatian/dataset/rs_eval/pose') # plot_trajectory('/home/jiatian/dataset/rs_eval/pose/poses_log.pickle') # delete_folder('/home/jiatian/dataset/realsense/recordvi-4-02-00/402-004-undistort', 300) # resave_imu_data() # plot_acc_data('/home/jiatian/dataset/office_kitchen_0001a') # plot_imu_traj('/home/jiatian/dataset/office_kitchen_0001a') # read_amazon_data('/home/jiatian/dataset/amazon/raw_data/000001.pkl') # vis_float_image('/home/jiatianwu/eval/eval_res') # vis_zcu_image('/home/jiatianwu/project/vitis-ai/nod_depth/saved_data/rgbd_tflite_vitis_data') # process_tello('/home/jiatianwu/dataset/tello') # vis_pickle_image('/home/jiatianwu/000001.pkl') # vis_folder(folder='/home/nod/lyft_kitti/train/image_2') # vis_image('/home/nod/datasets/lyft/raw_data/000000/000000_9ccf7db5e9d2ab8847906a7f086aa7c0c189efecfe381d9120bf02c7de6907b9.png') # rename_folder_util('/home/nod/tmp_2') # vis_depth_pose('/home/nod/datasets/kitti_eval/2011_09_26_drive_0022_sync_02', '/home/nod/datasets/kitti_eval_1/2011_09_26_drive_0022_sync_02/') # save_nyu_indoor_images('/home/nod/nod/nod/src/apps/nod_depth/saved_data/indoor_eval_res') # viz_resize('/home/nod/datasets/nod/images0') # read_process_nyu_data('/home/nod/datasets/nyudepthV2/nyu_depth_v2_labeled.mat') # generate_pc_nyudepth('/home/nod/datasets/nyudepthV2/rgbd_gt_data', '/home/nod/datasets/nyudepthV2/pc_gt') # crop_folder('/home/nod/tmp', '/home/nod/tmp_2') # readmat('/home/nod/Downloads/splits.mat') # save_nyu_eval_image('/home/nod/datasets/nyudepthV2/nyu_depth_v2_labeled.mat') # comp_nod_sgm('/home/nod/datasets/weanhall/eval', '/home/nod/datasets/weanhall/eval_sgm') # rename_folder_tum('/home/nod/datasets/robot/20200611/images') # add_metrics_weanhall('/home/nod/datasets/weanhall/rgbd_data_wean', '/home/nod/datasets/weanhall/eval_sgm_data', '/home/nod/datasets/weanhall/comp') # generate_pc_media_intrinsics('/home/nod/datasets/media/eval/eval_res_data', '/home/nod/datasets/media/eval/pc') # viz_rgbd('/home/nod/datasets/robot/20200611/rgbd_gt_data_finetune') # vis_image_crop('/home/nod/datasets/weanhall/eval_metrics/001907.jpg') # crop_folder('/home/nod/datasets/weanhall/eval_metrics', '/home/nod/datasets/weanhall/eval_metrics_crop') # add_metrics_weanhall('/home/nod/datasets/weanhall/eval_model_data', '/home/nod/datasets/weanhall/eval_sgm_data', '/home/nod/datasets/weanhall/rectified') # process_kitti_data('/home/nod/datasets/kitti/kitti_data') # rename_folder_image('/home/nod/datasets/nyudepthV2/test_kitchen/color') # merge_pickle_data('/home/nod/datasets/nyudepthV2/rgbd_data', '/home/nod/datasets/nyudepthV2/rgb_gt_data') # flip_array('/home/nod/datasets/nyudepthV2/eval_data/000000.jpg') # read_confidence('/home/nod/project/The_Bilateral_Solver/build/confidence.png') # merge_pickle_data('/home/nod/project/tf-monodepth2/saved_data/tmp_data', '/home/nod/datasets/robot/20200611/depth_data') # generate_pc_kinect('/home/nod/datasets/robot/20200611/rgbd_gt_data_finetune', '/home/nod/datasets/robot/20200611/pc_data_finetune') # save_rgb('/home/nod/datasets/robot/20200611/rgbd_gt_data') # save_depth('/home/nod/datasets/robot/20200611/rgbd_gt_data_finetune') # read_depth('/home/nod/project/dso/build/depths_out/00007.png') # process_dso('/home/nod/project/dso/build/sample/000068.pkl') # eval_densify('/home/nod/project/dso/build/sample/00068_densify.pkl') # convert_rgb_folder('/home/jiatian/dataset/tum') #vis_rgbd_pickle_image("/home/nod/datasets/nyudepthV2/rgbd_gt_tpu_nopp_data", "/home/nod/project/vitis-ai/mpsoc/vitis-ai-tool-example/tf_eval_script/eval_res") #convert_16bit_rgb('/home/jiatian/dataset/bu_tiv/lab1-test-seq1-red/red/TIV', '/home/jiatian/dataset/bu_tiv/lab1-test-seq1-red/red/rgb') # resize_folder( # '/home/jiatian/project/Zooming-Slow-Mo-CVPR-2020/test_example/adas')
[ "matplotlib.pyplot.title", "pickle.dump", "os.remove", "tensorflow.image.grayscale_to_rgb", "scipy.io.loadmat", "matplotlib.pyplot.clf", "matplotlib.pyplot.figure", "pickle.load", "numpy.arange", "numpy.mean", "matplotlib.pyplot.imsave", "matplotlib.pyplot.imread", "numpy.eye", "matplotlib...
[((910, 932), 'tensorflow.read_file', 'tf.read_file', (['img_path'], {}), '(img_path)\n', (922, 932), True, 'import tensorflow as tf\n'), ((948, 973), 'tensorflow.image.decode_jpeg', 'tf.image.decode_jpeg', (['img'], {}), '(img)\n', (968, 973), True, 'import tensorflow as tf\n'), ((987, 1024), 'tensorflow.image.decode_jpeg', 'tf.image.decode_jpeg', (['img'], {'channels': '(3)'}), '(img, channels=3)\n', (1007, 1024), True, 'import tensorflow as tf\n'), ((1038, 1073), 'tensorflow.image.grayscale_to_rgb', 'tf.image.grayscale_to_rgb', (['img_gray'], {}), '(img_gray)\n', (1063, 1073), True, 'import tensorflow as tf\n'), ((1404, 1419), 'pdb.set_trace', 'pdb.set_trace', ([], {}), '()\n', (1417, 1419), False, 'import pdb\n'), ((1496, 1515), 'os.listdir', 'os.listdir', (['dataset'], {}), '(dataset)\n', (1506, 1515), False, 'import os\n'), ((1956, 1974), 'os.system', 'os.system', (['command'], {}), '(command)\n', (1965, 1974), False, 'import os\n'), ((2042, 2060), 'os.listdir', 'os.listdir', (['folder'], {}), '(folder)\n', (2052, 2060), False, 'import os\n'), ((2756, 2767), 'matplotlib.pyplot.plot', 'plt.plot', (['x'], {}), '(x)\n', (2764, 2767), True, 'import matplotlib.pyplot as plt\n'), ((2772, 2783), 'matplotlib.pyplot.plot', 'plt.plot', (['y'], {}), '(y)\n', (2780, 2783), True, 'import matplotlib.pyplot as plt\n'), ((2788, 2799), 'matplotlib.pyplot.plot', 'plt.plot', (['z'], {}), '(z)\n', (2796, 2799), True, 'import matplotlib.pyplot as plt\n'), ((2804, 2814), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2812, 2814), True, 'import matplotlib.pyplot as plt\n'), ((2961, 2986), 'numpy.array', 'np.array', (['acc_data_1[1:4]'], {}), '(acc_data_1[1:4])\n', (2969, 2986), True, 'import numpy as np\n'), ((3003, 3028), 'numpy.array', 'np.array', (['acc_data_2[1:4]'], {}), '(acc_data_2[1:4])\n', (3011, 3028), True, 'import numpy as np\n'), ((3330, 3355), 'numpy.array', 'np.array', (['[0.0, 0.0, 0.0]'], {}), '([0.0, 0.0, 0.0])\n', (3338, 3355), True, 'import numpy as np\n'), ((3365, 3390), 'numpy.array', 'np.array', (['[0.0, 0.0, 0.0]'], {}), '([0.0, 0.0, 0.0])\n', (3373, 3390), True, 'import numpy as np\n'), ((3700, 3712), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (3710, 3712), True, 'import matplotlib.pyplot as plt\n'), ((3936, 3946), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3944, 3946), True, 'import matplotlib.pyplot as plt\n'), ((4114, 4131), 'pickle.load', 'pickle.load', (['data'], {}), '(data)\n', (4125, 4131), False, 'import pickle\n'), ((4169, 4204), 'numpy.zeros', 'np.zeros', (['rgb.shape'], {'dtype': 'np.uint8'}), '(rgb.shape, dtype=np.uint8)\n', (4177, 4204), True, 'import numpy as np\n'), ((4694, 4714), 'matplotlib.pyplot.show', 'plt.show', ([], {'block': '(True)'}), '(block=True)\n', (4702, 4714), True, 'import matplotlib.pyplot as plt\n'), ((5149, 5177), 'numpy.percentile', 'np.percentile', (['depth_map', '(90)'], {}), '(depth_map, 90)\n', (5162, 5177), True, 'import numpy as np\n'), ((5222, 5264), 'matplotlib.colors.Normalize', 'mpl.colors.Normalize', ([], {'vmin': 'vmin', 'vmax': 'vmax'}), '(vmin=vmin, vmax=vmax)\n', (5242, 5264), True, 'import matplotlib as mpl\n'), ((5278, 5332), 'matplotlib.cm.ScalarMappable', 'mpl.cm.ScalarMappable', ([], {'norm': 'normalizer', 'cmap': '"""viridis"""'}), "(norm=normalizer, cmap='viridis')\n", (5299, 5332), True, 'import matplotlib as mpl\n'), ((8225, 8242), 'pickle.load', 'pickle.load', (['data'], {}), '(data)\n', (8236, 8242), False, 'import pickle\n'), ((8352, 8398), 'numpy.vstack', 'np.vstack', (['(rgb, depth_image, depth_image_zcu)'], {}), '((rgb, depth_image, depth_image_zcu))\n', (8361, 8398), True, 'import numpy as np\n'), ((8410, 8437), 'PIL.Image.fromarray', 'Image.fromarray', (['image_show'], {}), '(image_show)\n', (8425, 8437), False, 'from PIL import Image\n'), ((8449, 8468), 'PIL.ImageDraw.Draw', 'ImageDraw.Draw', (['img'], {}), '(img)\n', (8463, 8468), False, 'from PIL import ImageDraw\n'), ((8538, 8573), 'PIL.ImageFont.truetype', 'ImageFont.truetype', (['"""Agane.ttf"""', '(32)'], {}), "('Agane.ttf', 32)\n", (8556, 8573), False, 'from PIL import ImageFont\n'), ((9179, 9190), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (9188, 9190), True, 'import matplotlib.pyplot as plt\n'), ((9226, 9242), 'PIL.Image.open', 'Image.open', (['path'], {}), '(path)\n', (9236, 9242), False, 'from PIL import Image\n'), ((9317, 9332), 'numpy.array', 'np.array', (['image'], {}), '(image)\n', (9325, 9332), True, 'import numpy as np\n'), ((9337, 9354), 'matplotlib.pyplot.imshow', 'plt.imshow', (['image'], {}), '(image)\n', (9347, 9354), True, 'import matplotlib.pyplot as plt\n'), ((9359, 9379), 'matplotlib.pyplot.show', 'plt.show', ([], {'block': '(True)'}), '(block=True)\n', (9367, 9379), True, 'import matplotlib.pyplot as plt\n'), ((9384, 9395), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (9393, 9395), True, 'import matplotlib.pyplot as plt\n'), ((9436, 9452), 'PIL.Image.open', 'Image.open', (['path'], {}), '(path)\n', (9446, 9452), False, 'from PIL import Image\n'), ((9510, 9525), 'numpy.array', 'np.array', (['image'], {}), '(image)\n', (9518, 9525), True, 'import numpy as np\n'), ((9530, 9547), 'matplotlib.pyplot.imshow', 'plt.imshow', (['image'], {}), '(image)\n', (9540, 9547), True, 'import matplotlib.pyplot as plt\n'), ((9552, 9572), 'matplotlib.pyplot.show', 'plt.show', ([], {'block': '(True)'}), '(block=True)\n', (9560, 9572), True, 'import matplotlib.pyplot as plt\n'), ((9577, 9588), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (9586, 9588), True, 'import matplotlib.pyplot as plt\n'), ((10774, 10791), 'pickle.load', 'pickle.load', (['data'], {}), '(data)\n', (10785, 10791), False, 'import pickle\n'), ((12929, 12949), 'h5py.File', 'h5py.File', (['path', '"""r"""'], {}), "(path, 'r')\n", (12938, 12949), False, 'import h5py\n'), ((14800, 14812), 'numpy.eye', 'np.eye', (['(3)', '(3)'], {}), '(3, 3)\n', (14806, 14812), True, 'import numpy as np\n'), ((16410, 16422), 'numpy.eye', 'np.eye', (['(3)', '(3)'], {}), '(3, 3)\n', (16416, 16422), True, 'import numpy as np\n'), ((17164, 17176), 'numpy.eye', 'np.eye', (['(3)', '(3)'], {}), '(3, 3)\n', (17170, 17176), True, 'import numpy as np\n'), ((19136, 19153), 'scipy.io.loadmat', 'loadmat', (['filepath'], {}), '(filepath)\n', (19143, 19153), False, 'from scipy.io import loadmat\n'), ((19173, 19188), 'pdb.set_trace', 'pdb.set_trace', ([], {}), '()\n', (19186, 19188), False, 'import pdb\n'), ((19234, 19253), 'h5py.File', 'h5py.File', (['filepath'], {}), '(filepath)\n', (19243, 19253), False, 'import h5py\n'), ((27176, 27192), 'numpy.fliplr', 'np.fliplr', (['image'], {}), '(image)\n', (27185, 27192), True, 'import numpy as np\n'), ((27248, 27268), 'matplotlib.pyplot.show', 'plt.show', ([], {'block': '(True)'}), '(block=True)\n', (27256, 27268), True, 'import matplotlib.pyplot as plt\n'), ((27502, 27517), 'pdb.set_trace', 'pdb.set_trace', ([], {}), '()\n', (27515, 27517), False, 'import pdb\n'), ((27597, 27614), 'pickle.load', 'pickle.load', (['data'], {}), '(data)\n', (27608, 27614), False, 'import pickle\n'), ((28088, 28134), 'numpy.logical_and', 'np.logical_and', (['(depth_gt > 10)', '(depth_gt < 2000)'], {}), '(depth_gt > 10, depth_gt < 2000)\n', (28102, 28134), True, 'import numpy as np\n'), ((28151, 28203), 'numpy.logical_and', 'np.logical_and', (['(depth_pred > 100)', '(depth_pred < 10000)'], {}), '(depth_pred > 100, depth_pred < 10000)\n', (28165, 28203), True, 'import numpy as np\n'), ((28219, 28267), 'numpy.logical_and', 'np.logical_and', (['(depth_dso > 10)', '(depth_dso < 2000)'], {}), '(depth_dso > 10, depth_dso < 2000)\n', (28233, 28267), True, 'import numpy as np\n'), ((28815, 28832), 'pickle.load', 'pickle.load', (['data'], {}), '(data)\n', (28826, 28832), False, 'import pickle\n'), ((29497, 29614), 'matplotlib.pyplot.title', 'plt.title', (['""" Nod Depth Densified DSO Kinect Depth"""'], {'fontsize': '(12)', 'loc': '"""left"""'}), "(\n ' Nod Depth Densified DSO Kinect Depth',\n fontsize=12, loc='left')\n", (29506, 29614), True, 'import matplotlib.pyplot as plt\n'), ((29689, 29709), 'matplotlib.pyplot.show', 'plt.show', ([], {'block': '(True)'}), '(block=True)\n', (29697, 29709), True, 'import matplotlib.pyplot as plt\n'), ((493, 517), 'csv.DictReader', 'csv.DictReader', (['csv_file'], {}), '(csv_file)\n', (507, 517), False, 'import csv\n'), ((1084, 1096), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (1094, 1096), True, 'import tensorflow as tf\n'), ((1595, 1614), 'os.listdir', 'os.listdir', (['seq_dir'], {}), '(seq_dir)\n', (1605, 1614), False, 'import os\n'), ((4230, 4250), 'numpy.arange', 'np.arange', (['(0)', '(640)', '(1)'], {}), '(0, 640, 1)\n', (4239, 4250), True, 'import numpy as np\n'), ((4277, 4297), 'numpy.arange', 'np.arange', (['(0)', '(480)', '(1)'], {}), '(0, 480, 1)\n', (4286, 4297), True, 'import numpy as np\n'), ((4663, 4688), 'numpy.hstack', 'np.hstack', (['(rgb, rgb_new)'], {}), '((rgb, rgb_new))\n', (4672, 4688), True, 'import numpy as np\n'), ((5539, 5557), 'os.listdir', 'os.listdir', (['folder'], {}), '(folder)\n', (5549, 5557), False, 'import os\n'), ((6427, 6445), 'os.listdir', 'os.listdir', (['folder'], {}), '(folder)\n', (6437, 6445), False, 'import os\n'), ((6571, 6588), 'pickle.load', 'pickle.load', (['data'], {}), '(data)\n', (6582, 6588), False, 'import pickle\n'), ((6759, 6827), 'numpy.vstack', 'np.vstack', (['(rgb, depth_image, depth_tflite_image, depth_vitis_image)'], {}), '((rgb, depth_image, depth_tflite_image, depth_vitis_image))\n', (6768, 6827), True, 'import numpy as np\n'), ((6856, 6883), 'PIL.Image.fromarray', 'Image.fromarray', (['image_show'], {}), '(image_show)\n', (6871, 6883), False, 'from PIL import Image\n'), ((6899, 6918), 'PIL.ImageDraw.Draw', 'ImageDraw.Draw', (['img'], {}), '(img)\n', (6913, 6918), False, 'from PIL import ImageDraw\n'), ((6934, 6969), 'PIL.ImageFont.truetype', 'ImageFont.truetype', (['"""Agane.ttf"""', '(32)'], {}), "('Agane.ttf', 32)\n", (6952, 6969), False, 'from PIL import ImageFont\n'), ((7604, 7622), 'os.listdir', 'os.listdir', (['folder'], {}), '(folder)\n', (7614, 7622), False, 'import os\n'), ((8102, 8127), 'pickle.dump', 'pickle.dump', (['data_dict', 'f'], {}), '(data_dict, f)\n', (8113, 8127), False, 'import pickle\n'), ((8942, 8960), 'os.listdir', 'os.listdir', (['folder'], {}), '(folder)\n', (8952, 8960), False, 'import os\n'), ((9084, 9101), 'matplotlib.pyplot.imshow', 'plt.imshow', (['image'], {}), '(image)\n', (9094, 9101), True, 'import matplotlib.pyplot as plt\n'), ((9110, 9130), 'matplotlib.pyplot.show', 'plt.show', ([], {'block': '(True)'}), '(block=True)\n', (9118, 9130), True, 'import matplotlib.pyplot as plt\n'), ((9139, 9155), 'matplotlib.pyplot.pause', 'plt.pause', (['(0.001)'], {}), '(0.001)\n', (9148, 9155), True, 'import matplotlib.pyplot as plt\n'), ((9164, 9173), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (9171, 9173), True, 'import matplotlib.pyplot as plt\n'), ((9639, 9657), 'os.listdir', 'os.listdir', (['folder'], {}), '(folder)\n', (9649, 9657), False, 'import os\n'), ((9876, 9894), 'os.listdir', 'os.listdir', (['folder'], {}), '(folder)\n', (9886, 9894), False, 'import os\n'), ((10104, 10122), 'os.listdir', 'os.listdir', (['folder'], {}), '(folder)\n', (10114, 10122), False, 'import os\n'), ((10363, 10381), 'os.listdir', 'os.listdir', (['folder'], {}), '(folder)\n', (10373, 10381), False, 'import os\n'), ((10919, 10947), 'numpy.expand_dims', 'np.expand_dims', (['pose'], {'axis': '(0)'}), '(pose, axis=0)\n', (10933, 10947), True, 'import numpy as np\n'), ((10963, 10991), 'numpy.expand_dims', 'np.expand_dims', (['pose'], {'axis': '(0)'}), '(pose, axis=0)\n', (10977, 10991), True, 'import numpy as np\n'), ((11624, 11640), 'matplotlib.pyplot.plot', 'plt.plot', (['xs', 'ys'], {}), '(xs, ys)\n', (11632, 11640), True, 'import matplotlib.pyplot as plt\n'), ((12042, 12078), 'numpy.vstack', 'np.vstack', (['(depth_image, pose_image)'], {}), '((depth_image, pose_image))\n', (12051, 12078), True, 'import numpy as np\n'), ((12275, 12293), 'os.listdir', 'os.listdir', (['folder'], {}), '(folder)\n', (12285, 12293), False, 'import os\n'), ((12566, 12584), 'os.listdir', 'os.listdir', (['folder'], {}), '(folder)\n', (12576, 12584), False, 'import os\n'), ((12864, 12884), 'matplotlib.pyplot.show', 'plt.show', ([], {'block': '(True)'}), '(block=True)\n', (12872, 12884), True, 'import matplotlib.pyplot as plt\n'), ((13198, 13228), 'numpy.transpose', 'np.transpose', (['image', '(2, 1, 0)'], {}), '(image, (2, 1, 0))\n', (13210, 13228), True, 'import numpy as np\n'), ((13245, 13272), 'numpy.transpose', 'np.transpose', (['depth', '(1, 0)'], {}), '(depth, (1, 0))\n', (13257, 13272), True, 'import numpy as np\n'), ((13489, 13514), 'pickle.dump', 'pickle.dump', (['data_dict', 'f'], {}), '(data_dict, f)\n', (13500, 13514), False, 'import pickle\n'), ((15039, 15063), 'os.listdir', 'os.listdir', (['input_folder'], {}), '(input_folder)\n', (15049, 15063), False, 'import os\n'), ((15244, 15261), 'pickle.load', 'pickle.load', (['data'], {}), '(data)\n', (15255, 15261), False, 'import pickle\n'), ((15832, 15856), 'os.listdir', 'os.listdir', (['input_folder'], {}), '(input_folder)\n', (15842, 15856), False, 'import os\n'), ((16037, 16054), 'pickle.load', 'pickle.load', (['data'], {}), '(data)\n', (16048, 16054), False, 'import pickle\n'), ((16609, 16633), 'os.listdir', 'os.listdir', (['input_folder'], {}), '(input_folder)\n', (16619, 16633), False, 'import os\n'), ((16814, 16831), 'pickle.load', 'pickle.load', (['data'], {}), '(data)\n', (16825, 16831), False, 'import pickle\n'), ((18068, 18126), 'PIL.Image.open', 'Image.open', (['"""/home/nod/project/dso/build/sample/00068.jpg"""'], {}), "('/home/nod/project/dso/build/sample/00068.jpg')\n", (18078, 18126), False, 'from PIL import Image\n'), ((18456, 18495), 'os.makedirs', 'os.makedirs', (['output_dir'], {'exist_ok': '(False)'}), '(output_dir, exist_ok=False)\n', (18467, 18495), False, 'import os\n'), ((18650, 18668), 'os.listdir', 'os.listdir', (['folder'], {}), '(folder)\n', (18660, 18668), False, 'import os\n'), ((18750, 18772), 'PIL.Image.open', 'Image.open', (['image_path'], {}), '(image_path)\n', (18760, 18772), False, 'from PIL import Image\n'), ((19470, 19500), 'numpy.transpose', 'np.transpose', (['image', '(2, 1, 0)'], {}), '(image, (2, 1, 0))\n', (19482, 19500), True, 'import numpy as np\n'), ((19693, 19715), 'os.listdir', 'os.listdir', (['nod_folder'], {}), '(nod_folder)\n', (19703, 19715), False, 'import os\n'), ((19742, 19764), 'os.listdir', 'os.listdir', (['sgm_folder'], {}), '(sgm_folder)\n', (19752, 19764), False, 'import os\n'), ((20298, 20327), 'PIL.Image.fromarray', 'Image.fromarray', (['toshow_image'], {}), '(toshow_image)\n', (20313, 20327), False, 'from PIL import Image\n'), ((20343, 20362), 'PIL.ImageDraw.Draw', 'ImageDraw.Draw', (['img'], {}), '(img)\n', (20357, 20362), False, 'from PIL import ImageDraw\n'), ((20440, 20475), 'PIL.ImageFont.truetype', 'ImageFont.truetype', (['"""Agane.ttf"""', '(36)'], {}), "('Agane.ttf', 36)\n", (20458, 20475), False, 'from PIL import ImageFont\n'), ((20939, 20957), 'os.listdir', 'os.listdir', (['folder'], {}), '(folder)\n', (20949, 20957), False, 'import os\n'), ((21165, 21183), 'os.listdir', 'os.listdir', (['folder'], {}), '(folder)\n', (21175, 21183), False, 'import os\n'), ((21517, 21533), 'os.listdir', 'os.listdir', (['path'], {}), '(path)\n', (21527, 21533), False, 'import os\n'), ((21749, 21771), 'os.listdir', 'os.listdir', (['nod_folder'], {}), '(nod_folder)\n', (21759, 21771), False, 'import os\n'), ((22076, 22097), 'pickle.load', 'pickle.load', (['nod_data'], {}), '(nod_data)\n', (22087, 22097), False, 'import pickle\n'), ((22211, 22232), 'pickle.load', 'pickle.load', (['sgm_data'], {}), '(sgm_data)\n', (22222, 22232), False, 'import pickle\n'), ((23592, 23621), 'PIL.Image.fromarray', 'Image.fromarray', (['toshow_image'], {}), '(toshow_image)\n', (23607, 23621), False, 'from PIL import Image\n'), ((23637, 23656), 'PIL.ImageDraw.Draw', 'ImageDraw.Draw', (['img'], {}), '(img)\n', (23651, 23656), False, 'from PIL import ImageDraw\n'), ((23734, 23769), 'PIL.ImageFont.truetype', 'ImageFont.truetype', (['"""Agane.ttf"""', '(36)'], {}), "('Agane.ttf', 36)\n", (23752, 23769), False, 'from PIL import ImageFont\n'), ((24117, 24156), 'matplotlib.pyplot.text', 'plt.text', (['(-550)', '(200)', 's_viz'], {'fontsize': '(14)'}), '(-550, 200, s_viz, fontsize=14)\n', (24125, 24156), True, 'import matplotlib.pyplot as plt\n'), ((24165, 24180), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (24173, 24180), True, 'import matplotlib.pyplot as plt\n'), ((24332, 24353), 'matplotlib.pyplot.show', 'plt.show', ([], {'block': '(False)'}), '(block=False)\n', (24340, 24353), True, 'import matplotlib.pyplot as plt\n'), ((24362, 24377), 'matplotlib.pyplot.pause', 'plt.pause', (['(0.01)'], {}), '(0.01)\n', (24371, 24377), True, 'import matplotlib.pyplot as plt\n'), ((24500, 24509), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (24507, 24509), True, 'import matplotlib.pyplot as plt\n'), ((24661, 24679), 'os.listdir', 'os.listdir', (['folder'], {}), '(folder)\n', (24671, 24679), False, 'import os\n'), ((24801, 24818), 'pickle.load', 'pickle.load', (['data'], {}), '(data)\n', (24812, 24818), False, 'import pickle\n'), ((24989, 25017), 'numpy.hstack', 'np.hstack', (['(depth, depth_gt)'], {}), '((depth, depth_gt))\n', (24998, 25017), True, 'import numpy as np\n'), ((25026, 25050), 'matplotlib.pyplot.imshow', 'plt.imshow', (['toshow_image'], {}), '(toshow_image)\n', (25036, 25050), True, 'import matplotlib.pyplot as plt\n'), ((25059, 25079), 'matplotlib.pyplot.show', 'plt.show', ([], {'block': '(True)'}), '(block=True)\n', (25067, 25079), True, 'import matplotlib.pyplot as plt\n'), ((25125, 25143), 'os.listdir', 'os.listdir', (['folder'], {}), '(folder)\n', (25135, 25143), False, 'import os\n'), ((25277, 25294), 'pickle.load', 'pickle.load', (['data'], {}), '(data)\n', (25288, 25294), False, 'import pickle\n'), ((25516, 25534), 'os.listdir', 'os.listdir', (['folder'], {}), '(folder)\n', (25526, 25534), False, 'import os\n'), ((25668, 25685), 'pickle.load', 'pickle.load', (['data'], {}), '(data)\n', (25679, 25685), False, 'import pickle\n'), ((25702, 25743), 'numpy.uint16', 'np.uint16', (["(data_dict['depth_pred'] * 1000)"], {}), "(data_dict['depth_pred'] * 1000)\n", (25711, 25743), True, 'import numpy as np\n'), ((25913, 25931), 'os.listdir', 'os.listdir', (['folder'], {}), '(folder)\n', (25923, 25931), False, 'import os\n'), ((26348, 26368), 'os.listdir', 'os.listdir', (['folder_1'], {}), '(folder_1)\n', (26358, 26368), False, 'import os\n'), ((26547, 26566), 'pickle.load', 'pickle.load', (['data_1'], {}), '(data_1)\n', (26558, 26566), False, 'import pickle\n'), ((26707, 26726), 'pickle.load', 'pickle.load', (['data_2'], {}), '(data_2)\n', (26718, 26726), False, 'import pickle\n'), ((27037, 27062), 'pickle.dump', 'pickle.dump', (['data_dict', 'f'], {}), '(data_dict, f)\n', (27048, 27062), False, 'import pickle\n'), ((27132, 27154), 'PIL.Image.open', 'Image.open', (['image_path'], {}), '(image_path)\n', (27142, 27154), False, 'from PIL import Image\n'), ((27209, 27242), 'numpy.vstack', 'np.vstack', (['(image, image_flip_lr)'], {}), '((image, image_flip_lr))\n', (27218, 27242), True, 'import numpy as np\n'), ((27325, 27347), 'PIL.Image.open', 'Image.open', (['image_path'], {}), '(image_path)\n', (27335, 27347), False, 'from PIL import Image\n'), ((27400, 27422), 'PIL.Image.open', 'Image.open', (['image_path'], {}), '(image_path)\n', (27410, 27422), False, 'from PIL import Image\n'), ((27754, 27812), 'PIL.Image.open', 'Image.open', (['"""/home/nod/project/dso/build/sample/00023.png"""'], {}), "('/home/nod/project/dso/build/sample/00023.png')\n", (27764, 27812), False, 'from PIL import Image\n'), ((28285, 28311), 'numpy.mean', 'np.mean', (['depth_gt[mask_gt]'], {}), '(depth_gt[mask_gt])\n', (28292, 28311), True, 'import numpy as np\n'), ((28314, 28342), 'numpy.mean', 'np.mean', (['depth_dso[mask_dso]'], {}), '(depth_dso[mask_dso])\n', (28321, 28342), True, 'import numpy as np\n'), ((28361, 28387), 'numpy.mean', 'np.mean', (['depth_gt[mask_gt]'], {}), '(depth_gt[mask_gt])\n', (28368, 28387), True, 'import numpy as np\n'), ((28390, 28420), 'numpy.mean', 'np.mean', (['depth_pred[mask_pred]'], {}), '(depth_pred[mask_pred])\n', (28397, 28420), True, 'import numpy as np\n'), ((29635, 29683), 'numpy.hstack', 'np.hstack', (['(depth_pred, depth_densify, depth_gt)'], {}), '((depth_pred, depth_densify, depth_gt))\n', (29644, 29683), True, 'import numpy as np\n'), ((30410, 30430), 'os.listdir', 'os.listdir', (['folder_1'], {}), '(folder_1)\n', (30420, 30430), False, 'import os\n'), ((30455, 30475), 'os.listdir', 'os.listdir', (['folder_2'], {}), '(folder_2)\n', (30465, 30475), False, 'import os\n'), ((30597, 30620), 'pickle.load', 'pickle.load', (['datapath_1'], {}), '(datapath_1)\n', (30608, 30620), False, 'import pickle\n'), ((30921, 30987), 'numpy.hstack', 'np.hstack', (['(rgb, depth_image_gt, depth_image_dpu, depth_image_tpu)'], {}), '((rgb, depth_image_gt, depth_image_dpu, depth_image_tpu))\n', (30930, 30987), True, 'import numpy as np\n'), ((31016, 31043), 'PIL.Image.fromarray', 'Image.fromarray', (['image_show'], {}), '(image_show)\n', (31031, 31043), False, 'from PIL import Image\n'), ((31210, 31230), 'os.listdir', 'os.listdir', (['folder_1'], {}), '(folder_1)\n', (31220, 31230), False, 'import os\n'), ((31341, 31363), 'matplotlib.pyplot.imread', 'plt.imread', (['datapath_1'], {}), '(datapath_1)\n', (31351, 31363), True, 'import matplotlib.pyplot as plt\n'), ((31372, 31424), 'matplotlib.pyplot.imsave', 'plt.imsave', (["(folder_2 + '/' + dirlist_1[idx])", 'image_1'], {}), "(folder_2 + '/' + dirlist_1[idx], image_1)\n", (31382, 31424), True, 'import matplotlib.pyplot as plt\n'), ((31494, 31512), 'os.listdir', 'os.listdir', (['folder'], {}), '(folder)\n', (31504, 31512), False, 'import os\n'), ((31812, 31830), 'os.listdir', 'os.listdir', (['folder'], {}), '(folder)\n', (31822, 31830), False, 'import os\n'), ((31943, 31962), 'os.remove', 'os.remove', (['datapath'], {}), '(datapath)\n', (31952, 31962), False, 'import os\n'), ((32068, 32087), 'os.remove', 'os.remove', (['datapath'], {}), '(datapath)\n', (32077, 32087), False, 'import os\n'), ((32156, 32176), 'os.listdir', 'os.listdir', (['folder_1'], {}), '(folder_1)\n', (32166, 32176), False, 'import os\n'), ((32201, 32221), 'os.listdir', 'os.listdir', (['folder_2'], {}), '(folder_2)\n', (32211, 32221), False, 'import os\n'), ((32498, 32525), 'PIL.Image.fromarray', 'Image.fromarray', (['image_show'], {}), '(image_show)\n', (32513, 32525), False, 'from PIL import Image\n'), ((720, 735), 'pdb.set_trace', 'pdb.set_trace', ([], {}), '()\n', (733, 735), False, 'import pdb\n'), ((5762, 5812), 'cv2.FileStorage', 'cv2.FileStorage', (['image_path', 'cv2.FILE_STORAGE_READ'], {}), '(image_path, cv2.FILE_STORAGE_READ)\n', (5777, 5812), False, 'import cv2\n'), ((6141, 6176), 'numpy.vstack', 'np.vstack', (['(rgb_image, depth_image)'], {}), '((rgb_image, depth_image))\n', (6150, 6176), True, 'import numpy as np\n'), ((7923, 7938), 'numpy.array', 'np.array', (['image'], {}), '(image)\n', (7931, 7938), True, 'import numpy as np\n'), ((9051, 9073), 'PIL.Image.open', 'Image.open', (['image_path'], {}), '(image_path)\n', (9061, 9073), False, 'from PIL import Image\n'), ((9756, 9820), 'os.rename', 'os.rename', (["(folder + '/' + seq)", "(folder + '/' + seq + '_CAM_FRONT')"], {}), "(folder + '/' + seq, folder + '/' + seq + '_CAM_FRONT')\n", (9765, 9820), False, 'import os\n'), ((10467, 10497), 'os.listdir', 'os.listdir', (["(folder + '/' + seq)"], {}), "(folder + '/' + seq)\n", (10477, 10497), False, 'import os\n'), ((18154, 18212), 'PIL.Image.open', 'Image.open', (['"""/home/nod/project/dso/build/sample/00023.png"""'], {}), "('/home/nod/project/dso/build/sample/00023.png')\n", (18164, 18212), False, 'from PIL import Image\n'), ((18516, 18554), 'os.makedirs', 'os.makedirs', (['output_dir'], {'exist_ok': '(True)'}), '(output_dir, exist_ok=True)\n', (18527, 18554), False, 'import os\n'), ((19334, 19345), 'numpy.array', 'np.array', (['v'], {}), '(v)\n', (19342, 19345), True, 'import numpy as np\n'), ((19903, 19950), 'PIL.Image.open', 'Image.open', (["(nod_folder + '/' + nod_dirlist[idx])"], {}), "(nod_folder + '/' + nod_dirlist[idx])\n", (19913, 19950), False, 'from PIL import Image\n'), ((19981, 20028), 'PIL.Image.open', 'Image.open', (["(sgm_folder + '/' + sgm_dirlist[idx])"], {}), "(sgm_folder + '/' + sgm_dirlist[idx])\n", (19991, 20028), False, 'from PIL import Image\n'), ((22413, 22440), 'PIL.Image.open', 'Image.open', (['image_left_path'], {}), '(image_left_path)\n', (22423, 22440), False, 'from PIL import Image\n'), ((22473, 22501), 'PIL.Image.open', 'Image.open', (['image_right_path'], {}), '(image_right_path)\n', (22483, 22501), False, 'from PIL import Image\n'), ((24094, 24107), 'numpy.array', 'np.array', (['img'], {}), '(img)\n', (24102, 24107), True, 'import numpy as np\n'), ((26020, 26040), 'os.listdir', 'os.listdir', (['seq_path'], {}), '(seq_path)\n', (26030, 26040), False, 'import os\n'), ((5897, 5962), 'PIL.Image.open', 'Image.open', (["('/home/jiatianwu/eval/eval_data/' + seq[:-4] + '.jpg')"], {}), "('/home/jiatianwu/eval/eval_data/' + seq[:-4] + '.jpg')\n", (5907, 5962), False, 'from PIL import Image\n'), ((7741, 7762), 'PIL.Image.open', 'Image.open', (['data_path'], {}), '(data_path)\n', (7751, 7762), False, 'from PIL import Image\n'), ((10168, 10198), 'PIL.Image.open', 'Image.open', (["(folder + '/' + seq)"], {}), "(folder + '/' + seq)\n", (10178, 10198), False, 'from PIL import Image\n'), ((12087, 12116), 'PIL.Image.fromarray', 'Image.fromarray', (['tosave_image'], {}), '(tosave_image)\n', (12102, 12116), False, 'from PIL import Image\n'), ((12388, 12410), 'PIL.Image.open', 'Image.open', (['image_path'], {}), '(image_path)\n', (12398, 12410), False, 'from PIL import Image\n'), ((12679, 12701), 'PIL.Image.open', 'Image.open', (['image_path'], {}), '(image_path)\n', (12689, 12701), False, 'from PIL import Image\n'), ((12742, 12764), 'PIL.Image.open', 'Image.open', (['image_path'], {}), '(image_path)\n', (12752, 12764), False, 'from PIL import Image\n'), ((19510, 19532), 'PIL.Image.fromarray', 'Image.fromarray', (['image'], {}), '(image)\n', (19525, 19532), False, 'from PIL import Image\n'), ((20236, 20280), 'numpy.hstack', 'np.hstack', (['(nod_pred_image, sgm_depth_image)'], {}), '((nod_pred_image, sgm_depth_image))\n', (20245, 20280), True, 'import numpy as np\n'), ((22645, 22681), 'numpy.hstack', 'np.hstack', (['(image_left, image_right)'], {}), '((image_left, image_right))\n', (22654, 22681), True, 'import numpy as np\n'), ((22683, 22728), 'numpy.hstack', 'np.hstack', (['(nod_depth_image, sgm_depth_image)'], {}), '((nod_depth_image, sgm_depth_image))\n', (22692, 22728), True, 'import numpy as np\n'), ((25335, 25355), 'PIL.Image.fromarray', 'Image.fromarray', (['rgb'], {}), '(rgb)\n', (25350, 25355), False, 'from PIL import Image\n'), ((25753, 25775), 'PIL.Image.fromarray', 'Image.fromarray', (['depth'], {}), '(depth)\n', (25768, 25775), False, 'from PIL import Image\n'), ((30864, 30886), 'PIL.Image.open', 'Image.open', (['datapath_2'], {}), '(datapath_2)\n', (30874, 30886), False, 'from PIL import Image\n'), ((32278, 32321), 'PIL.Image.open', 'Image.open', (["(folder_1 + '/' + dirlist_1[idx])"], {}), "(folder_1 + '/' + dirlist_1[idx])\n", (32288, 32321), False, 'from PIL import Image\n'), ((32354, 32397), 'PIL.Image.open', 'Image.open', (["(folder_2 + '/' + dirlist_2[idx])"], {}), "(folder_2 + '/' + dirlist_2[idx])\n", (32364, 32397), False, 'from PIL import Image\n'), ((32446, 32462), 'numpy.array', 'np.array', (['data_1'], {}), '(data_1)\n', (32454, 32462), True, 'import numpy as np\n'), ((32464, 32480), 'numpy.array', 'np.array', (['data_2'], {}), '(data_2)\n', (32472, 32480), True, 'import numpy as np\n'), ((6189, 6216), 'PIL.Image.fromarray', 'Image.fromarray', (['image_save'], {}), '(image_save)\n', (6204, 6216), False, 'from PIL import Image\n'), ((11042, 11070), 'torch.tensor', 'torch.tensor', (['pose[:, :, :3]'], {}), '(pose[:, :, :3])\n', (11054, 11070), False, 'import torch\n'), ((11080, 11108), 'torch.tensor', 'torch.tensor', (['pose[:, :, 3:]'], {}), '(pose[:, :, 3:])\n', (11092, 11108), False, 'import torch\n'), ((12815, 12830), 'numpy.array', 'np.array', (['image'], {}), '(image)\n', (12823, 12830), True, 'import numpy as np\n'), ((12832, 12852), 'numpy.array', 'np.array', (['image_dist'], {}), '(image_dist)\n', (12840, 12852), True, 'import numpy as np\n'), ((26186, 26208), 'PIL.Image.open', 'Image.open', (['image_path'], {}), '(image_path)\n', (26196, 26208), False, 'from PIL import Image\n'), ((26242, 26264), 'PIL.Image.fromarray', 'Image.fromarray', (['image'], {}), '(image)\n', (26257, 26264), False, 'from PIL import Image\n'), ((31605, 31625), 'PIL.Image.open', 'Image.open', (['datapath'], {}), '(datapath)\n', (31615, 31625), False, 'from PIL import Image\n'), ((10631, 10651), 'PIL.Image.open', 'Image.open', (['img_path'], {}), '(img_path)\n', (10641, 10651), False, 'from PIL import Image\n')]
# -*- coding: utf-8 -*- """ Lower-level methods to manage parameters and particle movement. Particle class for managing the definition of particle attributes and parameters of the domain as well as iterative movement of the particles through the domain. Project Homepage: https://github.com/passaH2O/dorado """ from __future__ import division, print_function, absolute_import import warnings from builtins import range from math import pi import numpy as np from tqdm import tqdm import dorado.lagrangian_walker as lw class modelParams: """Parameter class with attributes and grid particles will be routed on. The parameters class, :obj:`dorado.particle_track.modelParams`, must be populated with user-defined attributes of the grid the particles will be modeled on. **Required Parameters:** dx : `float` Length along one square cell face depth : `numpy.ndarray` Array of water depth values, if absent then the stage and topography arrays will be used to compute it stage : `numpy.ndarray` Array of water stage values, if absent then the depth and topography arrays will be used to compute it qx : `numpy.ndarray` Array of the x-component of flow discharge qy : `numpy.ndarray` Array of the y-component of flow discharge u : `numpy.ndarray` Array of the x-component of flow velocity v : `numpy.ndarray` Array of the y-component of flow velocity **Optional Parameters:** topography : `numpy.ndarray` Array of cell elevation values model : `str` Name of the hydrodynamic model input being used (e.g. 'DeltaRCM') theta : `float` First of two weighting parameters for the weighted random walk. Default value is 1.0, higher values give higher weighting probabilities to cells with greater water depths gamma : `float` Second of two weighting parameters for the weighted random walk. Default value is 0.05. Gamma must be in the range [0,1]. Gamma == 1 means that the random walk weights are independent of the discharge values, and instead are based on the water surface gradient (the stage). Gamma == 0 means that the random walk weights are not dependent on the surface gradient, and instead are based on the inertial forces (the flow discharge). diff_coeff : `float` Diffusion/dispersion coefficient for use in travel time computation. If set to 0.0, flow is purely advection with no diffusion. Higher values lead to more spread in exit age distribution. Max diffusion time in any given step is 0.5*diff_coeff percent. Default value is 0.2 (i.e. max of 10%) dry_depth : `float` Minimum depth for a cell to be considered wet, default value is 0.1m cell_type : `numpy.ndarray` Array of the different types of cells in the domain where 2 = land, 1 = channel, 0 = ocean, and -1 = edge. If not explicitly defined then the values are estimated based on the depth array and the defined dry_depth steepest_descent : `bool` Toggle for routing based on a steepest descent rather than the weighted random walk. If True, then the highest weighted cells are used to route the particles. Default value is False. verbose : `bool`, optional Toggles whether or not warnings and print output are output to the console. If False, nothing is output, if True, messages are output. Default value is True. Errors are always raised. This list of expected parameter values can also be obtained by querying the class attributes with `dir(modelParams)`, `modelParams.__dict__`, or `vars(modelParams)`. """ def __init__(self): """Create the expected variables for the modelParams class. Variables are initialized as NoneType they need to be assigned by the user. Due to the wide variety of data formats produced by differeny hydrodynamic models, this is process is not automated and must be handled on a case-by-case basis. """ self.dx = None self.depth = None self.stage = None self.qx = None self.qy = None self.u = None self.v = None self.verbose = True # print things by default class Particles(): """Class for the particle(s) that is(are) going to be routed.""" def __init__(self, params): """Check input parameters and assign default values where/if needed. Methods require a class of parameters (:obj:`dorado.particle_track.modelParams`) to be passed to the Particles class. e.g. particle = Particles(modelParams) Initialization tries to assign each value from the parameter class, otherwise an error is raised or default values are assigned when possible/sensible """ # pass verbose if getattr(params, 'verbose', None) is None: self.verbose = True # set verbosity on if somehow missing else: self.verbose = params.verbose # REQUIRED PARAMETERS # # Define the length along one cell face (assuming square cells) if getattr(params, 'dx', None) is None: raise ValueError("Length of cell face (modelParams.dx) is" " undefined") else: self.dx = params.dx # Define the water depth array if getattr(params, 'depth', None) is not None: try: self.depth = params.depth self.depth[np.isnan(self.depth)] = 0 except Exception: raise ValueError("Water depth array incorrectly defined.") elif getattr(params, 'stage', None) is not None and getattr(params, 'topography', None) is not None: try: self.depth = params.stage - params.topography self.depth[self.depth < 0] = 0 self.depth[np.isnan(self.depth)] = 0 except Exception: raise ValueError("Insufficient information: Specify depth") else: raise ValueError("Insufficient information: Specify depth") # Define the water stage array if getattr(params, 'stage', None) is not None: try: self.stage = params.stage self.stage[self.depth == 0] = np.nan except Exception: raise ValueError("Water stage array incorrectly defined.") elif getattr(params, 'topography', None) is not None and getattr(params, 'depth', None) is not None: try: self.stage = params.topography + params.depth self.stage[self.depth == 0] = np.nan except Exception: raise ValueError("Insufficient information: Specify stage") else: raise ValueError("Insufficient information: Specify stage") # check if hydrodynamic model input has been specified if getattr(params, 'model', None) is not None: pass else: params.model = [] # Define discharge and velocities for all cells in domain if params.model == 'DeltaRCM': if params.qx is not None and params.qy is not None: self.qx = params.qx self.qx[np.isnan(self.qx)] = 0 self.u = self.qx*self.depth/(self.depth**2 + 1e-8) self.u[np.isnan(self.u)] = 0 self.qy = params.qy self.qy[np.isnan(self.qy)] = 0 self.v = self.qy*self.depth/(self.depth**2 + 1e-8) self.v[np.isnan(self.v)] = 0 elif params.u is not None and params.v is not None: self.u = params.u self.u[np.isnan(self.u)] = 0 self.qx = self.u*self.depth self.v = params.v self.v[np.isnan(self.v)] = 0 self.qy = self.v*self.depth else: raise ValueError("Insufficient information:" " Specify velocities/discharge") else: if params.qx is not None and params.qy is not None: self.qx = -1*params.qy self.qx[np.isnan(self.qx)] = 0 self.u = self.qx*self.depth/(self.depth**2 + 1e-8) self.u[np.isnan(self.u)] = 0 self.qy = params.qx self.qy[np.isnan(self.qy)] = 0 self.v = self.qy*self.depth/(self.depth**2 + 1e-8) self.v[np.isnan(self.v)] = 0 elif params.u is not None and params.v is not None: self.u = -1*params.v self.u[np.isnan(self.u)] = 0 self.qx = self.u*self.depth self.v = params.u self.v[np.isnan(self.v)] = 0 self.qy = self.v*self.depth else: raise ValueError("Insufficient information:" " Specify velocities/discharge") # Define field of velocity magnitude (for travel time calculation) self.velocity = np.sqrt(self.u**2+self.v**2) # cannot have 0/nans - leads to infinite/nantravel times self.velocity[self.velocity < 1e-8] = 1e-8 self.u[np.abs(self.u) < 1e-8] = 1e-8 self.v[np.abs(self.v) < 1e-8] = 1e-8 # Compute velocity orientation at each cell self.velocity_angle = np.arctan2(-1.0*self.u, self.v) # OPTIONAL PARAMETERS (Have default values) # # Define the theta used to weight the random walk # Higher values give higher weighting probabilities to deeper cells try: self.theta = float(params.theta) except Exception: if self.verbose: print("Theta parameter not specified - using 1.0") self.theta = 1.0 # if unspecified use 1 # Gamma parameter used to weight the random walk # Sets weight ratio (between 0 and 1): # 1 = water surface gradient only (stage based) # 0 = inertial force only (discharge based) try: self.gamma = float(params.gamma) except Exception: if self.verbose: print("Gamma parameter not specified - using 0.05") self.gamma = 0.05 try: if params.diff_coeff < 0: if self.verbose: warnings.warn("Specified diffusion coefficient is negative" ". Rounding up to zero") params.diff_coeff = 0.0 elif params.diff_coeff >= 2: if self.verbose: warnings.warn("Diffusion behaves non-physically when" " coefficient >= 2") self.diff_coeff = float(params.diff_coeff) except Exception: if getattr(params, 'steepest_descent', False) is True: if self.verbose: print("Diffusion disabled for steepest descent") self.diff_coeff = 0.0 else: if self.verbose: print("Diffusion coefficient not specified - using 0.2") self.diff_coeff = 0.2 # Minimum depth for cell to be considered wet try: self.dry_depth = params.dry_depth except Exception: if self.verbose: print("minimum depth for wetness not defined - using 10 cm") self.dry_depth = 0.1 # Cell types: 2 = land, 1 = channel, 0 = ocean, -1 = edge try: self.cell_type = params.cell_type except Exception: if self.verbose: print("Cell Types not specified - Estimating from depth") self.cell_type = np.zeros_like(self.depth, dtype='int') self.cell_type[self.depth < self.dry_depth] = 2 self.cell_type = np.pad(self.cell_type[1:-1, 1:-1], 1, 'constant', constant_values=-1) # Steepest descent toggle - turns off randomness and uses highest # weighted value instead of doing weighted random walk # note: chooses randomly in event of ties try: if params.steepest_descent is True: if self.verbose: print("Using steepest descent") self.steepest_descent = True else: if self.verbose: print("Using weighted random walk") self.steepest_descent = False except Exception: if self.verbose: print("Using weighted random walk") self.steepest_descent = False # DEFAULT PARAMETERS (Can be defined otherwise) # sqrt2 = np.sqrt(2) sqrt05 = np.sqrt(0.5) # Define distances between cells in D8 sense try: self.distances = params.distances except Exception: # defined if not given self.distances = np.array([[sqrt2, 1, sqrt2], [1, 1, 1], [sqrt2, 1, sqrt2]]) # D8 components of x-unit vector try: self.ivec = params.ivec except Exception: # defined if not given self.ivec = np.array([[-sqrt05, 0, sqrt05], [-1, 0, 1], [-sqrt05, 0, sqrt05]]) # D8 components of y-unit vector try: self.jvec = params.jvec except Exception: # defined if not given self.jvec = np.array([[-sqrt05, -1, -sqrt05], [0, 0, 0], [sqrt05, 1, sqrt05]]) # Positive/Negative x-directions try: self.iwalk = params.iwalk except Exception: # defined if not given self.iwalk = np.array([[-1, 0, 1], [-1, 0, 1], [-1, 0, 1]]) # Positive/Negative y-directions try: self.jwalk = params.jwalk except Exception: # defined if not given self.jwalk = np.array([[-1, -1, -1], [0, 0, 0], [1, 1, 1]]) # Angles of D8 step directions try: self.angles = params.angles except Exception: # defined if not given self.angles = np.array([[3*pi/4, pi/2, pi/4], [pi, 0, 0], [5*pi/4, 3*pi/2, 7*pi/4]]) # initialize number of particles as 0 self.Np_tracer = 0 # initialize the walk_data self.walk_data = None # initialize routing weights array lw.make_weight(self) # function to clear walk data if you've made a mistake while generating it def clear_walk_data(self): """Manually reset self.walk_data back to None.""" self.walk_data = None # generate a group of particles in a set of initial locations def generate_particles(self, Np_tracer, seed_xloc, seed_yloc, seed_time=0, method='random', previous_walk_data=None): """Generate a set of particles in defined locations. After a :obj:`dorado.particle_track.Particles` class has been initialized, this function can be called to create some particles within a given region. If particles are to be seeded in different groupings in different regions, this function can be called multiple times in succession prior to moving them via :obj:`dorado.particle_track.run_iteration`. Walk data is stored within :obj:`dorado.particle_track.Particles` as `Particles.walk_data` so if this method is called in succession, even without the `previous_walk_data` flag, the new particle seed locations will be appended to the `walk_data` attribute of :obj:`dorado.particle_track.Particles`. **Inputs** : Np_tracer : `int` Number of particles to generate. seed_xloc : `list` List of x-coordinates over which to initially distribute the particles. seed_yloc : `list` List of y-coordinates over which to initially distribute the particles. seed_time : `float`, `int`, optional Seed time to apply to all newly seeded particles. This can be useful if you are generating new particles and adding them to a pre-existing set of particles and you want to run them in a group to a "target-time". The default value is 0, as new particles have not traveled for any time, but a savy user might have need to seed this value with something else. method : `str`, optional Specify the type of particle generation you wish to use. Current options are 'random' and 'exact' for seeding particles either randomly across a set of points, or exactly at a set of defined locations. If unspecified, the default is 'random'. previous_walk_data : `dict`, optional Dictionary of all prior x locations, y locations, and travel times. This input parameter should only be used if 'new' or 'indpendent' walk data exists (e.g. data loaded from a .json file). Otherwise the walk data stored in `self.walk_data` is likely to contain the previous information. Order of indices is previous_walk_data[field][particle][iter], where e.g. ['travel_times'][5][10] is the travel time of the 5th particle at the 10th iteration. """ # if the values in self are invalid the input checked will catch them # do input type checking Np_tracer, seed_xloc, seed_yloc, seed_time = gen_input_check(Np_tracer, seed_xloc, seed_yloc, seed_time, method) init_walk_data = dict() # create init_walk_data dictionary # initialize new travel times list if (seed_time != 0) and (self.verbose is True): warnings.warn("Particle seed time is nonzero," " be aware when post-processing.") new_start_times = [seed_time]*Np_tracer if method == 'random': # create random start indices based on x, y locations and np_tracer new_start_xindices = [lw.random_pick_seed(seed_xloc) for x in list(range(Np_tracer))] new_start_yindices = [lw.random_pick_seed(seed_yloc) for x in list(range(Np_tracer))] elif method == 'exact': # create exact start indices based on x, y locations and np_tracer # get number of particles per location and remainder left out Np_divy = divmod(Np_tracer, len(seed_xloc)) # assign the start locations for the evenly divided particles new_start_xindices = seed_xloc * Np_divy[0] new_start_yindices = seed_yloc * Np_divy[0] # add the remainder ones to the list one by one via looping for i in range(0, Np_divy[1]): new_start_xindices = new_start_xindices + [seed_xloc[i]] new_start_yindices = new_start_yindices + [seed_yloc[i]] # Now initialize vectors that will create the structured list new_xinds = [[new_start_xindices[i]] for i in list(range(Np_tracer))] new_yinds = [[new_start_yindices[i]] for i in list(range(Np_tracer))] new_times = [[new_start_times[i]] for i in list(range(Np_tracer))] # establish the start values start_xindices = new_xinds start_yindices = new_yinds start_times = new_times if self.walk_data is not None: # if there is walk_data from a previous call to the generator, # or from simulating particle transport previously, then we want # to keep it and append the new data to it internal_xinds = self.walk_data['xinds'] internal_yinds = self.walk_data['yinds'] internal_times = self.walk_data['travel_times'] # combine internal and new lists of particle information start_xindices = internal_xinds + start_xindices start_yindices = internal_yinds + start_yindices start_times = internal_times + start_times if previous_walk_data is not None: # If the generator has been run before, or if new # particles are going to be added to a set of pre-existing # particles, then the walk_data dictionary from either can # be fed into this function as input prev_xinds = previous_walk_data['xinds'] prev_yinds = previous_walk_data['yinds'] prev_times = previous_walk_data['travel_times'] # combine previous and new lists of particle information start_xindices = prev_xinds + start_xindices start_yindices = prev_yinds + start_yindices start_times = prev_times + start_times # determine the new total number of particles we have now self.Np_tracer = len(start_xindices) # store information in the init_walk_data dictionary and return it init_walk_data['xinds'] = start_xindices init_walk_data['yinds'] = start_yindices init_walk_data['travel_times'] = start_times # store the initialized walk data within self self.walk_data = init_walk_data # run an iteration where particles are moved # have option of specifying the particle start locations # otherwise they are randomly placed within x and y seed locations def run_iteration(self, target_time=None): """Run an iteration of the particle routing. Runs an iteration of the particle routing. Returns at each step the particle's locations and travel times. **Inputs** : target_time : `float`, optional The travel time (seconds) each particle should aim to have at end of this iteration. If left undefined, then just one iteration is run and the particles will be out of sync in time. Note that this loop will terminate before the target_time if the particle exceeds the hard-coded limit of 1e4 steps **Outputs** : all_walk_data : `dict` Dictionary of all x and y locations and travel times. Order of indices is previous_walk_data[field][particle][iter], where ['travel_times'][5][10] is the travel time of the 5th particle at the 10th iteration """ # if there is no walk data raise an error if self.walk_data is None: raise ValueError('Particles have not been initialized.' ' Call the `particle_generator()` function.') all_walk_data = dict() # init all_walk_data dictionary # if self.Np_tracer is not already defined, we can define it from # the init_walk_data if self.Np_tracer == 0: self.Np_tracer = len(self.walk_data['xinds']) # read in information from the init_walk_data dictionary # most recent locations all_xinds = self.walk_data['xinds'] start_xindices = [all_xinds[i][-1] for i in list(range(self.Np_tracer))] all_yinds = self.walk_data['yinds'] start_yindices = [all_yinds[i][-1] for i in list(range(self.Np_tracer))] # most recent times all_times = self.walk_data['travel_times'] start_times = [all_times[i][-1] for i in list(range(self.Np_tracer))] # merge x and y indices into list of [x,y] pairs start_pairs = [[start_xindices[i], start_yindices[i]] for i in list(range(self.Np_tracer))] # Do the particle movement if target_time is None: # If we're not aiming for a specific time, step the particles new_inds, travel_times = lw.particle_stepper(self, start_pairs, start_times) for ii in list(range(self.Np_tracer)): # Don't duplicate location # if particle is standing still at a boundary if new_inds[ii] != start_pairs[ii]: # Append new information all_xinds[ii].append(new_inds[ii][0]) all_yinds[ii].append(new_inds[ii][1]) all_times[ii].append(travel_times[ii]) # Store travel information in all_walk_data all_walk_data['xinds'] = all_xinds all_walk_data['yinds'] = all_yinds all_walk_data['travel_times'] = all_times else: # If we ARE aiming for a specific time # iterate each particle until we get there # Loop through all particles for ii in list(range(self.Np_tracer)): if len(all_times[ii]) > 1: est_next_dt = all_times[ii][-1] - all_times[ii][-2] else: # Initialize a guess for the next iteration's timestep est_next_dt = 0.1 count = 1 # init list for too many particle iterations _iter_particles = [] # Only iterate if this particle isn't already at a boundary: if -1 not in self.cell_type[all_xinds[ii][-1]-1: all_xinds[ii][-1]+2, all_yinds[ii][-1]-1: all_yinds[ii][-1]+2]: # Loop until |target time - current time| < # |target time - estimated next time| while abs(all_times[ii][-1] - target_time) >= \ abs(all_times[ii][-1] + est_next_dt - target_time): # for particle ii, take a step from most recent index new_inds, travel_times = lw.particle_stepper( self, [[all_xinds[ii][-1], all_yinds[ii][-1]]], [all_times[ii][-1]]) # Don't duplicate location # if particle is standing still at a boundary if new_inds[0] != [all_xinds[ii][-1], all_yinds[ii][-1]]: all_xinds[ii].append(new_inds[0][0]) all_yinds[ii].append(new_inds[0][1]) all_times[ii].append(travel_times[0]) else: break # Use that timestep to estimate how long the # next one will take est_next_dt = max(0.1, all_times[ii][-1] - all_times[ii][-2]) count += 1 if count > 1e4: _iter_particles.append(ii) break # Store travel information in all_walk_data all_walk_data['xinds'] = all_xinds all_walk_data['yinds'] = all_yinds all_walk_data['travel_times'] = all_times # write out warning if particles exceed step limit if (len(_iter_particles) > 0) and (self.verbose is True): warnings.warn(str(len(_iter_particles)) + "Particles" " exceeded iteration limit before reaching the" " target time, consider using a smaller" " time-step. Particles are: " + str(_iter_particles)) # re-write the walk_data attribute of self self.walk_data = all_walk_data return all_walk_data def gen_input_check(Np_tracer, seed_xloc, seed_yloc, seed_time, method): """Check the inputs provided to :obj:`generate_particles()`. This function does input type checking and either succeeds or returns an error if the types provided cannot be converted to those that we expect in :obj:`dorado.particle_track.generate_particles()`. **Inputs** : Np_tracer : `int` Number of particles to generate. seed_xloc : `list` List of x-coordinates over which to initially distribute the particles seed_yloc : `list` List of y-coordinates over which to initially distribute the particles seed_time : `int`, `float` Value to set as initial travel time for newly seeded particles. method : `str`, optional Type of particle generation to use, either 'random' or 'exact'. **Outputs** : Np_tracer : `int` Number of particles to generate. seed_xloc : `list` List of x-coordinates over which to initially distribute the particles seed_yloc : `list` List of y-coordinates over which to initially distribute the particles """ try: Np_tracer = int(Np_tracer) except Exception: raise TypeError("Np_tracer input type was not int.") try: # try to flatten if this is an array that is multi-dimensional if len(np.shape(seed_xloc)) > 1: seed_xloc = seed_xloc.flatten() # try to coerce into a list seed_xloc = [int(x) for x in list(seed_xloc)] except Exception: raise TypeError("seed_xloc input type was not a list.") try: # try to flatten if this is an array that is multi-dimensional if len(np.shape(seed_yloc)) > 1: seed_yloc = seed_yloc.flatten() # try to coerce into a list seed_yloc = [int(y) for y in list(seed_yloc)] except Exception: raise TypeError("seed_yloc input type was not a list.") if (isinstance(seed_time, float) is False) and \ (isinstance(seed_time, int) is False): raise TypeError('seed_time provided was not a float or int') if isinstance(method, str) is False: raise TypeError('Method provided was not a string.') elif method not in ['random', 'exact']: raise ValueError('Method input is not a valid method, must be' ' "random" or "exact".') return Np_tracer, seed_xloc, seed_yloc, seed_time def coord2ind(coordinates, raster_origin, raster_size, cellsize): """Convert geographical coordinates into raster index coordinates. Assumes geographic coordinates are projected onto a Cartesian grid. Accepts coordinates in meters or decimal degrees. **Inputs** : coordinates : `list` List [] of (x,y) pairs or tuples of coordinates to be converted from starting units (e.g. meters UTM) into raster index coordinates used in particle routing functions. raster_origin : `tuple` Tuple of the (x,y) raster origin in physical space, i.e. the coordinates of lower left corner. For rasters loaded from a GeoTIFF, lower left corner can be obtained using e.g. gdalinfo raster_size : `tuple` Tuple (L,W) of the raster dimensions, i.e. the output of numpy.shape(raster). cellsize : `float or int` Length along one square cell face. **Outputs** : inds : `list` List [] of tuples (x,y) of raster index coordinates """ x_orig = float(raster_origin[0]) y_orig = float(raster_origin[1]) cellsize = float(cellsize) L = int(raster_size[0]) # Need domain extent inds = [] for i in list(range(0, len(coordinates))): # Do coordinate transform: new_ind = (int(L - round((coordinates[i][1] - y_orig)/cellsize)), int(round((coordinates[i][0] - x_orig)/cellsize))) inds.append(new_ind) return inds def ind2coord(walk_data, raster_origin, raster_size, cellsize): """Convert raster index coordinates into geographical coordinates. Appends the walk_data dictionary from the output of run_iteration with additional fields 'xcoord' and 'ycoord' in projected geographic coordinate space. Locations align with cell centroids. Units of output coordinates match those of raster_origin and cellsize, can be meters or decimal degrees. **Inputs** : walk_data : `dict` Dictionary of all prior x locations, y locations, and travel times (the output of run_iteration) raster_origin : `tuple` Tuple of the (x,y) raster origin in physical space, i.e. the coordinates of lower left corner. For rasters loaded from a GeoTIFF, lower left corner can be obtained using e.g. gdalinfo raster_size : `tuple` Tuple (L,W) of the raster dimensions, i.e. the output of numpy.shape(raster). cellsize : `float or int` Length along one square cell face. **Outputs** : walk_data : `dict` Same as the input walk_data dictionary, with the added 'xcoord' and 'ycoord' fields representing the particles geographic position at each iteration. """ x_orig = float(raster_origin[0]) y_orig = float(raster_origin[1]) cellsize = float(cellsize) L = int(raster_size[0]) # Need domain extent Np_tracer = len(walk_data['xinds']) # Get number of particles all_xcoord = [] # Initialize all_ycoord = [] for i in list(range(0, Np_tracer)): # Do coordinate transform: this_ycoord = [(L-float(j))*cellsize+y_orig for j in walk_data['xinds'][i]] all_ycoord.append(this_ycoord) this_xcoord = [float(j)*cellsize+x_orig for j in walk_data['yinds'][i]] all_xcoord.append(this_xcoord) # Save back into dict: walk_data['xcoord'] = all_xcoord walk_data['ycoord'] = all_ycoord return walk_data def exposure_time(walk_data, region_of_interest): """Measure exposure time distribution of particles in a specified region. Function to measure the exposure time distribution (ETD) of particles to the specified region. For steady flows, the ETD is exactly equivalent to the residence time distribution. For unsteady flows, if particles make multiple excursions into the region, all of those times are counted. **Inputs** : walk_data : `dict` Output of a previous function call to run_iteration. region_of_interest : `int array` Binary array the same size as input arrays in modelParams class with 1's everywhere inside the region in which we want to measure exposure time, and 0's everywhere else. **Outputs** : exposure_times : `list` List of exposure times to region of interest, listed in order of particle ID. """ # Initialize arrays to record exposure time of each particle Np_tracer = len(walk_data['xinds']) # Number of particles # Array to be populated exposure_times = np.zeros([Np_tracer], dtype='float') # list of particles that don't exit ROI _short_list = [] # Loop through particles to measure exposure time for ii in tqdm(list(range(0, Np_tracer)), ascii=True): # Determine the starting region for particle ii previous_reg = region_of_interest[int(walk_data['xinds'][ii][0]), int(walk_data['yinds'][ii][0])] # Loop through iterations for jj in list(range(1, len(walk_data['travel_times'][ii]))): # Determine the new region and compare to previous region current_reg = region_of_interest[int(walk_data['xinds'][ii][jj]), int(walk_data['yinds'][ii][jj])] # Check to see if whole step was inside ROI # If so, travel time of the whole step added to ET if (current_reg + previous_reg) == 2: exposure_times[ii] += (walk_data['travel_times'][ii][jj] - walk_data['travel_times'][ii][jj-1]) # Check to see if half of the step was inside ROI # (either entering or exiting) # If so, travel time of half of the step added to ET elif (current_reg + previous_reg) == 1: exposure_times[ii] += 0.5*(walk_data['travel_times'][ii][jj] - walk_data['travel_times'][ii][jj-1]) # Update previous region previous_reg = current_reg # Check if particle is still stuck in ROI at the end of the run # (which can bias result) if jj == len(walk_data['travel_times'][ii])-1: if current_reg == 1: _short_list.append(ii) # add particle number to list # single print statement if len(_short_list) > 0: print(str(len(_short_list)) + ' Particles within ROI at final' ' timestep.\n' + 'Particles are: ' + str(_short_list) + '\nRun more iterations to get full tail of ETD.') return exposure_times.tolist() def nourishment_area(walk_data, raster_size, sigma=0.7, clip=99.5): """Determine the nourishment area of a particle injection Function will measure the regions of the domain 'fed' by a seed location, as indicated by the history of particle travel locations in walk_data. Returns a heatmap raster, in which values indicate number of occasions each cell was occupied by a particle (after spatial filtering to reduce noise in the random walk, and normalizing by number of particles). **Inputs** : walk_data : `dict` Dictionary of all prior x locations, y locations, and travel times (the output of run_iteration) raster_size : `tuple` Tuple (L,W) of the domain dimensions, i.e. the output of numpy.shape(raster). sigma : `float`, optional Degree of spatial smoothing of the area, implemented using a Gaussian kernal of the same sigma, via scipy.ndimage.gaussian_filter Default is light smoothing with sigma = 0.7 (to turn off smoothing, set sigma = 0) clip : `float`, optional Percentile at which to truncate the distribution. Particles which get stuck can lead to errors at the high-extreme, so this parameter is used to normalize by a "near-max". Default is the 99.5th percentile. To use true max, specify clip = 100 **Outputs** : visit_freq : `numpy.ndarray` Array of normalized particle visit frequency, with cells in the range [0, 1] representing the number of instances particles visited that cell. If sigma > 0, the array values include spatial filtering """ if sigma > 0: from scipy.ndimage import gaussian_filter # Measure visit frequency visit_freq = np.zeros(raster_size) for ii in list(range(len(walk_data['xinds']))): for jj in list(range(len(walk_data['xinds'][ii]))): visit_freq[walk_data['xinds'][ii][jj], walk_data['yinds'][ii][jj]] += 1 # Clip out highest percentile to correct possible outliers vmax = float(np.nanpercentile(visit_freq, clip)) visit_freq = np.clip(visit_freq, 0, vmax) # If applicable, do smoothing if sigma > 0: visit_freq = gaussian_filter(visit_freq, sigma=sigma) visit_freq[visit_freq==np.min(visit_freq)] = np.nan else: visit_freq[visit_freq==0] = np.nan # Normalize to 0-1 visit_freq = visit_freq/np.nanmax(visit_freq) return visit_freq def nourishment_time(walk_data, raster_size, sigma=0.7, clip=99.5): """Determine the nourishment time of a particle injection Function will measure the average length of time particles spend in each area of the domain for a given seed location, as indicated by the history of particle travel times in walk_data. Returns a heatmap raster, in which values indicate the average length of time particles tend to remain in each cell (after spatial filtering to reduce noise in the random walk). **Inputs** : walk_data : `dict` Dictionary of all prior x locations, y locations, and travel times (the output of run_iteration) raster_size : `tuple` Tuple (L,W) of the domain dimensions, i.e. the output of numpy.shape(raster). sigma : `float`, optional Degree of spatial smoothing of the area, implemented using a Gaussian kernal of the same sigma, via scipy.ndimage.gaussian_filter Default is light smoothing with sigma = 0.7 (to turn off smoothing, set sigma = 0) clip : `float`, optional Percentile at which to truncate the distribution. Particles which get stuck can lead to errors at the high-extreme, so this parameter is used to normalize by a "near-max". Default is the 99.5th percentile. To use true max, specify clip = 100 **Outputs** : mean_time : `numpy.ndarray` Array of mean occupation time, with cell values representing the mean time particles spent in that cell. If sigma > 0, the array values include spatial filtering """ if sigma > 0: from scipy.ndimage import gaussian_filter # Measure visit frequency visit_freq = np.zeros(raster_size) time_total = visit_freq.copy() for ii in list(range(len(walk_data['xinds']))): for jj in list(range(1, len(walk_data['xinds'][ii])-1)): # Running total of particles in this cell to find average visit_freq[walk_data['xinds'][ii][jj], walk_data['yinds'][ii][jj]] += 1 # Count the time in this cell as 0.5*last_dt + 0.5*next_dt last_dt = (walk_data['travel_times'][ii][jj] - \ walk_data['travel_times'][ii][jj-1]) next_dt = (walk_data['travel_times'][ii][jj+1] - \ walk_data['travel_times'][ii][jj]) time_total[walk_data['xinds'][ii][jj], walk_data['yinds'][ii][jj]] += 0.5*(last_dt + next_dt) # Find mean time in each cell with np.errstate(divide='ignore', invalid='ignore'): mean_time = time_total / visit_freq mean_time[visit_freq == 0] = 0 # Prone to numerical outliers, so clip out extremes vmax = float(np.nanpercentile(mean_time, clip)) mean_time = np.clip(mean_time, 0, vmax) # If applicable, do smoothing if sigma > 0: mean_time = gaussian_filter(mean_time, sigma=sigma) mean_time[mean_time==np.min(mean_time)] = np.nan else: mean_time[mean_time==0] = np.nan return mean_time def unstruct2grid(coordinates, quantity, cellsize, k_nearest_neighbors=3, boundary=None, crop=True): """Convert unstructured model outputs into gridded arrays. Interpolates model variables (e.g. depth, velocity) from an unstructured grid onto a Cartesian grid using inverse-distance-weighted interpolation. Assumes projected (i.e. "flat") geographic coordinates. Accepts coordinates in meters or decimal degrees. Extent of output rasters are based on extent of coordinates. (Function modeled after ANUGA plot_utils code) **Inputs** : coordinates : `list` List [] of (x,y) pairs or tuples of coordinates at which the interpolation quantities are located (e.g. centroids or vertices of an unstructured hydrodynamic model). quantity : `list` List [] of data to be interpolated with indices matching each (x,y) location given in coordinates. If quantity is depth, list would be formatted as [d1, d2, ... , dn]. cellsize : `float or int` Length along one square cell face. k_nearest_neighbors : `int`, optional Number of nearest neighbors to use in the interpolation. If k>1, inverse-distance-weighted interpolation is used. boundary : `list`, optional List [] of (x,y) coordinates used to delineate the boundary of interpolation. Points outside the polygon will be assigned as nan. Format needs to match requirements of matplotlib.path.Path() crop : `bool`, optional If a boundary is specified, setting crop to True will eliminate any all-NaN borders from the interpolated rasters. **Outputs** : interp_func : `function` Nearest-neighbor interpolation function for gridding additional quantities. Quicker to use this output function on additional variables (e.g. later time-steps of an unsteady model) than to make additional function calls to unstruct2grid. Function assumes data have the same coordinates. It is used as follows: "new_gridded_quantity = interp_func(new_quantity)". gridded_quantity : `numpy.ndarray` Array of quantity after interpolation. """ import matplotlib import scipy from scipy import interpolate cellsize = float(cellsize) # Make sure all input values are floats x = [float(i) for i, j in coordinates] y = [float(j) for i, j in coordinates] quantity = np.array([float(i) for i in quantity]) if len(quantity) != len(x): raise ValueError("Coordinate and quantity arrays must be equal length") # Get some dimensions and make x,y grid nx = int(np.ceil((max(x)-min(x))/cellsize)+1) xvect = np.linspace(min(x), min(x)+cellsize*(nx-1), nx) ny = int(np.ceil((max(y)-min(y))/cellsize)+1) yvect = np.linspace(min(y), min(y)+cellsize*(ny-1), ny) gridX, gridY = np.meshgrid(xvect, yvect) inputXY = np.array([x[:], y[:]]).transpose() gridXY_array = np.array([np.concatenate(gridX), np.concatenate(gridY)]).transpose() gridXY_array = np.ascontiguousarray(gridXY_array) # If a boundary has been specified, create array to index outside it if boundary is not None: path = matplotlib.path.Path(boundary) outside = ~path.contains_points(gridXY_array) # Create Interpolation function if k_nearest_neighbors == 1: # Only use nearest neighbor index_qFun = interpolate.NearestNDInterpolator(inputXY, np.arange(len(x), dtype='int64').transpose()) gridqInd = index_qFun(gridXY_array) # Function to do the interpolation def interp_func(data): if isinstance(data, list): data = np.array(data) gridded_data = data[gridqInd].astype(float) if boundary is not None: gridded_data[outside] = np.nan # Crop to bounds gridded_data.shape = (len(yvect), len(xvect)) gridded_data = np.flipud(gridded_data) if boundary is not None and crop is True: mask = ~np.isnan(gridded_data) # Delete all-nan border gridded_data = gridded_data[np.ix_(mask.any(1), mask.any(0))] return gridded_data else: # Inverse-distance interpolation index_qFun = scipy.spatial.cKDTree(inputXY) NNInfo = index_qFun.query(gridXY_array, k=k_nearest_neighbors) # Weights for interpolation nn_wts = 1./(NNInfo[0]+1.0e-100) nn_inds = NNInfo[1] def interp_func(data): if isinstance(data, list): data = np.array(data) denom = 0. num = 0. for i in list(range(k_nearest_neighbors)): denom += nn_wts[:, i] num += data[nn_inds[:, i]].astype(float)*nn_wts[:, i] gridded_data = (num/denom) if boundary is not None: gridded_data[outside] = np.nan # Crop to bounds gridded_data.shape = (len(yvect), len(xvect)) gridded_data = np.flipud(gridded_data) if boundary is not None and crop is True: mask = ~np.isnan(gridded_data) # Delete all-nan border gridded_data = gridded_data[np.ix_(mask.any(1), mask.any(0))] return gridded_data # Finally, call the interpolation function to create array: gridded_quantity = interp_func(quantity) return interp_func, gridded_quantity
[ "numpy.nanpercentile", "numpy.arctan2", "numpy.abs", "numpy.clip", "numpy.isnan", "numpy.shape", "scipy.spatial.cKDTree", "builtins.range", "numpy.pad", "numpy.meshgrid", "numpy.zeros_like", "scipy.ndimage.gaussian_filter", "dorado.lagrangian_walker.make_weight", "numpy.flipud", "numpy.m...
[((36873, 36909), 'numpy.zeros', 'np.zeros', (['[Np_tracer]'], {'dtype': '"""float"""'}), "([Np_tracer], dtype='float')\n", (36881, 36909), True, 'import numpy as np\n'), ((40834, 40855), 'numpy.zeros', 'np.zeros', (['raster_size'], {}), '(raster_size)\n', (40842, 40855), True, 'import numpy as np\n'), ((41209, 41237), 'numpy.clip', 'np.clip', (['visit_freq', '(0)', 'vmax'], {}), '(visit_freq, 0, vmax)\n', (41216, 41237), True, 'import numpy as np\n'), ((43379, 43400), 'numpy.zeros', 'np.zeros', (['raster_size'], {}), '(raster_size)\n', (43387, 43400), True, 'import numpy as np\n'), ((44466, 44493), 'numpy.clip', 'np.clip', (['mean_time', '(0)', 'vmax'], {}), '(mean_time, 0, vmax)\n', (44473, 44493), True, 'import numpy as np\n'), ((47841, 47866), 'numpy.meshgrid', 'np.meshgrid', (['xvect', 'yvect'], {}), '(xvect, yvect)\n', (47852, 47866), True, 'import numpy as np\n'), ((48054, 48088), 'numpy.ascontiguousarray', 'np.ascontiguousarray', (['gridXY_array'], {}), '(gridXY_array)\n', (48074, 48088), True, 'import numpy as np\n'), ((9766, 9800), 'numpy.sqrt', 'np.sqrt', (['(self.u ** 2 + self.v ** 2)'], {}), '(self.u ** 2 + self.v ** 2)\n', (9773, 9800), True, 'import numpy as np\n'), ((10083, 10116), 'numpy.arctan2', 'np.arctan2', (['(-1.0 * self.u)', 'self.v'], {}), '(-1.0 * self.u, self.v)\n', (10093, 10116), True, 'import numpy as np\n'), ((13436, 13446), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (13443, 13446), True, 'import numpy as np\n'), ((13464, 13476), 'numpy.sqrt', 'np.sqrt', (['(0.5)'], {}), '(0.5)\n', (13471, 13476), True, 'import numpy as np\n'), ((15547, 15567), 'dorado.lagrangian_walker.make_weight', 'lw.make_weight', (['self'], {}), '(self)\n', (15561, 15567), True, 'import dorado.lagrangian_walker as lw\n'), ((35276, 35295), 'builtins.range', 'range', (['(0)', 'Np_tracer'], {}), '(0, Np_tracer)\n', (35281, 35295), False, 'from builtins import range\n'), ((41156, 41190), 'numpy.nanpercentile', 'np.nanpercentile', (['visit_freq', 'clip'], {}), '(visit_freq, clip)\n', (41172, 41190), True, 'import numpy as np\n'), ((41312, 41352), 'scipy.ndimage.gaussian_filter', 'gaussian_filter', (['visit_freq'], {'sigma': 'sigma'}), '(visit_freq, sigma=sigma)\n', (41327, 41352), False, 'from scipy.ndimage import gaussian_filter\n'), ((41518, 41539), 'numpy.nanmax', 'np.nanmax', (['visit_freq'], {}), '(visit_freq)\n', (41527, 41539), True, 'import numpy as np\n'), ((44215, 44261), 'numpy.errstate', 'np.errstate', ([], {'divide': '"""ignore"""', 'invalid': '"""ignore"""'}), "(divide='ignore', invalid='ignore')\n", (44226, 44261), True, 'import numpy as np\n'), ((44415, 44448), 'numpy.nanpercentile', 'np.nanpercentile', (['mean_time', 'clip'], {}), '(mean_time, clip)\n', (44431, 44448), True, 'import numpy as np\n'), ((44567, 44606), 'scipy.ndimage.gaussian_filter', 'gaussian_filter', (['mean_time'], {'sigma': 'sigma'}), '(mean_time, sigma=sigma)\n', (44582, 44606), False, 'from scipy.ndimage import gaussian_filter\n'), ((48207, 48237), 'matplotlib.path.Path', 'matplotlib.path.Path', (['boundary'], {}), '(boundary)\n', (48227, 48237), False, 'import matplotlib\n'), ((49342, 49372), 'scipy.spatial.cKDTree', 'scipy.spatial.cKDTree', (['inputXY'], {}), '(inputXY)\n', (49363, 49372), False, 'import scipy\n'), ((19471, 19549), 'warnings.warn', 'warnings.warn', (['"""Particle seed time is nonzero, be aware when post-processing."""'], {}), "('Particle seed time is nonzero, be aware when post-processing.')\n", (19484, 19549), False, 'import warnings\n'), ((25612, 25663), 'dorado.lagrangian_walker.particle_stepper', 'lw.particle_stepper', (['self', 'start_pairs', 'start_times'], {}), '(self, start_pairs, start_times)\n', (25631, 25663), True, 'import dorado.lagrangian_walker as lw\n'), ((37054, 37073), 'builtins.range', 'range', (['(0)', 'Np_tracer'], {}), '(0, Np_tracer)\n', (37059, 37073), False, 'from builtins import range\n'), ((47882, 47904), 'numpy.array', 'np.array', (['[x[:], y[:]]'], {}), '([x[:], y[:]])\n', (47890, 47904), True, 'import numpy as np\n'), ((48960, 48983), 'numpy.flipud', 'np.flipud', (['gridded_data'], {}), '(gridded_data)\n', (48969, 48983), True, 'import numpy as np\n'), ((50090, 50113), 'numpy.flipud', 'np.flipud', (['gridded_data'], {}), '(gridded_data)\n', (50099, 50113), True, 'import numpy as np\n'), ((9926, 9940), 'numpy.abs', 'np.abs', (['self.u'], {}), '(self.u)\n', (9932, 9940), True, 'import numpy as np\n'), ((9971, 9985), 'numpy.abs', 'np.abs', (['self.v'], {}), '(self.v)\n', (9977, 9985), True, 'import numpy as np\n'), ((12445, 12483), 'numpy.zeros_like', 'np.zeros_like', (['self.depth'], {'dtype': '"""int"""'}), "(self.depth, dtype='int')\n", (12458, 12483), True, 'import numpy as np\n'), ((12573, 12642), 'numpy.pad', 'np.pad', (['self.cell_type[1:-1, 1:-1]', '(1)', '"""constant"""'], {'constant_values': '(-1)'}), "(self.cell_type[1:-1, 1:-1], 1, 'constant', constant_values=-1)\n", (12579, 12642), True, 'import numpy as np\n'), ((13680, 13739), 'numpy.array', 'np.array', (['[[sqrt2, 1, sqrt2], [1, 1, 1], [sqrt2, 1, sqrt2]]'], {}), '([[sqrt2, 1, sqrt2], [1, 1, 1], [sqrt2, 1, sqrt2]])\n', (13688, 13739), True, 'import numpy as np\n'), ((13994, 14060), 'numpy.array', 'np.array', (['[[-sqrt05, 0, sqrt05], [-1, 0, 1], [-sqrt05, 0, sqrt05]]'], {}), '([[-sqrt05, 0, sqrt05], [-1, 0, 1], [-sqrt05, 0, sqrt05]])\n', (14002, 14060), True, 'import numpy as np\n'), ((14305, 14371), 'numpy.array', 'np.array', (['[[-sqrt05, -1, -sqrt05], [0, 0, 0], [sqrt05, 1, sqrt05]]'], {}), '([[-sqrt05, -1, -sqrt05], [0, 0, 0], [sqrt05, 1, sqrt05]])\n', (14313, 14371), True, 'import numpy as np\n'), ((14619, 14665), 'numpy.array', 'np.array', (['[[-1, 0, 1], [-1, 0, 1], [-1, 0, 1]]'], {}), '([[-1, 0, 1], [-1, 0, 1], [-1, 0, 1]])\n', (14627, 14665), True, 'import numpy as np\n'), ((14915, 14961), 'numpy.array', 'np.array', (['[[-1, -1, -1], [0, 0, 0], [1, 1, 1]]'], {}), '([[-1, -1, -1], [0, 0, 0], [1, 1, 1]])\n', (14923, 14961), True, 'import numpy as np\n'), ((15212, 15306), 'numpy.array', 'np.array', (['[[3 * pi / 4, pi / 2, pi / 4], [pi, 0, 0], [5 * pi / 4, 3 * pi / 2, 7 * pi / 4]\n ]'], {}), '([[3 * pi / 4, pi / 2, pi / 4], [pi, 0, 0], [5 * pi / 4, 3 * pi / 2,\n 7 * pi / 4]])\n', (15220, 15306), True, 'import numpy as np\n'), ((19773, 19803), 'dorado.lagrangian_walker.random_pick_seed', 'lw.random_pick_seed', (['seed_xloc'], {}), '(seed_xloc)\n', (19792, 19803), True, 'import dorado.lagrangian_walker as lw\n'), ((19905, 19935), 'dorado.lagrangian_walker.random_pick_seed', 'lw.random_pick_seed', (['seed_yloc'], {}), '(seed_yloc)\n', (19924, 19935), True, 'import dorado.lagrangian_walker as lw\n'), ((20524, 20544), 'builtins.range', 'range', (['(0)', 'Np_divy[1]'], {}), '(0, Np_divy[1])\n', (20529, 20544), False, 'from builtins import range\n'), ((25749, 25770), 'builtins.range', 'range', (['self.Np_tracer'], {}), '(self.Np_tracer)\n', (25754, 25770), False, 'from builtins import range\n'), ((26544, 26565), 'builtins.range', 'range', (['self.Np_tracer'], {}), '(self.Np_tracer)\n', (26549, 26565), False, 'from builtins import range\n'), ((31027, 31046), 'numpy.shape', 'np.shape', (['seed_xloc'], {}), '(seed_xloc)\n', (31035, 31046), True, 'import numpy as np\n'), ((31368, 31387), 'numpy.shape', 'np.shape', (['seed_yloc'], {}), '(seed_yloc)\n', (31376, 31387), True, 'import numpy as np\n'), ((41384, 41402), 'numpy.min', 'np.min', (['visit_freq'], {}), '(visit_freq)\n', (41390, 41402), True, 'import numpy as np\n'), ((44636, 44653), 'numpy.min', 'np.min', (['mean_time'], {}), '(mean_time)\n', (44642, 44653), True, 'import numpy as np\n'), ((48703, 48717), 'numpy.array', 'np.array', (['data'], {}), '(data)\n', (48711, 48717), True, 'import numpy as np\n'), ((49643, 49657), 'numpy.array', 'np.array', (['data'], {}), '(data)\n', (49651, 49657), True, 'import numpy as np\n'), ((49728, 49754), 'builtins.range', 'range', (['k_nearest_neighbors'], {}), '(k_nearest_neighbors)\n', (49733, 49754), False, 'from builtins import range\n'), ((5890, 5910), 'numpy.isnan', 'np.isnan', (['self.depth'], {}), '(self.depth)\n', (5898, 5910), True, 'import numpy as np\n'), ((7944, 7961), 'numpy.isnan', 'np.isnan', (['self.qx'], {}), '(self.qx)\n', (7952, 7961), True, 'import numpy as np\n'), ((8057, 8073), 'numpy.isnan', 'np.isnan', (['self.u'], {}), '(self.u)\n', (8065, 8073), True, 'import numpy as np\n'), ((8140, 8157), 'numpy.isnan', 'np.isnan', (['self.qy'], {}), '(self.qy)\n', (8148, 8157), True, 'import numpy as np\n'), ((8253, 8269), 'numpy.isnan', 'np.isnan', (['self.v'], {}), '(self.v)\n', (8261, 8269), True, 'import numpy as np\n'), ((8874, 8891), 'numpy.isnan', 'np.isnan', (['self.qx'], {}), '(self.qx)\n', (8882, 8891), True, 'import numpy as np\n'), ((8987, 9003), 'numpy.isnan', 'np.isnan', (['self.u'], {}), '(self.u)\n', (8995, 9003), True, 'import numpy as np\n'), ((9070, 9087), 'numpy.isnan', 'np.isnan', (['self.qy'], {}), '(self.qy)\n', (9078, 9087), True, 'import numpy as np\n'), ((9183, 9199), 'numpy.isnan', 'np.isnan', (['self.v'], {}), '(self.v)\n', (9191, 9199), True, 'import numpy as np\n'), ((11066, 11152), 'warnings.warn', 'warnings.warn', (['"""Specified diffusion coefficient is negative. Rounding up to zero"""'], {}), "(\n 'Specified diffusion coefficient is negative. Rounding up to zero')\n", (11079, 11152), False, 'import warnings\n'), ((20843, 20859), 'builtins.range', 'range', (['Np_tracer'], {}), '(Np_tracer)\n', (20848, 20859), False, 'from builtins import range\n'), ((20942, 20958), 'builtins.range', 'range', (['Np_tracer'], {}), '(Np_tracer)\n', (20947, 20958), False, 'from builtins import range\n'), ((21017, 21033), 'builtins.range', 'range', (['Np_tracer'], {}), '(Np_tracer)\n', (21022, 21033), False, 'from builtins import range\n'), ((24897, 24918), 'builtins.range', 'range', (['self.Np_tracer'], {}), '(self.Np_tracer)\n', (24902, 24918), False, 'from builtins import range\n'), ((25048, 25069), 'builtins.range', 'range', (['self.Np_tracer'], {}), '(self.Np_tracer)\n', (25053, 25069), False, 'from builtins import range\n'), ((25228, 25249), 'builtins.range', 'range', (['self.Np_tracer'], {}), '(self.Np_tracer)\n', (25233, 25249), False, 'from builtins import range\n'), ((25409, 25430), 'builtins.range', 'range', (['self.Np_tracer'], {}), '(self.Np_tracer)\n', (25414, 25430), False, 'from builtins import range\n'), ((47947, 47968), 'numpy.concatenate', 'np.concatenate', (['gridX'], {}), '(gridX)\n', (47961, 47968), True, 'import numpy as np\n'), ((47999, 48020), 'numpy.concatenate', 'np.concatenate', (['gridY'], {}), '(gridY)\n', (48013, 48020), True, 'import numpy as np\n'), ((49062, 49084), 'numpy.isnan', 'np.isnan', (['gridded_data'], {}), '(gridded_data)\n', (49070, 49084), True, 'import numpy as np\n'), ((50192, 50214), 'numpy.isnan', 'np.isnan', (['gridded_data'], {}), '(gridded_data)\n', (50200, 50214), True, 'import numpy as np\n'), ((6427, 6447), 'numpy.isnan', 'np.isnan', (['self.depth'], {}), '(self.depth)\n', (6435, 6447), True, 'import numpy as np\n'), ((8397, 8413), 'numpy.isnan', 'np.isnan', (['self.u'], {}), '(self.u)\n', (8405, 8413), True, 'import numpy as np\n'), ((8521, 8537), 'numpy.isnan', 'np.isnan', (['self.v'], {}), '(self.v)\n', (8529, 8537), True, 'import numpy as np\n'), ((9330, 9346), 'numpy.isnan', 'np.isnan', (['self.u'], {}), '(self.u)\n', (9338, 9346), True, 'import numpy as np\n'), ((9454, 9470), 'numpy.isnan', 'np.isnan', (['self.v'], {}), '(self.v)\n', (9462, 9470), True, 'import numpy as np\n'), ((11319, 11390), 'warnings.warn', 'warnings.warn', (['"""Diffusion behaves non-physically when coefficient >= 2"""'], {}), "('Diffusion behaves non-physically when coefficient >= 2')\n", (11332, 11390), False, 'import warnings\n'), ((19852, 19868), 'builtins.range', 'range', (['Np_tracer'], {}), '(Np_tracer)\n', (19857, 19868), False, 'from builtins import range\n'), ((19984, 20000), 'builtins.range', 'range', (['Np_tracer'], {}), '(Np_tracer)\n', (19989, 20000), False, 'from builtins import range\n'), ((27688, 27781), 'dorado.lagrangian_walker.particle_stepper', 'lw.particle_stepper', (['self', '[[all_xinds[ii][-1], all_yinds[ii][-1]]]', '[all_times[ii][-1]]'], {}), '(self, [[all_xinds[ii][-1], all_yinds[ii][-1]]], [\n all_times[ii][-1]])\n', (27707, 27781), True, 'import dorado.lagrangian_walker as lw\n')]
import pandas as pd import numpy as np from keras.models import Sequential, Model from keras.layers import Dense, Dropout, Flatten, Input, Activation, BatchNormalization from keras.layers import Conv2D, MaxPooling2D from keras.callbacks import EarlyStopping, ModelCheckpoint, ReduceLROnPlateau from keras.layers.normalization import BatchNormalization from keras.optimizers import Adam import cv2 import keras np.random.seed(1207) """ """ def get_scaled_imgs(df): imgs = [] for i, row in df.iterrows(): # make 75x75 image band_1 = np.array(row['band_1']).reshape(75, 75) band_2 = np.array(row['band_2']).reshape(75, 75) band_3 = band_1 + band_2 # plus since log(x*y) = log(x) + log(y) # Rescale a = (band_1 - band_1.mean()) / (band_1.max() - band_1.min()) b = (band_2 - band_2.mean()) / (band_2.max() - band_2.min()) c = (band_3 - band_3.mean()) / (band_3.max() - band_3.min()) imgs.append(np.dstack((a, b, c))) return np.array(imgs) def get_more_images(imgs): more_images = [] vert_flip_imgs = [] hori_flip_imgs = [] for i in range(0, imgs.shape[0]): a = imgs[i, :, :, 0] b = imgs[i, :, :, 1] c = imgs[i, :, :, 2] av = cv2.flip(a, 1) ah = cv2.flip(a, 0) bv = cv2.flip(b, 1) bh = cv2.flip(b, 0) cv = cv2.flip(c, 1) ch = cv2.flip(c, 0) vert_flip_imgs.append(np.dstack((av, bv, cv))) hori_flip_imgs.append(np.dstack((ah, bh, ch))) v = np.array(vert_flip_imgs) h = np.array(hori_flip_imgs) more_images = np.concatenate((imgs, v, h)) return more_images def getModel(): # Build keras model image_model = Sequential() # CNN 1 image_model.add(Conv2D(64, kernel_size=(3, 3), activation='relu', input_shape=(75, 75, 3))) image_model.add(Conv2D(64, kernel_size=(3, 3), activation='relu')) image_model.add(Conv2D(64, kernel_size=(3, 3), activation='relu')) image_model.add(MaxPooling2D(pool_size=(3, 3), strides=(2, 2))) # CNN 2 image_model.add(Conv2D(128, kernel_size=(3, 3), activation='relu')) image_model.add(Conv2D(128, kernel_size=(3, 3), activation='relu')) image_model.add(Conv2D(128, kernel_size=(3, 3), activation='relu')) image_model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2))) # CNN 3 image_model.add(Conv2D(128, kernel_size=(3, 3), activation='relu')) image_model.add(Conv2D(128, kernel_size=(3, 3), activation='relu')) image_model.add(Conv2D(128, kernel_size=(3, 3), activation='relu')) image_model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2))) # CNN 4 image_model.add(Conv2D(256, kernel_size=(3, 3), activation='relu')) image_model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2))) # You must flatten the data for the dense layers image_model.add(Flatten()) # Image input encoding image_input = Input(shape=(75, 75, 3)) encoded_image = image_model(image_input) # Inc angle input inc_angle_input = Input(shape=(1,)) # Combine image and inc angle combined = keras.layers.concatenate([encoded_image, inc_angle_input]) dense_model = Sequential() # Dense 1 dense_model.add(Dense(512, activation='relu', input_shape=(257,))) dense_model.add(Dropout(0.2)) # Dense 3 dense_model.add(Dense(256, activation='relu')) dense_model.add(Dropout(0.2)) # Output dense_model.add(Dense(1, activation="sigmoid")) output = dense_model(combined) # Final model combined_model = Model( inputs=[image_input, inc_angle_input], outputs=output) optimizer = Adam(lr=0.0001, decay=0.0) combined_model.compile(loss='binary_crossentropy', optimizer=optimizer, metrics=['accuracy']) return combined_model df_train = pd.read_json('./input/train.json') Xtrain = get_scaled_imgs(df_train) Ytrain = np.array(df_train['is_iceberg']) df_train.inc_angle = df_train.inc_angle.replace('na', 0) idx_tr = np.where(df_train.inc_angle > 0) Ytrain = Ytrain[idx_tr[0]] Xtrain = Xtrain[idx_tr[0], ...] Xinc = df_train.inc_angle[idx_tr[0]] #Xtrain = get_more_images(Xtrain) #Xinc = np.concatenate((Xinc, Xinc, Xinc)) #Ytrain = np.concatenate((Ytrain, Ytrain, Ytrain)) model = getModel() model.summary() model_file = '.mdl_angle2_wts.hdf5' batch_size = 32 earlyStopping = EarlyStopping( monitor='val_loss', patience=10, verbose=0, mode='min') mcp_save = ModelCheckpoint( model_file, save_best_only=True, monitor='val_loss', mode='min') reduce_lr_loss = ReduceLROnPlateau( monitor='val_loss', factor=0.1, patience=8, verbose=1, epsilon=1e-4, mode='min') model.fit([Xtrain, Xinc], Ytrain, batch_size=batch_size, epochs=50, verbose=1, callbacks=[mcp_save, reduce_lr_loss], validation_split=0.2) model.load_weights(filepath=model_file) score = model.evaluate([Xtrain, Xinc], Ytrain, verbose=1) print('Train score:', score[0]) print('Train accuracy:', score[1]) df_test = pd.read_json('./input/test.json') df_test.inc_angle = df_test.inc_angle.replace('na', 0) Xtest = (get_scaled_imgs(df_test)) Xinc = df_test.inc_angle pred_test = model.predict([Xtest, Xinc]) submission = pd.DataFrame( {'id': df_test["id"], 'is_iceberg': pred_test.reshape((pred_test.shape[0]))}) print(submission.head(10)) submission.to_csv('sub_inc_angle_noaug.csv', index=False)
[ "numpy.random.seed", "keras.models.Model", "keras.layers.Input", "keras.layers.concatenate", "keras.layers.Flatten", "keras.callbacks.ReduceLROnPlateau", "keras.layers.MaxPooling2D", "numpy.dstack", "keras.callbacks.ModelCheckpoint", "keras.layers.Dropout", "keras.optimizers.Adam", "keras.laye...
[((412, 432), 'numpy.random.seed', 'np.random.seed', (['(1207)'], {}), '(1207)\n', (426, 432), True, 'import numpy as np\n'), ((3894, 3928), 'pandas.read_json', 'pd.read_json', (['"""./input/train.json"""'], {}), "('./input/train.json')\n", (3906, 3928), True, 'import pandas as pd\n'), ((3973, 4005), 'numpy.array', 'np.array', (["df_train['is_iceberg']"], {}), "(df_train['is_iceberg'])\n", (3981, 4005), True, 'import numpy as np\n'), ((4073, 4105), 'numpy.where', 'np.where', (['(df_train.inc_angle > 0)'], {}), '(df_train.inc_angle > 0)\n', (4081, 4105), True, 'import numpy as np\n'), ((4437, 4506), 'keras.callbacks.EarlyStopping', 'EarlyStopping', ([], {'monitor': '"""val_loss"""', 'patience': '(10)', 'verbose': '(0)', 'mode': '"""min"""'}), "(monitor='val_loss', patience=10, verbose=0, mode='min')\n", (4450, 4506), False, 'from keras.callbacks import EarlyStopping, ModelCheckpoint, ReduceLROnPlateau\n'), ((4523, 4608), 'keras.callbacks.ModelCheckpoint', 'ModelCheckpoint', (['model_file'], {'save_best_only': '(True)', 'monitor': '"""val_loss"""', 'mode': '"""min"""'}), "(model_file, save_best_only=True, monitor='val_loss', mode='min'\n )\n", (4538, 4608), False, 'from keras.callbacks import EarlyStopping, ModelCheckpoint, ReduceLROnPlateau\n'), ((4626, 4730), 'keras.callbacks.ReduceLROnPlateau', 'ReduceLROnPlateau', ([], {'monitor': '"""val_loss"""', 'factor': '(0.1)', 'patience': '(8)', 'verbose': '(1)', 'epsilon': '(0.0001)', 'mode': '"""min"""'}), "(monitor='val_loss', factor=0.1, patience=8, verbose=1,\n epsilon=0.0001, mode='min')\n", (4643, 4730), False, 'from keras.callbacks import EarlyStopping, ModelCheckpoint, ReduceLROnPlateau\n'), ((5058, 5091), 'pandas.read_json', 'pd.read_json', (['"""./input/test.json"""'], {}), "('./input/test.json')\n", (5070, 5091), True, 'import pandas as pd\n'), ((1015, 1029), 'numpy.array', 'np.array', (['imgs'], {}), '(imgs)\n', (1023, 1029), True, 'import numpy as np\n'), ((1544, 1568), 'numpy.array', 'np.array', (['vert_flip_imgs'], {}), '(vert_flip_imgs)\n', (1552, 1568), True, 'import numpy as np\n'), ((1577, 1601), 'numpy.array', 'np.array', (['hori_flip_imgs'], {}), '(hori_flip_imgs)\n', (1585, 1601), True, 'import numpy as np\n'), ((1621, 1649), 'numpy.concatenate', 'np.concatenate', (['(imgs, v, h)'], {}), '((imgs, v, h))\n', (1635, 1649), True, 'import numpy as np\n'), ((1735, 1747), 'keras.models.Sequential', 'Sequential', ([], {}), '()\n', (1745, 1747), False, 'from keras.models import Sequential, Model\n'), ((2980, 3004), 'keras.layers.Input', 'Input', ([], {'shape': '(75, 75, 3)'}), '(shape=(75, 75, 3))\n', (2985, 3004), False, 'from keras.layers import Dense, Dropout, Flatten, Input, Activation, BatchNormalization\n'), ((3095, 3112), 'keras.layers.Input', 'Input', ([], {'shape': '(1,)'}), '(shape=(1,))\n', (3100, 3112), False, 'from keras.layers import Dense, Dropout, Flatten, Input, Activation, BatchNormalization\n'), ((3163, 3221), 'keras.layers.concatenate', 'keras.layers.concatenate', (['[encoded_image, inc_angle_input]'], {}), '([encoded_image, inc_angle_input])\n', (3187, 3221), False, 'import keras\n'), ((3241, 3253), 'keras.models.Sequential', 'Sequential', ([], {}), '()\n', (3251, 3253), False, 'from keras.models import Sequential, Model\n'), ((3616, 3676), 'keras.models.Model', 'Model', ([], {'inputs': '[image_input, inc_angle_input]', 'outputs': 'output'}), '(inputs=[image_input, inc_angle_input], outputs=output)\n', (3621, 3676), False, 'from keras.models import Sequential, Model\n'), ((3703, 3729), 'keras.optimizers.Adam', 'Adam', ([], {'lr': '(0.0001)', 'decay': '(0.0)'}), '(lr=0.0001, decay=0.0)\n', (3707, 3729), False, 'from keras.optimizers import Adam\n'), ((1269, 1283), 'cv2.flip', 'cv2.flip', (['a', '(1)'], {}), '(a, 1)\n', (1277, 1283), False, 'import cv2\n'), ((1297, 1311), 'cv2.flip', 'cv2.flip', (['a', '(0)'], {}), '(a, 0)\n', (1305, 1311), False, 'import cv2\n'), ((1325, 1339), 'cv2.flip', 'cv2.flip', (['b', '(1)'], {}), '(b, 1)\n', (1333, 1339), False, 'import cv2\n'), ((1353, 1367), 'cv2.flip', 'cv2.flip', (['b', '(0)'], {}), '(b, 0)\n', (1361, 1367), False, 'import cv2\n'), ((1381, 1395), 'cv2.flip', 'cv2.flip', (['c', '(1)'], {}), '(c, 1)\n', (1389, 1395), False, 'import cv2\n'), ((1409, 1423), 'cv2.flip', 'cv2.flip', (['c', '(0)'], {}), '(c, 0)\n', (1417, 1423), False, 'import cv2\n'), ((1781, 1855), 'keras.layers.Conv2D', 'Conv2D', (['(64)'], {'kernel_size': '(3, 3)', 'activation': '"""relu"""', 'input_shape': '(75, 75, 3)'}), "(64, kernel_size=(3, 3), activation='relu', input_shape=(75, 75, 3))\n", (1787, 1855), False, 'from keras.layers import Conv2D, MaxPooling2D\n'), ((1904, 1953), 'keras.layers.Conv2D', 'Conv2D', (['(64)'], {'kernel_size': '(3, 3)', 'activation': '"""relu"""'}), "(64, kernel_size=(3, 3), activation='relu')\n", (1910, 1953), False, 'from keras.layers import Conv2D, MaxPooling2D\n'), ((1975, 2024), 'keras.layers.Conv2D', 'Conv2D', (['(64)'], {'kernel_size': '(3, 3)', 'activation': '"""relu"""'}), "(64, kernel_size=(3, 3), activation='relu')\n", (1981, 2024), False, 'from keras.layers import Conv2D, MaxPooling2D\n'), ((2046, 2092), 'keras.layers.MaxPooling2D', 'MaxPooling2D', ([], {'pool_size': '(3, 3)', 'strides': '(2, 2)'}), '(pool_size=(3, 3), strides=(2, 2))\n', (2058, 2092), False, 'from keras.layers import Conv2D, MaxPooling2D\n'), ((2131, 2181), 'keras.layers.Conv2D', 'Conv2D', (['(128)'], {'kernel_size': '(3, 3)', 'activation': '"""relu"""'}), "(128, kernel_size=(3, 3), activation='relu')\n", (2137, 2181), False, 'from keras.layers import Conv2D, MaxPooling2D\n'), ((2203, 2253), 'keras.layers.Conv2D', 'Conv2D', (['(128)'], {'kernel_size': '(3, 3)', 'activation': '"""relu"""'}), "(128, kernel_size=(3, 3), activation='relu')\n", (2209, 2253), False, 'from keras.layers import Conv2D, MaxPooling2D\n'), ((2275, 2325), 'keras.layers.Conv2D', 'Conv2D', (['(128)'], {'kernel_size': '(3, 3)', 'activation': '"""relu"""'}), "(128, kernel_size=(3, 3), activation='relu')\n", (2281, 2325), False, 'from keras.layers import Conv2D, MaxPooling2D\n'), ((2347, 2393), 'keras.layers.MaxPooling2D', 'MaxPooling2D', ([], {'pool_size': '(2, 2)', 'strides': '(2, 2)'}), '(pool_size=(2, 2), strides=(2, 2))\n', (2359, 2393), False, 'from keras.layers import Conv2D, MaxPooling2D\n'), ((2432, 2482), 'keras.layers.Conv2D', 'Conv2D', (['(128)'], {'kernel_size': '(3, 3)', 'activation': '"""relu"""'}), "(128, kernel_size=(3, 3), activation='relu')\n", (2438, 2482), False, 'from keras.layers import Conv2D, MaxPooling2D\n'), ((2504, 2554), 'keras.layers.Conv2D', 'Conv2D', (['(128)'], {'kernel_size': '(3, 3)', 'activation': '"""relu"""'}), "(128, kernel_size=(3, 3), activation='relu')\n", (2510, 2554), False, 'from keras.layers import Conv2D, MaxPooling2D\n'), ((2576, 2626), 'keras.layers.Conv2D', 'Conv2D', (['(128)'], {'kernel_size': '(3, 3)', 'activation': '"""relu"""'}), "(128, kernel_size=(3, 3), activation='relu')\n", (2582, 2626), False, 'from keras.layers import Conv2D, MaxPooling2D\n'), ((2648, 2694), 'keras.layers.MaxPooling2D', 'MaxPooling2D', ([], {'pool_size': '(2, 2)', 'strides': '(2, 2)'}), '(pool_size=(2, 2), strides=(2, 2))\n', (2660, 2694), False, 'from keras.layers import Conv2D, MaxPooling2D\n'), ((2729, 2779), 'keras.layers.Conv2D', 'Conv2D', (['(256)'], {'kernel_size': '(3, 3)', 'activation': '"""relu"""'}), "(256, kernel_size=(3, 3), activation='relu')\n", (2735, 2779), False, 'from keras.layers import Conv2D, MaxPooling2D\n'), ((2801, 2847), 'keras.layers.MaxPooling2D', 'MaxPooling2D', ([], {'pool_size': '(2, 2)', 'strides': '(2, 2)'}), '(pool_size=(2, 2), strides=(2, 2))\n', (2813, 2847), False, 'from keras.layers import Conv2D, MaxPooling2D\n'), ((2923, 2932), 'keras.layers.Flatten', 'Flatten', ([], {}), '()\n', (2930, 2932), False, 'from keras.layers import Dense, Dropout, Flatten, Input, Activation, BatchNormalization\n'), ((3289, 3338), 'keras.layers.Dense', 'Dense', (['(512)'], {'activation': '"""relu"""', 'input_shape': '(257,)'}), "(512, activation='relu', input_shape=(257,))\n", (3294, 3338), False, 'from keras.layers import Dense, Dropout, Flatten, Input, Activation, BatchNormalization\n'), ((3360, 3372), 'keras.layers.Dropout', 'Dropout', (['(0.2)'], {}), '(0.2)\n', (3367, 3372), False, 'from keras.layers import Dense, Dropout, Flatten, Input, Activation, BatchNormalization\n'), ((3409, 3438), 'keras.layers.Dense', 'Dense', (['(256)'], {'activation': '"""relu"""'}), "(256, activation='relu')\n", (3414, 3438), False, 'from keras.layers import Dense, Dropout, Flatten, Input, Activation, BatchNormalization\n'), ((3460, 3472), 'keras.layers.Dropout', 'Dropout', (['(0.2)'], {}), '(0.2)\n', (3467, 3472), False, 'from keras.layers import Dense, Dropout, Flatten, Input, Activation, BatchNormalization\n'), ((3508, 3538), 'keras.layers.Dense', 'Dense', (['(1)'], {'activation': '"""sigmoid"""'}), "(1, activation='sigmoid')\n", (3513, 3538), False, 'from keras.layers import Dense, Dropout, Flatten, Input, Activation, BatchNormalization\n'), ((981, 1001), 'numpy.dstack', 'np.dstack', (['(a, b, c)'], {}), '((a, b, c))\n', (990, 1001), True, 'import numpy as np\n'), ((1455, 1478), 'numpy.dstack', 'np.dstack', (['(av, bv, cv)'], {}), '((av, bv, cv))\n', (1464, 1478), True, 'import numpy as np\n'), ((1510, 1533), 'numpy.dstack', 'np.dstack', (['(ah, bh, ch)'], {}), '((ah, bh, ch))\n', (1519, 1533), True, 'import numpy as np\n'), ((563, 586), 'numpy.array', 'np.array', (["row['band_1']"], {}), "(row['band_1'])\n", (571, 586), True, 'import numpy as np\n'), ((620, 643), 'numpy.array', 'np.array', (["row['band_2']"], {}), "(row['band_2'])\n", (628, 643), True, 'import numpy as np\n')]
# Copyright 2021 AI Singapore # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # Code of this file is mostly forked from # [@xuannianz](https://github.com/xuannianz)) """ Processing helper functinos for EfficientDet """ from typing import List, Tuple import numpy as np import cv2 IMG_MEAN = [0.485, 0.456, 0.406] IMG_STD = [0.229, 0.224, 0.225] def preprocess_image(image: np.ndarray, image_size: int) -> Tuple[List[List[float]], float]: """Preprocessing helper function for efficientdet Args: image (np.array): the input image in numpy array image_size (int): the model input size as specified in config Returns: image (np.array): the preprocessed image scale (float): the scale in which the original image was resized to """ # image, RGB image_height, image_width = image.shape[:2] if image_height > image_width: scale = image_size / image_height resized_height = image_size resized_width = int(image_width * scale) else: scale = image_size / image_width resized_height = int(image_height * scale) resized_width = image_size image = cv2.resize(image, (resized_width, resized_height)) image = image.astype(np.float32) image /= 255. image -= IMG_MEAN image /= IMG_STD pad_h = image_size - resized_height pad_w = image_size - resized_width image = np.pad(image, [(0, pad_h), (0, pad_w), (0, 0)], mode='constant') return image, scale def postprocess_boxes(boxes: np.ndarray, scale: float, height: int, width: int) -> np.ndarray: """Postprocessing helper function for efficientdet Args: boxes (np.array): the original detected bboxes from model output scale (float): scale in which the original image was resized to height (int): the height of the original image width (int): the width of the original image Returns: boxes (np.array): the postprocessed bboxes """ boxes /= scale boxes[:, 0] = np.clip(boxes[:, 0], 0, width - 1) boxes[:, 1] = np.clip(boxes[:, 1], 0, height - 1) boxes[:, 2] = np.clip(boxes[:, 2], 0, width - 1) boxes[:, 3] = np.clip(boxes[:, 3], 0, height - 1) boxes[:, [0, 2]] /= width boxes[:, [1, 3]] /= height return boxes
[ "numpy.pad", "cv2.resize", "numpy.clip" ]
[((1682, 1732), 'cv2.resize', 'cv2.resize', (['image', '(resized_width, resized_height)'], {}), '(image, (resized_width, resized_height))\n', (1692, 1732), False, 'import cv2\n'), ((1922, 1986), 'numpy.pad', 'np.pad', (['image', '[(0, pad_h), (0, pad_w), (0, 0)]'], {'mode': '"""constant"""'}), "(image, [(0, pad_h), (0, pad_w), (0, 0)], mode='constant')\n", (1928, 1986), True, 'import numpy as np\n'), ((2604, 2638), 'numpy.clip', 'np.clip', (['boxes[:, 0]', '(0)', '(width - 1)'], {}), '(boxes[:, 0], 0, width - 1)\n', (2611, 2638), True, 'import numpy as np\n'), ((2657, 2692), 'numpy.clip', 'np.clip', (['boxes[:, 1]', '(0)', '(height - 1)'], {}), '(boxes[:, 1], 0, height - 1)\n', (2664, 2692), True, 'import numpy as np\n'), ((2711, 2745), 'numpy.clip', 'np.clip', (['boxes[:, 2]', '(0)', '(width - 1)'], {}), '(boxes[:, 2], 0, width - 1)\n', (2718, 2745), True, 'import numpy as np\n'), ((2764, 2799), 'numpy.clip', 'np.clip', (['boxes[:, 3]', '(0)', '(height - 1)'], {}), '(boxes[:, 3], 0, height - 1)\n', (2771, 2799), True, 'import numpy as np\n')]
import numpy as np state=np.array([[1,2,3,4], [3,4,5,6], [1,1,1,1]]) state_part=state[:2,1] print(state_part) target=np.zeros((2,2)) target[1]=[1,2] print(target) x=np.random.uniform(0.1, 0.9) * 10 print(x)
[ "numpy.zeros", "numpy.random.uniform", "numpy.array" ]
[((26, 78), 'numpy.array', 'np.array', (['[[1, 2, 3, 4], [3, 4, 5, 6], [1, 1, 1, 1]]'], {}), '([[1, 2, 3, 4], [3, 4, 5, 6], [1, 1, 1, 1]])\n', (34, 78), True, 'import numpy as np\n'), ((135, 151), 'numpy.zeros', 'np.zeros', (['(2, 2)'], {}), '((2, 2))\n', (143, 151), True, 'import numpy as np\n'), ((183, 210), 'numpy.random.uniform', 'np.random.uniform', (['(0.1)', '(0.9)'], {}), '(0.1, 0.9)\n', (200, 210), True, 'import numpy as np\n')]
import numpy as np import torch import os, sys from samplers import GenerativeSampler, sample, log_normal_pdf class Rewarder(object): rewardfn = None sampler = None device = None logp = None logps = None rewardfn_state = {} obs = {} @classmethod def __init__(cls, rewardfn, sampler, device, obs = None): cls.rewardfn = rewardfn cls.sampler = sampler cls.device = device cls.obs = {'image': None} if obs is not None: cls.reset(obs) #cls.holes = [] @classmethod def suspend(cls): cls.rewardfn_state = cls.rewardfn.__dict__.copy() return cls.rewardfn_state @classmethod def restore(cls, state = None, refill = True): #cls.rewardfn.reset() if state is not None: cls.rewardfn_state = state.copy() cls.rewardfn.__dict__ = cls.rewardfn_state.copy() cls.rewardfn_state = {} if refill: cls.rewardfn.holes = [h for h in cls.refill(True)] @classmethod def reset(cls, obs = None): cls.rewardfn.reset() if obs is not None: cls.obs['image'] = np.copy(obs['image']) if isinstance(obs['image'], np.ndarray) else np.copy(obs['image'].detach().cpu().numpy()) @classmethod def __call__(cls, obs, act, reward, done): if isinstance(act, torch.Tensor): action = act.detach().cpu().numpy().item() if isinstance(act, np.ndarray): action = act.item() if cls.obs['image'] is None: holes = cls.refill(use_mean = True) cls.rewardfn.reset(holes, verbose = True) cls.obs['image'] = np.copy(obs['image']) if isinstance(obs['image'], np.ndarray) else np.copy(obs['image'].detach().cpu().numpy()) #cls.holes.append([holes]) return 0. else: rew = cls.rewardfn.step(cls.obs, act, reward, done) #cls.holes[-1].append(cls.holes[-1][-1]) cls.obs['image'] = np.copy(obs['image']) if isinstance(obs['image'], np.ndarray) else np.copy(obs['image'].detach().cpu().numpy()) if done: cls.rewardfn.reset(verbose = cls.rewardfn.reach) return rew @classmethod def refill(cls, use_mean = True): seed = torch.ones([1, cls.sampler.input_size]).to(cls.device) with torch.no_grad(): cls.sampler.eval() mean, logvar = cls.sampler(seed) if use_mean: print("means: {}".format(mean)) print("logvar: {}".format(logvar)) return mean.flatten().detach().cpu().numpy().tolist() holes = sample(mean, logvar, num_samples = 1).flatten().detach().cpu().numpy().tolist() #holes = mean.flatten().detach().cpu().numpy().tolist() return holes class RewarderWithMemory(Rewarder): #rewardfn = None #sampler = None #device = None #logp = None #logps = None dcmodel = None memory = None memories = [] preprocess_obss = lambda obs, device: obs @classmethod def __init__(cls, rewardfn, sampler, dcmodel, device, preprocess_obss = None, obs = None, ): super(cls, RewarderWithMemory).__init__(rewardfn, sampler, device, obs) #cls.rewardfn = rewardfn #cls.sampler = sampler #cls.device = device #cls.obs = None #cls.holes = [] cls.dcmodel = dcmodel if preprocess_obss is not None: cls.preprocess_obss = preprocess_obss cls.memory = None cls.memories = [] @classmethod def __call__(cls, obs, act, reward, done): if isinstance(act, torch.Tensor): action = act.detach().cpu().numpy().item() if isinstance(act, np.ndarray): action = act.item() # Update dc_model memory state = cls.preprocess_obss([obs], device = cls.device).image.to(cls.device) action = torch.FloatTensor([action]).flatten().unsqueeze(1).to(cls.device) if cls.memory is None: cls.memory = torch.zeros([action.shape[0], cls.dcmodel.memory_size], device = cls.device).to(cls.device) #if len(cls.memories) == 0: #cls.memories = [[cls.memory[i]] for i in range(cls.memory.shape[0])] # else: # cls.memories = cls.memories + [cls.memory[i] for i in range(cls.memory.shape[0])] with torch.no_grad(): cls.dcmodel.eval() dc_rew, cls.memory = cls.dcmodel(state, action, cls.memory) dc_rew = dc_rew.cpu().numpy().item() mask = 1. - torch.FloatTensor([done]).to(cls.device) cls.memory = cls.memory * mask # Let programmatic reward function output reward if cls.obs['image'] is None: holes = cls.refill(use_mean = True) cls.rewardfn.reset(holes, verbose = True) cls.obs['image'] = np.copy(obs['image']) if isinstance(obs['image'], np.ndarray) else np.copy(obs['image'].detach().cpu().numpy()) #cls.holes.append([holes]) prog_rew = 0. else: prog_rew = cls.rewardfn.step(cls.obs, act, reward, done) #cls.holes[-1].append(cls.holes[-1][-1]) cls.obs['image'] = np.copy(obs['image']) if isinstance(obs['image'], np.ndarray) else np.copy(obs['image'].detach().cpu().numpy()) if done: cls.rewardfn.reset(verbose = cls.rewardfn.reach) rew = prog_rew #+ 1./2. * np.log(1./(1. + np.exp(dc_rew - prog_rew)) * 1./(1. + np.exp(prog_rew - dc_rew))) return rew @classmethod def update_memory(cls, memory): idx = 0 for i in range(len(cls.memories)): for j in range(len(cls.memories[i])): memory[idx, :] = cls.memories[i][j].flatten()[:] idx += 1 cls.memories = [] return memory class RewardFn(object): def __init__(self): self.traj = [] self.t_min = float('inf') self.carry = True self.locked = True self.reach = False self.doc = [] self.sum_rew = 0. self.init_rew = 0. self.num_holes = 8 self.holes = [None for i in range(self.num_holes)] def reset(self, holes = None, verbose = False): if self.reach and verbose: print(self.doc) if self.holes[0] is not None: self.init_rew = len(self.traj) * self.holes[0] - self.sum_rew self.sum_rew = 0. self.traj = [] self.doc = [] self.carry = False self.locked = True self.reach = False self.t_min = float('inf') if holes is not None: self.holes = [h for h in holes] def step(self, obs, action, reward, done): #print("Analyzing obs\n pre_obs: {}\n action: {}\n reward: {}\n done: {}\n".format(obs, action, reward, done)) if len(self.traj) < 1: ########## reward hole ########## #rew = self.holes[0] rew = 0. #- self.holes[0] - self.holes[1] - self.holes[3] - self.holes[4] - self.holes[5] - self.holes[6] - self.holes[7] ########## reward hole ########## self.traj.append([obs, action, rew, done, None]) self.sum_rew += rew self.doc.append("initialize") return rew t = len(self.traj) + 1 ########## reward hole ########## rew = 0. #- self.holes[1] - self.holes[3] - self.holes[4] - self.holes[5] - self.holes[6] - self.holes[7] #rew = self.holes[0] ########## reward hole ########## if (obs['image'][3, 5][0] == 8) and (action == 2): # Reach the goal state if t < self.t_min: # For the first time self.t_min = t ########## reward hole ########## rew = self.holes[1] #+ self.holes[0] #rew = - 1.0 self.traj.append([obs, action, rew, done, 1]) ########## reward hole ########## self.doc.append("reach the goal state for the first time. default reward {}".format(reward)) #print("Reaching obs\n pre_obs: {}\n action: {}\n reward: {}\n done: {}\n".format(obs, action, reward, done)) elif self.reach: #if done: # raise ValueError("Repeat done: {} >= t_min = {}".format(reward, self.t_min)) # Not the first time self.doc.append("reach the goal state again") ########## reward hole ########## #rew = self.holes[1] rew = self.holes[2] self.traj.append([obs, action, rew, done, 2]) ########## reward hole ########## self.reach = True elif obs['image'][3, 5][0] == 5: # See a key in front if (action == 3) and self.locked and (not self.carry): # pick up the key if locked self.doc.append("pick up a key") ########## reward hole ########## #rew = 0.1 rew = self.holes[3]#+ self.holes[0] self.traj.append([obs, action, rew, done, 3]) ########## reward hole ########## self.carry = True # From now on, there is no need to repeat past action elif action == 4 and self.carry and self.locked: # Key is dropped self.carry = False # Don't drop the key if locked self.doc.append("drop the key without using it") ########## reward hole ########## #rew = -0.2 rew = self.holes[4]#+ self.holes[0] self.traj.append([obs, action, rew, done, 4]) ########## reward hole ########## elif obs['image'][3, 5][0] == 4 and (action == 5): # Seeing a door, and toggle it if obs['image'][3, 5][2] == 0: # If the door was open, then toggling it means closing the gate self.doc.append("closed a door") ########## reward hole ########## #rew = -0.1 rew = self.holes[5] #+ self.holes[0] self.traj.append([obs, action, rew, done, 5]) ########## reward hole ########## elif obs['image'][3, 5][2] == 2 and self.carry and self.locked: # If the door was locked and agent is carrying a key, then by toggling it the door is open self.doc.append("unlock a door") ########## reward hole ########## #rew = 0.5 rew = self.holes[6] #+ self.holes[0] self.traj.append([obs, action, rew, done, 6]) ########## reward hole ########## self.locked = False elif obs['image'][3, 5][0] == 2 and (action == 2): # Hit the wall self.doc.append("hit a wall") ########## reward hole ########## #rew = -0.2 rew = self.holes[7] #+ self.holes[0] self.traj.append([obs, action, rew, done, 7]) ########## reward hole ########## #elif not self.locked: # rew = self.holes[2] else: rew = 0. self.traj.append([obs, action, rew, done, None]) self.sum_rew += rew return rew
[ "torch.ones", "numpy.copy", "torch.FloatTensor", "samplers.sample", "torch.zeros", "torch.no_grad" ]
[((2404, 2419), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (2417, 2419), False, 'import torch\n'), ((4474, 4489), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (4487, 4489), False, 'import torch\n'), ((1171, 1192), 'numpy.copy', 'np.copy', (["obs['image']"], {}), "(obs['image'])\n", (1178, 1192), True, 'import numpy as np\n'), ((1698, 1719), 'numpy.copy', 'np.copy', (["obs['image']"], {}), "(obs['image'])\n", (1705, 1719), True, 'import numpy as np\n'), ((2038, 2059), 'numpy.copy', 'np.copy', (["obs['image']"], {}), "(obs['image'])\n", (2045, 2059), True, 'import numpy as np\n'), ((2336, 2375), 'torch.ones', 'torch.ones', (['[1, cls.sampler.input_size]'], {}), '([1, cls.sampler.input_size])\n', (2346, 2375), False, 'import torch\n'), ((4980, 5001), 'numpy.copy', 'np.copy', (["obs['image']"], {}), "(obs['image'])\n", (4987, 5001), True, 'import numpy as np\n'), ((5329, 5350), 'numpy.copy', 'np.copy', (["obs['image']"], {}), "(obs['image'])\n", (5336, 5350), True, 'import numpy as np\n'), ((4139, 4213), 'torch.zeros', 'torch.zeros', (['[action.shape[0], cls.dcmodel.memory_size]'], {'device': 'cls.device'}), '([action.shape[0], cls.dcmodel.memory_size], device=cls.device)\n', (4150, 4213), False, 'import torch\n'), ((4659, 4684), 'torch.FloatTensor', 'torch.FloatTensor', (['[done]'], {}), '([done])\n', (4676, 4684), False, 'import torch\n'), ((4017, 4044), 'torch.FloatTensor', 'torch.FloatTensor', (['[action]'], {}), '([action])\n', (4034, 4044), False, 'import torch\n'), ((2711, 2746), 'samplers.sample', 'sample', (['mean', 'logvar'], {'num_samples': '(1)'}), '(mean, logvar, num_samples=1)\n', (2717, 2746), False, 'from samplers import GenerativeSampler, sample, log_normal_pdf\n')]
import numpy as np def softmax(predictions): ''' Computes probabilities from scores Arguments: predictions, np array, shape is either (N) or (batch_size, N) - classifier output Returns: probs, np array of the same shape as predictions - probability for every class, 0..1 ''' # print("pred\n" + str(predictions)) # print("max predictions: \n" + str(np.max(predictions, axis=1))) probs = predictions - np.atleast_2d(np.max(predictions, axis=1)).T # print("probs\n" + str(probs)) probs = np.exp(probs) # print("probs\n" + str(probs)) probs /= np.atleast_2d(probs.sum(axis=1)).T # print("probs\n" + str(probs)) # TODO implement softmax # Your final implementation shouldn't have any loops # raise Exception("Not implemented!") return probs def cross_entropy_loss(probs, target_index): ''' Computes cross-entropy loss Arguments: probs, np array, shape is either (N) or (batch_size, N) - probabilities for every class target_index: np array of int, shape is (1) or (batch_size) - index of the true class for given sample(s) Returns: loss: single value ''' batch_size = target_index.shape[0] # print("target index = \n", target_index) target_probs = np.zeros(probs.shape) target_probs[range(batch_size), target_index] = 1 # for i in range(batch_size): # target_probs[i,target_index[i]] = 1 # print("target_probs = \n", str(target_probs)) # print("batch_size =" + str(batch_size)) # print("probs[:, target_index] = " + str(probs[:, target_index])) # print("LN OF PROBS = \n", str(np.log(probs))) # print("ALMOST LOSS = \n", str(np.log(probs) * target_probs)) losses = - (np.log(probs) * target_probs).sum()/batch_size # losses = losses.sum()/batch_size # print("losses = ", str(losses)) # losses[target_index] # TODO implement cross-entropy # Your final implementation shouldn't have any loops # raise Exception("Not implemented!") return losses def softmax_with_cross_entropy(predictions, target_index): ''' Computes softmax and cross-entropy loss for model predictions, including the gradient Arguments: predictions, np array, shape is either (N) or (batch_size, N) - classifier output target_index: np array of int, shape is (1) or (batch_size) - index of the true class for given sample(s) Returns: loss, single value - cross-entropy loss dprediction, np array same shape as predictions - gradient of predictions by loss value ''' batch_size = target_index.shape[0] target_probs = np.zeros(predictions.shape) target_probs[range(batch_size), target_index] = 1 # for i in range(batch_size): # target_probs[i,target_index[i]] = 1 probs = softmax(predictions) loss = cross_entropy_loss(probs, target_index) dprediction = (probs - target_probs)/batch_size # print("softmax of predictions = " + str(dprediction)) # print("target index = " + str(target_index)) # dprediction[:,target_index] -= 1 # print("after deducting 1 = " + str(dprediction)) # print("Done with softmax_CE function") # TODO implement softmax with cross-entropy # Your final implementation shouldn't have any loops # raise Exception("Not implemented!") return loss, dprediction def l2_regularization(W, reg_strength): ''' Computes L2 regularization loss on weights and its gradient Arguments: W, np array - weights reg_strength - float value Returns: loss, single value - l2 regularization loss gradient, np.array same shape as W - gradient of weight by l2 loss ''' loss = np.multiply(W, W).sum() * reg_strength grad = 2 * reg_strength * W # TODO: implement l2 regularization and gradient # Your final implementation shouldn't have any loops # raise Exception("Not implemented!") return loss, grad def linear_softmax(X, W, target_index): ''' Performs linear classification and returns loss and gradient over W Arguments: X, np array, shape (num_batch, num_features) - batch of images W, np array, shape (num_features, classes) - weights target_index, np array, shape (num_batch) - index of target classes Returns: loss, single value - cross-entropy loss gradient, np.array same shape as W - gradient of weight by loss ''' batch_size = target_index.shape[0] predictions = np.dot(X, W) loss, dprediction = softmax_with_cross_entropy(predictions, target_index) dW = np.dot(X.T, dprediction) # (num_features, num_batch) x (batch_size, N) # TODO implement prediction and gradient over W # Your final implementation shouldn't have any loops # raise Exception("Not implemented!") return loss, dW class LinearSoftmaxClassifier(): def __init__(self): self.W = None def fit(self, X, y, batch_size=100, learning_rate=1e-7, reg=1e-5, epochs=1): ''' Trains linear classifier Arguments: X, np array (num_samples, num_features) - training data y, np array of int (num_samples) - labels batch_size, int - batch size to use learning_rate, float - learning rate for gradient descent reg, float - L2 regularization strength epochs, int - number of epochs ''' num_train = X.shape[0] num_features = X.shape[1] num_classes = np.max(y)+1 if self.W is None: self.W = 0.001 * np.random.randn(num_features, num_classes) loss_history = [] for epoch in range(epochs): shuffled_indices = np.arange(num_train) np.random.shuffle(shuffled_indices) sections = np.arange(batch_size, num_train, batch_size) batches_indices = np.array_split(shuffled_indices, sections) batch = X[batches_indices, :] loss_linear, dW = linear_softmax(X, self.W, y) loss_reg, dW_reg = l2_regularization(self.W, reg) self.W -= (dW + dW_reg) * learning_rate loss = loss_linear + loss_reg loss_history.append(loss) # TODO implement generating batches from indices # Compute loss and gradients # Apply gradient to weights using learning rate # Don't forget to add both cross-entropy loss # and regularization! # raise Exception("Not implemented!") # end # print("Epoch %i, loss: %f" % (epoch, loss)) return loss_history def predict(self, X): ''' Produces classifier predictions on the set Arguments: X, np array (test_samples, num_features) Returns: y_pred, np.array of int (test_samples) ''' y_pred = np.zeros(X.shape[0], dtype=np.int) prob = softmax(np.dot(X, self.W)) y_pred = np.argmax(prob, axis=1) # TODO Implement class prediction # Your final implementation shouldn't have any loops # raise Exception("Not implemented!") return y_pred
[ "numpy.multiply", "numpy.log", "numpy.argmax", "numpy.random.randn", "numpy.zeros", "numpy.max", "numpy.arange", "numpy.exp", "numpy.array_split", "numpy.dot", "numpy.random.shuffle" ]
[((558, 571), 'numpy.exp', 'np.exp', (['probs'], {}), '(probs)\n', (564, 571), True, 'import numpy as np\n'), ((1322, 1343), 'numpy.zeros', 'np.zeros', (['probs.shape'], {}), '(probs.shape)\n', (1330, 1343), True, 'import numpy as np\n'), ((2710, 2737), 'numpy.zeros', 'np.zeros', (['predictions.shape'], {}), '(predictions.shape)\n', (2718, 2737), True, 'import numpy as np\n'), ((4573, 4585), 'numpy.dot', 'np.dot', (['X', 'W'], {}), '(X, W)\n', (4579, 4585), True, 'import numpy as np\n'), ((4673, 4697), 'numpy.dot', 'np.dot', (['X.T', 'dprediction'], {}), '(X.T, dprediction)\n', (4679, 4697), True, 'import numpy as np\n'), ((6976, 7010), 'numpy.zeros', 'np.zeros', (['X.shape[0]'], {'dtype': 'np.int'}), '(X.shape[0], dtype=np.int)\n', (6984, 7010), True, 'import numpy as np\n'), ((7070, 7093), 'numpy.argmax', 'np.argmax', (['prob'], {'axis': '(1)'}), '(prob, axis=1)\n', (7079, 7093), True, 'import numpy as np\n'), ((5592, 5601), 'numpy.max', 'np.max', (['y'], {}), '(y)\n', (5598, 5601), True, 'import numpy as np\n'), ((5797, 5817), 'numpy.arange', 'np.arange', (['num_train'], {}), '(num_train)\n', (5806, 5817), True, 'import numpy as np\n'), ((5830, 5865), 'numpy.random.shuffle', 'np.random.shuffle', (['shuffled_indices'], {}), '(shuffled_indices)\n', (5847, 5865), True, 'import numpy as np\n'), ((5889, 5933), 'numpy.arange', 'np.arange', (['batch_size', 'num_train', 'batch_size'], {}), '(batch_size, num_train, batch_size)\n', (5898, 5933), True, 'import numpy as np\n'), ((5964, 6006), 'numpy.array_split', 'np.array_split', (['shuffled_indices', 'sections'], {}), '(shuffled_indices, sections)\n', (5978, 6006), True, 'import numpy as np\n'), ((7034, 7051), 'numpy.dot', 'np.dot', (['X', 'self.W'], {}), '(X, self.W)\n', (7040, 7051), True, 'import numpy as np\n'), ((479, 506), 'numpy.max', 'np.max', (['predictions'], {'axis': '(1)'}), '(predictions, axis=1)\n', (485, 506), True, 'import numpy as np\n'), ((3787, 3804), 'numpy.multiply', 'np.multiply', (['W', 'W'], {}), '(W, W)\n', (3798, 3804), True, 'import numpy as np\n'), ((5660, 5702), 'numpy.random.randn', 'np.random.randn', (['num_features', 'num_classes'], {}), '(num_features, num_classes)\n', (5675, 5702), True, 'import numpy as np\n'), ((1787, 1800), 'numpy.log', 'np.log', (['probs'], {}), '(probs)\n', (1793, 1800), True, 'import numpy as np\n')]
# Authors: <NAME> <<EMAIL>> # # License: BSD (3-clause) import numpy as np from numpy.testing import assert_allclose, assert_equal, assert_array_equal from scipy import linalg from .. import pick_types, Evoked from ..io import BaseRaw from ..io.constants import FIFF from ..bem import fit_sphere_to_headshape def _get_data(x, ch_idx): """Get the (n_ch, n_times) data array.""" if isinstance(x, BaseRaw): return x[ch_idx][0] elif isinstance(x, Evoked): return x.data[ch_idx] def _check_snr(actual, desired, picks, min_tol, med_tol, msg, kind='MEG'): """Check the SNR of a set of channels.""" actual_data = _get_data(actual, picks) desired_data = _get_data(desired, picks) bench_rms = np.sqrt(np.mean(desired_data * desired_data, axis=1)) error = actual_data - desired_data error_rms = np.sqrt(np.mean(error * error, axis=1)) np.clip(error_rms, 1e-60, np.inf, out=error_rms) # avoid division by zero snrs = bench_rms / error_rms # min tol snr = snrs.min() bad_count = (snrs < min_tol).sum() msg = ' (%s)' % msg if msg != '' else msg assert bad_count == 0, ('SNR (worst %0.2f) < %0.2f for %s/%s ' 'channels%s' % (snr, min_tol, bad_count, len(picks), msg)) # median tol snr = np.median(snrs) assert snr >= med_tol, ('%s SNR median %0.2f < %0.2f%s' % (kind, snr, med_tol, msg)) def assert_meg_snr(actual, desired, min_tol, med_tol=500., chpi_med_tol=500., msg=None): """Assert channel SNR of a certain level. Mostly useful for operations like Maxwell filtering that modify MEG channels while leaving EEG and others intact. """ picks = pick_types(desired.info, meg=True, exclude=[]) picks_desired = pick_types(desired.info, meg=True, exclude=[]) assert_array_equal(picks, picks_desired, err_msg='MEG pick mismatch') chpis = pick_types(actual.info, meg=False, chpi=True, exclude=[]) chpis_desired = pick_types(desired.info, meg=False, chpi=True, exclude=[]) if chpi_med_tol is not None: assert_array_equal(chpis, chpis_desired, err_msg='cHPI pick mismatch') others = np.setdiff1d(np.arange(len(actual.ch_names)), np.concatenate([picks, chpis])) others_desired = np.setdiff1d(np.arange(len(desired.ch_names)), np.concatenate([picks_desired, chpis_desired])) assert_array_equal(others, others_desired, err_msg='Other pick mismatch') if len(others) > 0: # if non-MEG channels present assert_allclose(_get_data(actual, others), _get_data(desired, others), atol=1e-11, rtol=1e-5, err_msg='non-MEG channel mismatch') _check_snr(actual, desired, picks, min_tol, med_tol, msg, kind='MEG') if chpi_med_tol is not None and len(chpis) > 0: _check_snr(actual, desired, chpis, 0., chpi_med_tol, msg, kind='cHPI') def assert_snr(actual, desired, tol): """Assert actual and desired arrays are within some SNR tolerance.""" snr = (linalg.norm(desired, ord='fro') / linalg.norm(desired - actual, ord='fro')) assert snr >= tol, '%f < %f' % (snr, tol) def _dig_sort_key(dig): """Sort dig keys.""" return (dig['kind'], dig['ident']) def assert_dig_allclose(info_py, info_bin): """Assert dig allclose.""" # test dig positions dig_py = sorted(info_py['dig'], key=_dig_sort_key) dig_bin = sorted(info_bin['dig'], key=_dig_sort_key) assert_equal(len(dig_py), len(dig_bin)) for ii, (d_py, d_bin) in enumerate(zip(dig_py, dig_bin)): for key in ('ident', 'kind', 'coord_frame'): assert_equal(d_py[key], d_bin[key]) assert_allclose(d_py['r'], d_bin['r'], rtol=1e-5, atol=1e-5, err_msg='Failure on %s:\n%s\n%s' % (ii, d_py['r'], d_bin['r'])) if any(d['kind'] == FIFF.FIFFV_POINT_EXTRA for d in dig_py): r_bin, o_head_bin, o_dev_bin = fit_sphere_to_headshape( info_bin, units='m', verbose='error') r_py, o_head_py, o_dev_py = fit_sphere_to_headshape( info_py, units='m', verbose='error') assert_allclose(r_py, r_bin, atol=1e-6) assert_allclose(o_dev_py, o_dev_bin, rtol=1e-5, atol=1e-6) assert_allclose(o_head_py, o_head_bin, rtol=1e-5, atol=1e-6) def assert_naming(warns, fname, n_warn): """Assert a non-standard naming scheme was used while saving or loading. Parameters ---------- warns : list List of warnings from ``warnings.catch_warnings(record=True)``. fname : str Filename that should appear in the warning message. n_warn : int Number of warnings that should have naming convention errors. """ assert sum('naming conventions' in str(ww.message) for ww in warns) == n_warn # check proper stacklevel reporting for ww in warns: if 'naming conventions' in str(ww.message): assert fname in ww.filename
[ "numpy.median", "numpy.testing.assert_array_equal", "numpy.clip", "numpy.mean", "scipy.linalg.norm", "numpy.testing.assert_equal", "numpy.testing.assert_allclose", "numpy.concatenate" ]
[((887, 935), 'numpy.clip', 'np.clip', (['error_rms', '(1e-60)', 'np.inf'], {'out': 'error_rms'}), '(error_rms, 1e-60, np.inf, out=error_rms)\n', (894, 935), True, 'import numpy as np\n'), ((1340, 1355), 'numpy.median', 'np.median', (['snrs'], {}), '(snrs)\n', (1349, 1355), True, 'import numpy as np\n'), ((1890, 1959), 'numpy.testing.assert_array_equal', 'assert_array_equal', (['picks', 'picks_desired'], {'err_msg': '"""MEG pick mismatch"""'}), "(picks, picks_desired, err_msg='MEG pick mismatch')\n", (1908, 1959), False, 'from numpy.testing import assert_allclose, assert_equal, assert_array_equal\n'), ((2542, 2615), 'numpy.testing.assert_array_equal', 'assert_array_equal', (['others', 'others_desired'], {'err_msg': '"""Other pick mismatch"""'}), "(others, others_desired, err_msg='Other pick mismatch')\n", (2560, 2615), False, 'from numpy.testing import assert_allclose, assert_equal, assert_array_equal\n'), ((742, 786), 'numpy.mean', 'np.mean', (['(desired_data * desired_data)'], {'axis': '(1)'}), '(desired_data * desired_data, axis=1)\n', (749, 786), True, 'import numpy as np\n'), ((851, 881), 'numpy.mean', 'np.mean', (['(error * error)'], {'axis': '(1)'}), '(error * error, axis=1)\n', (858, 881), True, 'import numpy as np\n'), ((2150, 2220), 'numpy.testing.assert_array_equal', 'assert_array_equal', (['chpis', 'chpis_desired'], {'err_msg': '"""cHPI pick mismatch"""'}), "(chpis, chpis_desired, err_msg='cHPI pick mismatch')\n", (2168, 2220), False, 'from numpy.testing import assert_allclose, assert_equal, assert_array_equal\n'), ((2306, 2336), 'numpy.concatenate', 'np.concatenate', (['[picks, chpis]'], {}), '([picks, chpis])\n', (2320, 2336), True, 'import numpy as np\n'), ((2440, 2486), 'numpy.concatenate', 'np.concatenate', (['[picks_desired, chpis_desired]'], {}), '([picks_desired, chpis_desired])\n', (2454, 2486), True, 'import numpy as np\n'), ((3187, 3218), 'scipy.linalg.norm', 'linalg.norm', (['desired'], {'ord': '"""fro"""'}), "(desired, ord='fro')\n", (3198, 3218), False, 'from scipy import linalg\n'), ((3232, 3272), 'scipy.linalg.norm', 'linalg.norm', (['(desired - actual)'], {'ord': '"""fro"""'}), "(desired - actual, ord='fro')\n", (3243, 3272), False, 'from scipy import linalg\n'), ((3839, 3972), 'numpy.testing.assert_allclose', 'assert_allclose', (["d_py['r']", "d_bin['r']"], {'rtol': '(1e-05)', 'atol': '(1e-05)', 'err_msg': '("""Failure on %s:\n%s\n%s""" % (ii, d_py[\'r\'], d_bin[\'r\']))'}), '(d_py[\'r\'], d_bin[\'r\'], rtol=1e-05, atol=1e-05, err_msg=\n """Failure on %s:\n%s\n%s""" % (ii, d_py[\'r\'], d_bin[\'r\']))\n', (3854, 3972), False, 'from numpy.testing import assert_allclose, assert_equal, assert_array_equal\n'), ((4309, 4349), 'numpy.testing.assert_allclose', 'assert_allclose', (['r_py', 'r_bin'], {'atol': '(1e-06)'}), '(r_py, r_bin, atol=1e-06)\n', (4324, 4349), False, 'from numpy.testing import assert_allclose, assert_equal, assert_array_equal\n'), ((4357, 4417), 'numpy.testing.assert_allclose', 'assert_allclose', (['o_dev_py', 'o_dev_bin'], {'rtol': '(1e-05)', 'atol': '(1e-06)'}), '(o_dev_py, o_dev_bin, rtol=1e-05, atol=1e-06)\n', (4372, 4417), False, 'from numpy.testing import assert_allclose, assert_equal, assert_array_equal\n'), ((4424, 4486), 'numpy.testing.assert_allclose', 'assert_allclose', (['o_head_py', 'o_head_bin'], {'rtol': '(1e-05)', 'atol': '(1e-06)'}), '(o_head_py, o_head_bin, rtol=1e-05, atol=1e-06)\n', (4439, 4486), False, 'from numpy.testing import assert_allclose, assert_equal, assert_array_equal\n'), ((3795, 3830), 'numpy.testing.assert_equal', 'assert_equal', (['d_py[key]', 'd_bin[key]'], {}), '(d_py[key], d_bin[key])\n', (3807, 3830), False, 'from numpy.testing import assert_allclose, assert_equal, assert_array_equal\n')]
import numpy as np import pandas as pd import os.path import random import collections from bisect import bisect_right from bisect import bisect_left from .. import multimatch_gaze as mp dtype = [ ("onset", "<f8"), ("duration", "<f8"), ("label", "<U10"), ("start_x", "<f8"), ("start_y", "<f8"), ("end_x", "<f8"), ("end_y", "<f8"), ("amp", "<f8"), ("peak_vel", "<f8"), ("med_vel", "<f8"), ("avg_vel", "<f8"), ] def same_sample(run=1, subj=1): """duplicate dataset to force exactly similar scanpaths. Choose the run (integer between 1-8) and whether you want a lab (1) or mri (2) subject""" if subj == 1: sub = "sub-30" else: sub = "sub-10" path = os.path.join( "multimatch_gaze/tests/testdata", "{}_task-movie_run-{}_events.tsv".format(sub, run), ) loc = os.path.join( "multimatch_gaze/tests/testdata", "locations_run-{}_events.tsv".format(run) ) data = np.recfromcsv( path, delimiter="\t", dtype={ "names": ( "onset", "duration", "label", "start_x", "start_y", "end_x", "end_y", "amp", "peak_vel", "med_vel", "avg_vel", ), "formats": ( "f8", "f8", "U10", "f8", "f8", "f8", "f8", "f8", "f8", "f8", "f8", ), }, ) data2 = data shots = pd.read_csv(loc, sep="\t") return data, data2, shots def short_shots(run=3): """create a shortened shots location annotation to test longshots()""" loc = os.path.join( "multimatch_gaze/tests/testdata", "locations_run-{}_events.tsv".format(run) ) shots = pd.read_csv(loc, sep="\t") shortshots = shots[0:20] return shortshots def mk_fix_vector(length=5): """creates a random length x 3 fixation vector in form of a record array""" fix = np.recarray( (0,), dtype=[("start_x", "<f8"), ("start_y", "<f8"), ("duration", "<f8")] ) for i in range(0, length): fixation = np.array( ( np.random.uniform(1, 720), np.random.uniform(1, 720), np.random.uniform(0.01, 5), ), dtype=[("start_x", float), ("start_y", float), ("duration", float)], ) fix = np.append(fix, fixation) return fix def mk_strucarray(length=5): """create a random scanpath in the data format generateScanpathStructureArray would output""" fixation_x = random.sample(range(700), length) fixation_y = random.sample(range(700), length) fixation_dur = random.sample(range(5), length) saccade_x = random.sample(range(700), length - 1) saccade_y = random.sample(range(700), length - 1) saccade_lenx = random.sample(range(700), length - 1) saccade_leny = random.sample(range(700), length - 1) saccade_rho = random.sample(range(700), length - 1) saccade_theta = random.sample(range(4), length - 1) eyedata = dict( fix=dict(x=fixation_x, y=fixation_y, dur=fixation_dur,), sac=dict( x=saccade_x, y=saccade_y, lenx=saccade_lenx, leny=saccade_leny, theta=saccade_theta, rho=saccade_rho, ), ) eyedata2 = dict( fix=dict( x=fixation_x[::-1] * 2, y=fixation_y[::-1] * 2, dur=fixation_dur[::-1] * 2, ), sac=dict( x=saccade_x[::-1] * 2, y=saccade_y[::-1] * 2, lenx=saccade_lenx[::-1] * 2, leny=saccade_leny[::-1] * 2, theta=saccade_theta[::-1] * 2, rho=saccade_rho[::-1] * 2, ), ) return eyedata, eyedata2 def mk_angles(): """creates vectors with predefined angular relations. angles1 and angles2 contain the following properties: 1. same 0, 2. 60 diff, 3. 90 diff, 4.120 diff,4. 180 diff (max. dissimilar). They are in sectors (0,1) and (0, -1). Angles3 and angles4 contain the same properties reversed and lie in sectors (-1, 0) and (-1, -1)""" angles1 = dict(sac=dict(theta=[0, 0.523, 0.785, 1.04, 1.57])) angles2 = dict(sac=dict(theta=[0, -0.523, -0.785, -1.04, -1.57])) angles3 = dict(sac=dict(theta=[1.57, 2.093, 2.356, 2.617, 3.14])) angles4 = dict(sac=dict(theta=[-1.57, -2.093, -2.356, -2.617, -3.14])) path = [0, 6, 12, 18, 24] M_assignment = np.arange(5 * 5).reshape(5, 5) return M_assignment, path, angles1, angles2, angles3, angles4 def mk_durs(): """create some example duration for test_durationsim()""" durations1 = collections.OrderedDict() durations2 = collections.OrderedDict() durations1 = dict(fix=dict(dur=[0.001, 20.0, 7, -18, -2.0])) durations2 = dict(fix=dict(dur=[0.008, 18.0, 7, -11, 3.0])) path = [0, 6, 12, 18, 24] M_assignment = np.arange(5 * 5).reshape(5, 5) return M_assignment, path, durations1, durations2 def mk_supershort_shots(): data = { "onset": np.arange(0, 20), "duration": np.repeat(1, 20), "locale": np.repeat("somewhere", 20), } shots = pd.DataFrame(data) return shots def mk_longershots(): data = { "onset": np.arange(0, 20), "duration": np.repeat(5, 20), "locale": np.repeat("somewhere", 20), } shots = pd.DataFrame(data) return shots # some functions to work specifically with studyforrest eye tracking data # Functions specifically for the data at hand def takeclosestright(mylist, mynumber): """Return integer closest right to 'myNumber' in an ordered list. :param: mylist: int :param: mynumber: array :return: after: float, number within mylist closest to right of my number """ pos = bisect_right(mylist, mynumber) if pos == 0: return mylist[0] if pos == len(mylist): return mylist[-1] after = mylist[pos] return after def takeclosestleft(mylist, mynumber): """Return integer closest left to 'myNumber' in an ordered list. :param: mylist: int :param: mynumber: array :return: after: float, number within mylist closest to the left of mynumber """ pos = bisect_left(mylist, mynumber) if pos == 0: return mylist[0] if pos == len(mylist): return mylist[-1] before = mylist[pos - 1] return before def create_onsets(data, dur): """Create shot onsets from studyforrests location annotation. Create onset times of all shots of at least 'dur' seconds of length. :param: data: dataframe location annotation from studyforrest :param: dur: float time in seconds a shot should at least be long :return: onsets: array-like, list of shot onset times """ onsets = [] for index, row in data.iterrows(): if row["duration"] >= dur: onsets.append(row["onset"]) return onsets def create_offsets(data, dur): """Create shot offsets from studyforrests location annotation. Create offset times of all shots of at least 'dur' seconds of length :param: data: dataframe, location annotation from studyforrest :param: dur: float, time in seconds a shot should at least be long :return: onsets: array-like, list of shot offset times """ offsets = [] for index, row in data.iterrows(): if row["duration"] >= dur: # calculate end of shot by adding onset + duration, subtract an # epsilon to be really sure not to get into a cut offsets.append(row["onset"] + row["duration"] - 0.03) return offsets def create_chunks(onsets, fixations, dur): """Chunk eyetracking data into scanpaths. Use onset data to obtain indices of full eyetracking data for chunking. :param: onsets: array-like, onset times of movie shots :param: fixations: record array, nx4 fixation vector (onset, x, y, duration), output of preprocess() function :param: dur: float, desired duration of segment length :return: startidx, endix: array, start and end ids of eyemovement data to chunk into segments """ # initialize empty lists startidx, endidx = [], [] for shotonset in onsets: start = takeclosestright(fixations["onset"], shotonset) startidx.append(np.where(fixations["onset"] == start)[0].tolist()) end = takeclosestright(fixations["onset"], shotonset + dur) endidx.append(np.where(fixations["onset"] == end)[0].tolist()) # flatten the nested lists startidx = [element for sublist in startidx for element in sublist] endidx = [element for sublist in endidx for element in sublist] return startidx, endidx def create_offsetchunks(offsets, fixations, dur): """Chunk eyetracking data into scanpaths. Use offset data to obtain indices of full eyetracking data for chunking. :param: offsets: array-like, offset times of movie shots :param: fixations: record array, nx4 fixation vector (onset, x, y, duration), output of preprocess() :param: dur: float, desired duration of segment length :return: startidx, endix: array start and end ids of eyemovement data to chunk into segments """ startidx, endidx = [], [] for shotoffset in offsets: start = takeclosestright(fixations["onset"], shotoffset - dur) startidx.append(np.where(fixations["onset"] == start)[0].tolist()) end = takeclosestleft(fixations["onset"], shotoffset) endidx.append(np.where(fixations["onset"] == end)[0].tolist()) # flatten the nested lists startidx = [element for sublist in startidx for element in sublist] endidx = [element for sublist in endidx for element in sublist] return startidx, endidx def fixations_chunks(fixations, startid, endid): """Chunk eyemovement data into scanpaths. :param: fixations: record array, nx4 fixation vector (onset, x, y, duration), output of preprocess() :param: startid, endid: array, start- and end-ids of the scanpaths, output from either create_chunks() or create_offsetchunks() :return: fixation_vector: array-like, a nx3 fixation vector (x, y, duration) """ fixation_vector = [] # slice fixation data according to indices, take columns # start_x, start_y and duration for idx in range(0, len(startid)): ind = fixations[startid[idx] : endid[idx]][["start_x", "start_y", "duration"]] fixation_vector.append(ind) return fixation_vector def pursuits_to_fixations(remodnav_data): """Transform start and endpoints of pursuits to fixations. Uses the output of a record array created by the remodnav algorithm for eye-movement classification to transform pursuit data into fixations. The start and end point of a pursuit are relabeled as a fixation. This is useful for example if the underlying stimulus material is a moving image - visual intake of a moving object would then resemble a pursuit. :param: npdata: recordarray, remodnav output of eyemovement data :return: newdata: recordarray """ # initialize empty rec array of the same shape newdata = np.recarray((0,), dtype=dtype) # reassemble rec array. # split pursuits to use end and start as fixations later from copy import deepcopy data = deepcopy(remodnav_data) for i, d in enumerate(data): if data[i]["label"] == "PURS": # start and end point of pursuit get # half the total duration d["duration"] = d["duration"] / 2 d["label"] = "FIXA" d2 = deepcopy(d) # end point of the pursuit is start # of new fixation d2["onset"] += d2["duration"] d2["start_x"] = d2["end_x"] d2["start_y"] = d2["end_y"] newdata = np.append(newdata, np.array(d, dtype=dtype)) newdata = np.append(newdata, np.array(d2, dtype=dtype)) else: newdata = np.append(newdata, np.array(d, dtype=dtype)) return newdata def preprocess_remodnav(data, screensize): """Preprocess record array of eye-events. A record array from REMoDNaV data is preprocessed in the following way: Subset to only get fixation data, disregard out-of-frame gazes, subset to only keep x, y coordinates, duration. :param: data: recordarray, REMoDNaV output of eye events from movie data :param: screensize: list of float, screen measurements in px :return: fixations: array-like nx3 fixation vectors (onset, x, y, duration) """ # only fixation labels filterevents = data[(data["label"] == "FIXA")] # within x coordinates? filterxbounds = filterevents[ np.logical_and( filterevents["start_x"] >= 0, filterevents["start_x"] <= screensize[0] ) ] # within y coordinates? filterybounds = filterxbounds[ np.logical_and( filterxbounds["start_y"] >= 0, filterxbounds["end_y"] <= screensize[1] ) ] # give me onset times, start_x, start_y and duration fixations = filterybounds[["onset", "start_x", "start_y", "duration"]] return fixations def read_remodnav(data): """ Helper to read input data produced by the REMoDNaV algorithm. Further information on the REMoDNaV algorithm can be found here: https://github.com/psychoinformatics-de/remodnav """ d = np.recfromcsv(data, delimiter="\t", dtype=dtype) return d def longshot(shots, group_shots, ldur=4.92): """Group movie shots without a cut together to obtain longer segments. Note: This way, fewer but longer scanpaths are obtained. Example: use median shotlength of 4.92s. :param: shots: dataframe, contains movie location annotation :param: group_shots: boolean, if True, grouping of movie shots is performed :param: dur: float, length in seconds for movie shot. An attempt is made to group short shots without a cut together to form longer shots of ldur length :return: aggregated, dataframe of aggregated movie shots """ # turn pandas dataframe shots into record array structshots = shots.to_records() if group_shots: i = 0 while i < len(structshots): # break before running into index error if structshots[i] == structshots[-1]: break else: if ( (structshots[i]["duration"] < ldur) & (structshots[i + 1]["duration"] < ldur) & (structshots[i]["locale"] == structshots[i + 1]["locale"]) ): # add durations together and delete second row structshots[i]["duration"] += structshots[i + 1]["duration"] structshots = np.delete(structshots, i + 1, 0) else: i += 1 aggregated = pd.DataFrame( { "onset": structshots["onset"].tolist(), "duration": structshots["duration"].tolist(), }, columns=["onset", "duration"], ) return aggregated def docomparison_forrest( shots, data1, data2, screensize=[1280, 720], dur=4.92, ldur=0, offset=False, TDur=0, TDir=0, TAmp=0, grouping=False, ): """Compare two scanpaths on five similarity dimensions. :param: data1, data2: recarray, eyemovement information of forrest gump studyforrest dataset :param: screensize: list, screen dimensions in px. :param: ldur: float, duration in seconds. An attempt is made to group short shots together to form shots of ldur length :param: grouping: boolean, if True, simplification is performed based on thresholds TAmp, TDir, and TDur :param: TDir: float, Direction threshold, angle in degrees. :param: TDur: float, Duration threshold, duration in seconds. :param: TAmp: float, Amplitude threshold, length in px. :return: scanpathcomparisons: array array of 5 scanpath similarity measures :return: durations: array-like durations of extracted scanpaths. Vector (Shape), Direction (Angle), Length, Position, and Duration. 1 = absolute similarity, 0 = lowest similarity possible. :return: onsets: array-like onset times of the scanpaths """ # determine whether short shots should be grouped together if ldur != 0: group_shots = True else: group_shots = False scanpathcomparisons = [] # transform pursuits into fixations newdata1 = pursuits_to_fixations(data1) newdata2 = pursuits_to_fixations(data2) print("Loaded data.") # preprocess input files fixations1 = preprocess_remodnav(newdata1, screensize) fixations2 = preprocess_remodnav(newdata2, screensize) shots = longshot(shots, group_shots, ldur) # get shots and scanpath on- and offsets if offset: onset = create_offsets(shots, dur) startid1, endid1 = create_offsetchunks(onset, fixations1, dur) startid2, endid2 = create_offsetchunks(onset, fixations2, dur) else: onset = create_onsets(shots, dur) startid1, endid1 = create_chunks(onset, fixations1, dur) startid2, endid2 = create_chunks(onset, fixations2, dur) fixation_vectors1 = fixations_chunks(fixations1, startid1, endid1) fixation_vectors2 = fixations_chunks(fixations2, startid2, endid2) print("Split fixation data into {} scanpaths.".format(len(startid1))) # save onset and duration times, if valid ones can be calculated onset_times = [] exact_durations = [] for i in range(0, len(startid1)): onset_time = fixations1[startid1[i]]["onset"] onset_times.append(onset_time) exact_duration = ( fixations1[endid1[i]]["onset"] - fixations1[startid1[i]]["onset"] ) # capture negative durations for invalid scanpaths if exact_duration > 0: exact_durations.append(exact_duration) else: exact_durations.append(np.nan) if i == len(startid1): print("Captured onsets and duration" " times of all scanpath pairs.") # loop over all fixation vectors/scanpaths and calculate similarity for i in range(0, len(onset)): # check if fixation vectors/scanpaths are long enough if (len(fixation_vectors1[i]) >= 3) & (len(fixation_vectors2[i]) >= 3): subj1 = mp.gen_scanpath_structure(fixation_vectors1[i]) subj2 = mp.gen_scanpath_structure(fixation_vectors2[i]) if grouping: subj1 = mp.simplify_scanpath(subj1, TAmp, TDir, TDur) subj2 = mp.simplify_scanpath(subj2, TAmp, TDir, TDur) M = mp.cal_vectordifferences(subj1, subj2) scanpath_dim = np.shape(M) M_assignment = np.arange(scanpath_dim[0] * scanpath_dim[1]).reshape( scanpath_dim[0], scanpath_dim[1] ) numVert, rows, cols, weight = mp.createdirectedgraph( scanpath_dim, M, M_assignment ) path, dist = mp.dijkstra( numVert, rows, cols, weight, 0, scanpath_dim[0] * scanpath_dim[1] - 1 ) unnormalised = mp.getunnormalised(subj1, subj2, path, M_assignment) normal = mp.normaliseresults(unnormalised, screensize) scanpathcomparisons.append(normal) # return nan as result if at least one scanpath it too short else: scanpathcomparisons.append(np.repeat(np.nan, 5)) print( "Scanpath {} had a length of {}, however, a minimal " "length of 3 is required. Appending nan.".format( i, min(len(fixation_vectors1), len(fixation_vectors2)) ) ) return scanpathcomparisons, onset_times, exact_durations
[ "pandas.DataFrame", "numpy.random.uniform", "copy.deepcopy", "numpy.logical_and", "pandas.read_csv", "bisect.bisect_right", "numpy.recfromcsv", "numpy.recarray", "numpy.shape", "numpy.append", "numpy.where", "numpy.arange", "numpy.array", "collections.OrderedDict", "bisect.bisect_left", ...
[((976, 1233), 'numpy.recfromcsv', 'np.recfromcsv', (['path'], {'delimiter': '"""\t"""', 'dtype': "{'names': ('onset', 'duration', 'label', 'start_x', 'start_y', 'end_x',\n 'end_y', 'amp', 'peak_vel', 'med_vel', 'avg_vel'), 'formats': ('f8',\n 'f8', 'U10', 'f8', 'f8', 'f8', 'f8', 'f8', 'f8', 'f8', 'f8')}"}), "(path, delimiter='\\t', dtype={'names': ('onset', 'duration',\n 'label', 'start_x', 'start_y', 'end_x', 'end_y', 'amp', 'peak_vel',\n 'med_vel', 'avg_vel'), 'formats': ('f8', 'f8', 'U10', 'f8', 'f8', 'f8',\n 'f8', 'f8', 'f8', 'f8', 'f8')})\n", (989, 1233), True, 'import numpy as np\n'), ((1699, 1725), 'pandas.read_csv', 'pd.read_csv', (['loc'], {'sep': '"""\t"""'}), "(loc, sep='\\t')\n", (1710, 1725), True, 'import pandas as pd\n'), ((1983, 2009), 'pandas.read_csv', 'pd.read_csv', (['loc'], {'sep': '"""\t"""'}), "(loc, sep='\\t')\n", (1994, 2009), True, 'import pandas as pd\n'), ((2182, 2273), 'numpy.recarray', 'np.recarray', (['(0,)'], {'dtype': "[('start_x', '<f8'), ('start_y', '<f8'), ('duration', '<f8')]"}), "((0,), dtype=[('start_x', '<f8'), ('start_y', '<f8'), (\n 'duration', '<f8')])\n", (2193, 2273), True, 'import numpy as np\n'), ((4887, 4912), 'collections.OrderedDict', 'collections.OrderedDict', ([], {}), '()\n', (4910, 4912), False, 'import collections\n'), ((4930, 4955), 'collections.OrderedDict', 'collections.OrderedDict', ([], {}), '()\n', (4953, 4955), False, 'import collections\n'), ((5398, 5416), 'pandas.DataFrame', 'pd.DataFrame', (['data'], {}), '(data)\n', (5410, 5416), True, 'import pandas as pd\n'), ((5608, 5626), 'pandas.DataFrame', 'pd.DataFrame', (['data'], {}), '(data)\n', (5620, 5626), True, 'import pandas as pd\n'), ((6031, 6061), 'bisect.bisect_right', 'bisect_right', (['mylist', 'mynumber'], {}), '(mylist, mynumber)\n', (6043, 6061), False, 'from bisect import bisect_right\n'), ((6461, 6490), 'bisect.bisect_left', 'bisect_left', (['mylist', 'mynumber'], {}), '(mylist, mynumber)\n', (6472, 6490), False, 'from bisect import bisect_left\n'), ((11482, 11512), 'numpy.recarray', 'np.recarray', (['(0,)'], {'dtype': 'dtype'}), '((0,), dtype=dtype)\n', (11493, 11512), True, 'import numpy as np\n'), ((11644, 11667), 'copy.deepcopy', 'deepcopy', (['remodnav_data'], {}), '(remodnav_data)\n', (11652, 11667), False, 'from copy import deepcopy\n'), ((13748, 13796), 'numpy.recfromcsv', 'np.recfromcsv', (['data'], {'delimiter': '"""\t"""', 'dtype': 'dtype'}), "(data, delimiter='\\t', dtype=dtype)\n", (13761, 13796), True, 'import numpy as np\n'), ((2607, 2631), 'numpy.append', 'np.append', (['fix', 'fixation'], {}), '(fix, fixation)\n', (2616, 2631), True, 'import numpy as np\n'), ((5278, 5294), 'numpy.arange', 'np.arange', (['(0)', '(20)'], {}), '(0, 20)\n', (5287, 5294), True, 'import numpy as np\n'), ((5316, 5332), 'numpy.repeat', 'np.repeat', (['(1)', '(20)'], {}), '(1, 20)\n', (5325, 5332), True, 'import numpy as np\n'), ((5352, 5378), 'numpy.repeat', 'np.repeat', (['"""somewhere"""', '(20)'], {}), "('somewhere', 20)\n", (5361, 5378), True, 'import numpy as np\n'), ((5488, 5504), 'numpy.arange', 'np.arange', (['(0)', '(20)'], {}), '(0, 20)\n', (5497, 5504), True, 'import numpy as np\n'), ((5526, 5542), 'numpy.repeat', 'np.repeat', (['(5)', '(20)'], {}), '(5, 20)\n', (5535, 5542), True, 'import numpy as np\n'), ((5562, 5588), 'numpy.repeat', 'np.repeat', (['"""somewhere"""', '(20)'], {}), "('somewhere', 20)\n", (5571, 5588), True, 'import numpy as np\n'), ((13059, 13149), 'numpy.logical_and', 'np.logical_and', (["(filterevents['start_x'] >= 0)", "(filterevents['start_x'] <= screensize[0])"], {}), "(filterevents['start_x'] >= 0, filterevents['start_x'] <=\n screensize[0])\n", (13073, 13149), True, 'import numpy as np\n'), ((13245, 13335), 'numpy.logical_and', 'np.logical_and', (["(filterxbounds['start_y'] >= 0)", "(filterxbounds['end_y'] <= screensize[1])"], {}), "(filterxbounds['start_y'] >= 0, filterxbounds['end_y'] <=\n screensize[1])\n", (13259, 13335), True, 'import numpy as np\n'), ((4694, 4710), 'numpy.arange', 'np.arange', (['(5 * 5)'], {}), '(5 * 5)\n', (4703, 4710), True, 'import numpy as np\n'), ((5134, 5150), 'numpy.arange', 'np.arange', (['(5 * 5)'], {}), '(5 * 5)\n', (5143, 5150), True, 'import numpy as np\n'), ((11923, 11934), 'copy.deepcopy', 'deepcopy', (['d'], {}), '(d)\n', (11931, 11934), False, 'from copy import deepcopy\n'), ((19159, 19170), 'numpy.shape', 'np.shape', (['M'], {}), '(M)\n', (19167, 19170), True, 'import numpy as np\n'), ((2373, 2398), 'numpy.random.uniform', 'np.random.uniform', (['(1)', '(720)'], {}), '(1, 720)\n', (2390, 2398), True, 'import numpy as np\n'), ((2416, 2441), 'numpy.random.uniform', 'np.random.uniform', (['(1)', '(720)'], {}), '(1, 720)\n', (2433, 2441), True, 'import numpy as np\n'), ((2459, 2485), 'numpy.random.uniform', 'np.random.uniform', (['(0.01)', '(5)'], {}), '(0.01, 5)\n', (2476, 2485), True, 'import numpy as np\n'), ((12176, 12200), 'numpy.array', 'np.array', (['d'], {'dtype': 'dtype'}), '(d, dtype=dtype)\n', (12184, 12200), True, 'import numpy as np\n'), ((12243, 12268), 'numpy.array', 'np.array', (['d2'], {'dtype': 'dtype'}), '(d2, dtype=dtype)\n', (12251, 12268), True, 'import numpy as np\n'), ((12325, 12349), 'numpy.array', 'np.array', (['d'], {'dtype': 'dtype'}), '(d, dtype=dtype)\n', (12333, 12349), True, 'import numpy as np\n'), ((19895, 19915), 'numpy.repeat', 'np.repeat', (['np.nan', '(5)'], {}), '(np.nan, 5)\n', (19904, 19915), True, 'import numpy as np\n'), ((15150, 15182), 'numpy.delete', 'np.delete', (['structshots', '(i + 1)', '(0)'], {}), '(structshots, i + 1, 0)\n', (15159, 15182), True, 'import numpy as np\n'), ((19198, 19242), 'numpy.arange', 'np.arange', (['(scanpath_dim[0] * scanpath_dim[1])'], {}), '(scanpath_dim[0] * scanpath_dim[1])\n', (19207, 19242), True, 'import numpy as np\n'), ((8587, 8624), 'numpy.where', 'np.where', (["(fixations['onset'] == start)"], {}), "(fixations['onset'] == start)\n", (8595, 8624), True, 'import numpy as np\n'), ((8728, 8763), 'numpy.where', 'np.where', (["(fixations['onset'] == end)"], {}), "(fixations['onset'] == end)\n", (8736, 8763), True, 'import numpy as np\n'), ((9665, 9702), 'numpy.where', 'np.where', (["(fixations['onset'] == start)"], {}), "(fixations['onset'] == start)\n", (9673, 9702), True, 'import numpy as np\n'), ((9800, 9835), 'numpy.where', 'np.where', (["(fixations['onset'] == end)"], {}), "(fixations['onset'] == end)\n", (9808, 9835), True, 'import numpy as np\n')]
import numpy as np import numba as nb nb_parallel = True # not sure if this makes any difference on the cluster @nb.njit(parallel=nb_parallel) def get_sphere_mask(pos, center, radius): """Calculate a spherical mask with given center and radius. Returns a boolean mask that filters out the particles given by pos that are within the given radius from center. """ return np.sum((pos - center)**2, axis=1) < radius**2 @nb.njit(parallel=nb_parallel) def mean_pos(pos): """Calculate mean position (mean over axis 0). Needed since numba does not support np.mean with axis argument. Warning: numba does not support the dtype argument, so numeric errors may occur if data is single precision. """ return np.sum(pos, axis=0) / len(pos) @nb.njit def mean_pos_pbc(pos, box_size): """Compute center of a cluster in a periodic box. Periodic box is assumed to be [0, box_size] Method from Bai and Breen 2008. (https://en.wikipedia.org/wiki/Center_of_mass#Systems_with_periodic_boundary_conditions) """ theta = 2*np.pi * pos / box_size x = -mean_pos(np.cos(theta)) y = -mean_pos(np.sin(theta)) return box_size * (np.arctan2(y, x) + np.pi) / (2*np.pi) def wrap_pbc(coords, box_size, in_place=False): dx = box_size*(coords < -box_size/2) - box_size*(coords >= box_size/2) if in_place: coords += dx return return coords + dx @nb.njit def center_box_pbc(coords, center, box_size): """Recenter positions in a periodic box on a given center. Returns coordinates in range [-L/2, L/2) centered on given center. """ dx = center + box_size*(center < -box_size/2) - box_size*(center >= box_size/2) coords_centered = coords - dx coords_centered += box_size*(coords_centered < -box_size/2) \ - box_size*(coords_centered >= box_size/2) return coords_centered def sphere_volume(radius, a=1): """Volume of a sphere with an optional scale factor.""" return 4/3 * np.pi * (a * radius)**3 @nb.njit def calc_vr_phys(pos, vel, center, radius, a, H, h): """Calculate physical radial velocities. Calculates physical radial velocities (km/s) wrt to given center for all particles given by (pos, vel). (center, radius) determines the boundary of the halo which is used to calculate the velocity of the center of mass. H is the Hubble parameter at the given scale factor a, while h = H0/100. Returns distances of particles from center as well as radial velocities. """ pos_centered = pos - center p_radii = np.sqrt(np.sum(pos_centered**2, axis=1)) vel_center = mean_pos(vel[p_radii < radius]) vel_peculiar = np.sqrt(a) * (vel - vel_center) unit_vectors = pos_centered / np.expand_dims(p_radii, 1) vr_peculiar = np.multiply(vel_peculiar, unit_vectors).sum(1) hubble_flow = H * a * p_radii / h vr_physical = vr_peculiar + hubble_flow return p_radii, vr_physical @nb.njit def calc_hmf(bins, masses, box_size): """Calculate the halo mass function given masses and bins. Returns number densitesy of halos more massive than given bin values and errors assuming a Poisson counting process. """ hmf = np.zeros_like(bins) errors = np.zeros_like(bins) for i, thresh in enumerate(bins): count = np.sum(masses > thresh) hmf[i] = count / box_size**3 errors[i] = np.sqrt(count) / box_size**3 return hmf, errors
[ "numpy.zeros_like", "numpy.sum", "numpy.multiply", "numpy.arctan2", "numba.njit", "numpy.expand_dims", "numpy.sin", "numpy.cos", "numpy.sqrt" ]
[((117, 146), 'numba.njit', 'nb.njit', ([], {'parallel': 'nb_parallel'}), '(parallel=nb_parallel)\n', (124, 146), True, 'import numba as nb\n'), ((443, 472), 'numba.njit', 'nb.njit', ([], {'parallel': 'nb_parallel'}), '(parallel=nb_parallel)\n', (450, 472), True, 'import numba as nb\n'), ((3233, 3252), 'numpy.zeros_like', 'np.zeros_like', (['bins'], {}), '(bins)\n', (3246, 3252), True, 'import numpy as np\n'), ((3266, 3285), 'numpy.zeros_like', 'np.zeros_like', (['bins'], {}), '(bins)\n', (3279, 3285), True, 'import numpy as np\n'), ((394, 429), 'numpy.sum', 'np.sum', (['((pos - center) ** 2)'], {'axis': '(1)'}), '((pos - center) ** 2, axis=1)\n', (400, 429), True, 'import numpy as np\n'), ((748, 767), 'numpy.sum', 'np.sum', (['pos'], {'axis': '(0)'}), '(pos, axis=0)\n', (754, 767), True, 'import numpy as np\n'), ((2604, 2637), 'numpy.sum', 'np.sum', (['(pos_centered ** 2)'], {'axis': '(1)'}), '(pos_centered ** 2, axis=1)\n', (2610, 2637), True, 'import numpy as np\n'), ((2705, 2715), 'numpy.sqrt', 'np.sqrt', (['a'], {}), '(a)\n', (2712, 2715), True, 'import numpy as np\n'), ((2771, 2797), 'numpy.expand_dims', 'np.expand_dims', (['p_radii', '(1)'], {}), '(p_radii, 1)\n', (2785, 2797), True, 'import numpy as np\n'), ((3340, 3363), 'numpy.sum', 'np.sum', (['(masses > thresh)'], {}), '(masses > thresh)\n', (3346, 3363), True, 'import numpy as np\n'), ((1119, 1132), 'numpy.cos', 'np.cos', (['theta'], {}), '(theta)\n', (1125, 1132), True, 'import numpy as np\n'), ((1152, 1165), 'numpy.sin', 'np.sin', (['theta'], {}), '(theta)\n', (1158, 1165), True, 'import numpy as np\n'), ((2816, 2855), 'numpy.multiply', 'np.multiply', (['vel_peculiar', 'unit_vectors'], {}), '(vel_peculiar, unit_vectors)\n', (2827, 2855), True, 'import numpy as np\n'), ((3421, 3435), 'numpy.sqrt', 'np.sqrt', (['count'], {}), '(count)\n', (3428, 3435), True, 'import numpy as np\n'), ((1190, 1206), 'numpy.arctan2', 'np.arctan2', (['y', 'x'], {}), '(y, x)\n', (1200, 1206), True, 'import numpy as np\n')]
import textwrap from typing import Optional, Dict, Any, Union, TYPE_CHECKING import numpy as np import qcodes.utils.validators as vals from qcodes.utils.validators import Arrays from .KeysightB1500_sampling_measurement import SamplingMeasurement from .KeysightB1500_module import B1500Module, parse_spot_measurement_response from .message_builder import MessageBuilder from . import constants from .constants import ModuleKind, ChNr, AAD, MM if TYPE_CHECKING: from .KeysightB1500_base import KeysightB1500 class B1517A(B1500Module): """ Driver for Keysight B1517A Source/Monitor Unit module for B1500 Semiconductor Parameter Analyzer. Args: parent: mainframe B1500 instance that this module belongs to name: Name of the instrument instance to create. If `None` (Default), then the name is autogenerated from the instrument class. slot_nr: Slot number of this module (not channel number) """ MODULE_KIND = ModuleKind.SMU _interval_validator = vals.Numbers(0.0001, 65.535) def __init__(self, parent: 'KeysightB1500', name: Optional[str], slot_nr, **kwargs): super().__init__(parent, name, slot_nr, **kwargs) self.channels = (ChNr(slot_nr),) self._measure_config: Dict[str, Optional[Any]] = { k: None for k in ("measure_range",)} self._source_config: Dict[str, Optional[Any]] = { k: None for k in ("output_range", "compliance", "compl_polarity", "min_compliance_range")} self._timing_parameters: Dict[str, Optional[Any]] = { k: None for k in ("h_bias", "interval", "number", "h_base")} # We want to snapshot these configuration dictionaries self._meta_attrs += ['_measure_config', '_source_config', '_timing_parameters'] self.add_parameter( name="measurement_mode", get_cmd=None, set_cmd=self._set_measurement_mode, set_parser=MM.Mode, vals=vals.Enum(*list(MM.Mode)), docstring=textwrap.dedent(""" Set measurement mode for this module. It is recommended for this parameter to use values from :class:`.constants.MM.Mode` enumeration. Refer to the documentation of ``MM`` command in the programming guide for more information.""") ) # Instrument is initialized with this setting having value of # `1`, spot measurement mode, hence let's set the parameter to this # value since it is not possible to request this value from the # instrument. self.measurement_mode.cache.set(MM.Mode.SPOT) self.add_parameter( name="voltage", unit="V", set_cmd=self._set_voltage, get_cmd=self._get_voltage, snapshot_get=False ) self.add_parameter( name="current", unit="A", set_cmd=self._set_current, get_cmd=self._get_current, snapshot_get=False ) self.add_parameter( name="time_axis", get_cmd=self._get_time_axis, vals=Arrays(shape=(self._get_number_of_samples,)), snapshot_value=False, label='Time', unit='s' ) self.add_parameter( name="sampling_measurement_trace", parameter_class=SamplingMeasurement, vals=Arrays(shape=(self._get_number_of_samples,)), setpoints=(self.time_axis,) ) def _get_number_of_samples(self) -> int: if self._timing_parameters['number'] is not None: sample_number = self._timing_parameters['number'] return sample_number else: raise Exception('set timing parameters first') def _get_time_axis(self) -> np.ndarray: sample_rate = self._timing_parameters['interval'] total_time = self._total_measurement_time() time_xaxis = np.arange(0, total_time, sample_rate) return time_xaxis def _total_measurement_time(self) -> float: if self._timing_parameters['interval'] is None or \ self._timing_parameters['number'] is None: raise Exception('set timing parameters first') sample_number = self._timing_parameters['number'] sample_rate = self._timing_parameters['interval'] total_time = float(sample_rate * sample_number) return total_time def _set_voltage(self, value: float) -> None: if self._source_config["output_range"] is None: self._source_config["output_range"] = constants.VOutputRange.AUTO if not isinstance(self._source_config["output_range"], constants.VOutputRange): raise TypeError( "Asking to force voltage, but source_config contains a " "current output range" ) msg = MessageBuilder().dv( chnum=self.channels[0], v_range=self._source_config["output_range"], voltage=value, i_comp=self._source_config["compliance"], comp_polarity=self._source_config["compl_polarity"], i_range=self._source_config["min_compliance_range"], ) self.write(msg.message) def _set_current(self, value: float) -> None: if self._source_config["output_range"] is None: self._source_config["output_range"] = constants.IOutputRange.AUTO if not isinstance(self._source_config["output_range"], constants.IOutputRange): raise TypeError( "Asking to force current, but source_config contains a " "voltage output range" ) msg = MessageBuilder().di( chnum=self.channels[0], i_range=self._source_config["output_range"], current=value, v_comp=self._source_config["compliance"], comp_polarity=self._source_config["compl_polarity"], v_range=self._source_config["min_compliance_range"], ) self.write(msg.message) def _get_current(self) -> float: msg = MessageBuilder().ti( chnum=self.channels[0], i_range=self._measure_config["measure_range"], ) response = self.ask(msg.message) parsed = parse_spot_measurement_response(response) return parsed["value"] def _get_voltage(self) -> float: msg = MessageBuilder().tv( chnum=self.channels[0], v_range=self._measure_config["measure_range"], ) response = self.ask(msg.message) parsed = parse_spot_measurement_response(response) return parsed["value"] def _set_measurement_mode(self, mode: Union[MM.Mode, int]) -> None: self.write(MessageBuilder() .mm(mode=mode, channels=[self.channels[0]]) .message) def source_config( self, output_range: constants.OutputRange, compliance: Optional[Union[float, int]] = None, compl_polarity: Optional[constants.CompliancePolarityMode] = None, min_compliance_range: Optional[constants.OutputRange] = None, ) -> None: """Configure sourcing voltage/current Args: output_range: voltage/current output range compliance: voltage/current compliance value compl_polarity: compliance polarity mode min_compliance_range: minimum voltage/current compliance output range """ if min_compliance_range is not None: if isinstance(min_compliance_range, type(output_range)): raise TypeError( "When forcing voltage, min_compliance_range must be an " "current output range (and vice versa)." ) self._source_config = { "output_range": output_range, "compliance": compliance, "compl_polarity": compl_polarity, "min_compliance_range": min_compliance_range, } def measure_config(self, measure_range: constants.MeasureRange) -> None: """Configure measuring voltage/current Args: measure_range: voltage/current measurement range """ self._measure_config = {"measure_range": measure_range} def timing_parameters(self, h_bias: float, interval: float, number: int, h_base: Optional[float] = None ) -> None: """ This command sets the timing parameters of the sampling measurement mode (:attr:`.MM.Mode.SAMPLING`, ``10``). Refer to the programming guide for more information about the ``MT`` command, especially for notes on sampling operation and about setting interval < 0.002 s. Args: h_bias: Time since the bias value output until the first sampling point. Numeric expression. in seconds. 0 (initial setting) to 655.35 s, resolution 0.01 s. The following values are also available for interval < 0.002 s. ``|h_bias|`` will be the time since the sampling start until the bias value output. -0.09 to -0.0001 s, resolution 0.0001 s. interval: Interval of the sampling. Numeric expression, 0.0001 to 65.535, in seconds. Initial value is 0.002. Resolution is 0.001 at interval < 0.002. Linear sampling of interval < 0.002 in 0.00001 resolution is available only when the following formula is satisfied. ``interval >= 0.0001 + 0.00002 * (number of measurement channels-1)`` number: Number of samples. Integer expression. 1 to the following value. Initial value is 1000. For the linear sampling: ``100001 / (number of measurement channels)``. For the log sampling: ``1 + (number of data for 11 decades)`` h_base: Hold time of the base value output until the bias value output. Numeric expression. in seconds. 0 (initial setting) to 655.35 s, resolution 0.01 s. """ # The duplication of kwargs in the calls below is due to the # difference in type annotations between ``MessageBuilder.mt()`` # method and ``_timing_parameters`` attribute. self._interval_validator.validate(interval) self._timing_parameters.update(h_bias=h_bias, interval=interval, number=number, h_base=h_base) self.write(MessageBuilder() .mt(h_bias=h_bias, interval=interval, number=number, h_base=h_base) .message) def use_high_speed_adc(self) -> None: """Use high-speed ADC type for this module/channel""" self.write(MessageBuilder() .aad(chnum=self.channels[0], adc_type=AAD.Type.HIGH_SPEED) .message) def use_high_resolution_adc(self) -> None: """Use high-resolution ADC type for this module/channel""" self.write(MessageBuilder() .aad(chnum=self.channels[0], adc_type=AAD.Type.HIGH_RESOLUTION) .message)
[ "textwrap.dedent", "numpy.arange", "qcodes.utils.validators.Arrays", "qcodes.utils.validators.Numbers" ]
[((1026, 1054), 'qcodes.utils.validators.Numbers', 'vals.Numbers', (['(0.0001)', '(65.535)'], {}), '(0.0001, 65.535)\n', (1038, 1054), True, 'import qcodes.utils.validators as vals\n'), ((4121, 4158), 'numpy.arange', 'np.arange', (['(0)', 'total_time', 'sample_rate'], {}), '(0, total_time, sample_rate)\n', (4130, 4158), True, 'import numpy as np\n'), ((2114, 2490), 'textwrap.dedent', 'textwrap.dedent', (['"""\n Set measurement mode for this module.\n \n It is recommended for this parameter to use values from \n :class:`.constants.MM.Mode` enumeration.\n \n Refer to the documentation of ``MM`` command in the \n programming guide for more information."""'], {}), '(\n """\n Set measurement mode for this module.\n \n It is recommended for this parameter to use values from \n :class:`.constants.MM.Mode` enumeration.\n \n Refer to the documentation of ``MM`` command in the \n programming guide for more information."""\n )\n', (2129, 2490), False, 'import textwrap\n'), ((3298, 3342), 'qcodes.utils.validators.Arrays', 'Arrays', ([], {'shape': '(self._get_number_of_samples,)'}), '(shape=(self._get_number_of_samples,))\n', (3304, 3342), False, 'from qcodes.utils.validators import Arrays\n'), ((3577, 3621), 'qcodes.utils.validators.Arrays', 'Arrays', ([], {'shape': '(self._get_number_of_samples,)'}), '(shape=(self._get_number_of_samples,))\n', (3583, 3621), False, 'from qcodes.utils.validators import Arrays\n')]
# Copyright 2019 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Diff proto objects returning paths to changed attributes.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np def summarize_array_diffs(lhs, rhs): """Output value differences, with index for each, between two arrays.""" result = [] indices = np.transpose(np.nonzero(lhs - rhs)) for row in indices: index = tuple(np.array([e]) for e in row.tolist()) lhs_element = lhs[index] rhs_element = rhs[index] result.append( "{}: {} -> {}".format( "".join("[{}]".format(i) for i in row), lhs_element[0], rhs_element[0] ) ) if indices.size: return "{} element(s) changed - ".format(len(indices)) + "; ".join(result) else: return ""
[ "numpy.nonzero", "numpy.array" ]
[((950, 971), 'numpy.nonzero', 'np.nonzero', (['(lhs - rhs)'], {}), '(lhs - rhs)\n', (960, 971), True, 'import numpy as np\n'), ((1019, 1032), 'numpy.array', 'np.array', (['[e]'], {}), '([e])\n', (1027, 1032), True, 'import numpy as np\n')]
from train import * import os import numpy as np import torch from torch.nn import functional as F from utils import cropping, load_data, get_transform, load_otb_data import os os.environ['CUDA_VISIBLE_DEVICES']='0' def test(env, R, root_dir, data_name='vot'): R.agent.eval() if data_name=='vot': imglist, gt_bboxes = load_data(root_dir) elif data_name == 'otb': imglist, gt_bboxes = load_otb_data(root_dir) else: return [] init_gt = gt_bboxes[0] end = len(gt_bboxes) predicted_list = [init_gt] bbox = init_gt e = 0 while e < end-1: # initialize the env. Current frame and previous bbox env.reset(imglist[e+1], gt_bboxes[e], bbox) # predict full episode print('tracking %d frame...' % (e+1)) while True: bbox_img = cropping(env.img, env.state) bbox_img = R.transforms(bbox_img).cuda() bbox_img = bbox_img.unsqueeze(0) q_value, stop = R.agent(bbox_img) stop = F.softmax(stop.cpu(), dim=1) if stop[0][1] > 0.5: action = 10 # stop else: action = torch.argmax(q_value) _, is_t, r = env.step(action) if is_t: break e = e + 1 predicted_list.append(env.state) bbox = env.state return predicted_list def main(): # create model args = parse_arguments() env = Env() transforms = get_transform() R = Reinforce(None, transforms=transforms) # load weights if os.path.isfile(args.resume): print("=> loading checkpoint '{}'".format(args.resume)) checkpoint = torch.load(args.resume) R.agent.load_state_dict(checkpoint['state_dict']) print("=> loaded checkpoint '{}' (epoch {})" .format(args.resume, checkpoint['epoch'])) else: print("=> no checkpoint found at '{}'".format(args.resume)) predicted_list = test(env, R, args.data) # save result predicted_list = np.vstack(predicted_list) np.savetxt('predicted_bbox', predicted_list, fmt='%.3f', delimiter=',') if __name__ == '__main__': main()
[ "utils.cropping", "utils.load_data", "utils.load_otb_data", "torch.argmax", "torch.load", "numpy.savetxt", "os.path.isfile", "utils.get_transform", "numpy.vstack" ]
[((1487, 1502), 'utils.get_transform', 'get_transform', ([], {}), '()\n', (1500, 1502), False, 'from utils import cropping, load_data, get_transform, load_otb_data\n'), ((1577, 1604), 'os.path.isfile', 'os.path.isfile', (['args.resume'], {}), '(args.resume)\n', (1591, 1604), False, 'import os\n'), ((2047, 2072), 'numpy.vstack', 'np.vstack', (['predicted_list'], {}), '(predicted_list)\n', (2056, 2072), True, 'import numpy as np\n'), ((2077, 2148), 'numpy.savetxt', 'np.savetxt', (['"""predicted_bbox"""', 'predicted_list'], {'fmt': '"""%.3f"""', 'delimiter': '""","""'}), "('predicted_bbox', predicted_list, fmt='%.3f', delimiter=',')\n", (2087, 2148), True, 'import numpy as np\n'), ((337, 356), 'utils.load_data', 'load_data', (['root_dir'], {}), '(root_dir)\n', (346, 356), False, 'from utils import cropping, load_data, get_transform, load_otb_data\n'), ((1691, 1714), 'torch.load', 'torch.load', (['args.resume'], {}), '(args.resume)\n', (1701, 1714), False, 'import torch\n'), ((415, 438), 'utils.load_otb_data', 'load_otb_data', (['root_dir'], {}), '(root_dir)\n', (428, 438), False, 'from utils import cropping, load_data, get_transform, load_otb_data\n'), ((837, 865), 'utils.cropping', 'cropping', (['env.img', 'env.state'], {}), '(env.img, env.state)\n', (845, 865), False, 'from utils import cropping, load_data, get_transform, load_otb_data\n'), ((1173, 1194), 'torch.argmax', 'torch.argmax', (['q_value'], {}), '(q_value)\n', (1185, 1194), False, 'import torch\n')]
import numpy as np def euclidean_distance(x: np.array, y: np.array) -> float: """Calculates euclidean distance. This function calculates euclidean distance between two points x and y in Euclidean n-space. Args: x, y: points in Euclidean n-space. Returns: length of the line segment connecting given points. """ return np.sqrt(np.sum((x - y) ** 2)) def euclidean_similarity(x: np.array, y: np.array) -> float: """Calculates euclidean similarity. This function calculates euclidean similarity between points x and y in Euclidean n-space that based on euclidean distance between this points. Args: x, y: two points in Euclidean n-space. Returns: similarity between points x and y. """ return 1 / (1 + euclidean_distance(x, y)) def pearson_similarity(x: np.array, y: np.array) -> float: """Calculates Pearson correlation coefficient. This function calculates Pearson correlation coefficient for given 1-D data arrays x and y. Args: x, y: two 1-D data arrays with float values. Returns: Pearson correlation between x and y. """ x_b, y_b = x - x.mean(), y - y.mean() denominator = np.sqrt(np.sum(x_b ** 2) * np.sum(y_b ** 2)) if denominator == 0: return np.nan return np.sum(x_b * y_b) / denominator def recsys_euclidean_similarity(x: np.array, y: np.array) -> float: """Calculates euclidean similarity of two users/items. This function calculates users or items similarity based on euclidean similarity. The similarity between two users/items, that represented here as two 1-D arrays where each value is score for some item (from some user), is calculated only for those indices i for which there is score both for first and second user/item. It's assumed that zero values in arrays are equal to lack of score for some items (from some users). Args: x, y: two 1-D data arrays that represent user's/item's scores. Returns: euclidean similarity between two users/items x and y. """ x_new, y_new = x[(x != 0) & (y != 0)], y[(x != 0) & (y != 0)] if x_new.shape[0] == 0: return -np.inf return euclidean_similarity(x_new, y_new) def recsys_pearson_similarity(x: np.array, y: np.array) -> float: """Calculates pearson similarity of two users/items. This function calculates users or items similarity based on pearson similarity. The similarity between two users/items, that represented here as two 1-D arrays where each value is score for some item (from some user), is calculated only for those indices i for which there is score both for first and second user/item. It's assumed that zero values in arrays are equal to lack of score for some items (from some users). Args: x, y: two 1-D data arrays that represent user's/item's scores. Returns: pearson similarity between two users\items x and y. """ x_new, y_new = x[(x != 0) & (y != 0)], y[(x != 0) & (y != 0)] if x_new.shape[0] == 0: return -np.inf return pearson_similarity(x_new, y_new) def apk(actual: np.array, predicted: np.array, k: int=10) -> float: """Calculates the average precision at k. This function calculates the average precision at k for given predicted elements by actual elements. Args: actual: array of relevant elements in any order. predicted: array of predicted elements that are sorted by relevance in descending order. k: number of predicted elements. Returns: The average precision at k over the input lists. """ if len(predicted) < k: k = len(predicted) precision_at_k = np.array([np.in1d(predicted[:i], actual).sum() / i for i in range(1, k+1)]) rel = np.array([1 if p in actual else 0 for p in predicted[:k]]) return (precision_at_k * rel).mean() def mapk(actual: np.array, predicted: np.array, k: int=10) -> float: """Calculates the mean average precision at k. This function calculates the mean average precision at k for given predicted elements for multiple users by actual elements. Args: actual: 2-D array of relevant elements. predicted: 2-D array of predicted elements. k: number of predicted elements. Returns: The mean average precision at k over the input arrays. """ sum = 0 U = len(predicted) for i in range(U): sum += apk(actual[i], predicted[i], k) return sum / U
[ "numpy.array", "numpy.sum", "numpy.in1d" ]
[((3905, 3965), 'numpy.array', 'np.array', (['[(1 if p in actual else 0) for p in predicted[:k]]'], {}), '([(1 if p in actual else 0) for p in predicted[:k]])\n', (3913, 3965), True, 'import numpy as np\n'), ((381, 401), 'numpy.sum', 'np.sum', (['((x - y) ** 2)'], {}), '((x - y) ** 2)\n', (387, 401), True, 'import numpy as np\n'), ((1354, 1371), 'numpy.sum', 'np.sum', (['(x_b * y_b)'], {}), '(x_b * y_b)\n', (1360, 1371), True, 'import numpy as np\n'), ((1257, 1273), 'numpy.sum', 'np.sum', (['(x_b ** 2)'], {}), '(x_b ** 2)\n', (1263, 1273), True, 'import numpy as np\n'), ((1276, 1292), 'numpy.sum', 'np.sum', (['(y_b ** 2)'], {}), '(y_b ** 2)\n', (1282, 1292), True, 'import numpy as np\n'), ((3829, 3859), 'numpy.in1d', 'np.in1d', (['predicted[:i]', 'actual'], {}), '(predicted[:i], actual)\n', (3836, 3859), True, 'import numpy as np\n')]
#!/usr/bin/env python3 # dcfac0e3-1ade-11e8-9de3-00505601122b # 7d179d73-3e93-11e9-b0fd-00505601122b import argparse import sys import matplotlib.pyplot as plt import numpy as np import sklearn.datasets import sklearn.metrics import sklearn.model_selection if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument( "--C", default=1, type=float, help="Inverse regularization strenth" ) parser.add_argument("--examples", default=200, type=int, help="Number of examples") parser.add_argument( "--kernel", default="rbf", type=str, help="Kernel type [poly|rbf]" ) parser.add_argument( "--kernel_degree", default=5, type=int, help="Degree for poly kernel" ) parser.add_argument( "--kernel_gamma", default=1.0, type=float, help="Gamma for poly and rbf kernel" ) parser.add_argument( "--num_passes", default=10, type=int, help="Number of passes without changes to stop after", ) parser.add_argument( "--plot", default=False, action="store_true", help="Plot progress" ) parser.add_argument("--seed", default=42, type=int, help="Random seed") parser.add_argument( "--test_ratio", default=0.5, type=float, help="Test set size ratio" ) parser.add_argument( "--tolerance", default=1e-4, type=float, help="Default tolerance for KKT conditions", ) args = parser.parse_args() # Set random seed np.random.seed(args.seed) # Generate an artifical regression dataset, with +-1 as targets data, target = sklearn.datasets.make_classification( n_samples=args.examples, n_features=2, n_informative=2, n_redundant=0, random_state=args.seed, ) target = 2 * target - 1 # Split the data randomly to train and test using `sklearn.model_selection.train_test_split`, # with `test_size=args.test_ratio` and `random_state=args.seed`. train_data, test_data, train_target, test_target = sklearn.model_selection.train_test_split( data, target, stratify=target, test_size=args.test_ratio, random_state=args.seed ) # We consider the following kernels: # - linear: K(x, y) = x^T y # - poly: K(x, y; degree, gamma) = (gamma * x^T y + 1) ^ degree # - rbf: K(x, y; gamma) = exp^{- gamma * ||x - y||^2} def kernel(x, y): if args.kernel == "linear": return x @ y if args.kernel == "poly": return (args.kernel_gamma * x @ y + 1) ** args.kernel_degree if args.kernel == "rbf": return np.exp(-args.kernel_gamma * ((x - y) @ (x - y))) def calc_b(X, y, w): b_tmp = y - np.dot(w.T, X.T) return np.mean(b_tmp) def calc_w(alpha, y, X): return np.dot(X.T, np.multiply(alpha, y)) def clip(a, H, L): if a > H: return H if L > a: return L return a def predict(a, b, train_data, train_target, x): return ( sum( a[i] * train_target[i] * kernel(train_data[i], x) for i in range(len(a)) ) + b ) # Create initial weights a, b = np.zeros(len(train_data)), 0 j_generator = np.random.RandomState(args.seed) passes = 0 while passes < args.num_passes: a_changed = 0 for i in range(len(a)): pred_i = predict(a, b, train_data, train_target, train_data[i, :]) Ei = pred_i - train_target[i] cond_1 = (a[i] < args.C) and (train_target[i] * Ei < -args.tolerance) cond_2 = (a[i] > 0) and (train_target[i] * Ei > args.tolerance) if cond_1 or cond_2: j = j_generator.randint(len(a) - 1) j = j + (j >= i) pred_j = predict(a, b, train_data, train_target, train_data[j, :]) Ej = pred_j - train_target[j] second_derivative_j = ( 2 * kernel(train_data[i,], train_data[j,]) - kernel(train_data[i,], train_data[i,]) - kernel(train_data[j,], train_data[j,]) ) a_j_new = a[j] - train_target[j] * ((Ei - Ej) / (second_derivative_j)) if second_derivative_j >= -args.tolerance: continue if train_target[i] == train_target[j]: L = np.maximum(0, a[i] + a[j] - args.C) H = np.minimum(args.C, a[i] + a[j]) else: L = np.maximum(0, a[j] - a[i]) H = np.minimum(args.C, args.C + a[j] - a[i]) if (H - L) < args.tolerance: continue # nothing a_j_new = clip(a_j_new, H, L) if np.abs(a_j_new - a[j]) < args.tolerance: continue a_i_new = a[i] - train_target[i] * train_target[j] * (a_j_new - a[j]) b_j = ( b - Ej - train_target[i] * (a_i_new - a[i]) * kernel(train_data[i,], train_data[j,]) - train_target[j] * (a_j_new - a[j]) * kernel(train_data[j,], train_data[j,]) ) b_i = ( b - Ei - train_target[i] * (a_i_new - a[i]) * kernel(train_data[i,], train_data[i,]) - train_target[j] * (a_j_new - a[j]) * kernel(train_data[j,], train_data[i,]) ) a[j] = a_j_new a[i] = a_i_new # - increase a_changed if 0 < a[i] < args.C: b = b_i elif 0 < a[j] < args.C: b = b_j else: b = (b_i + b_j) / 2 a_changed = a_changed + 1 passes = 0 if a_changed else passes + 1 pred_train = np.sign( [ predict(a, b, train_data, train_target, train_data[o, :]) for o in range(train_data.shape[0]) ] ) pred_test = np.sign( [ predict(a, b, train_data, train_target, test_data[o, :]) for o in range(test_data.shape[0]) ] ) train_accuracy = np.mean(pred_train == train_target) test_accuracy = np.mean(pred_test == test_target) # TODO: After each iteration, measure the accuracy for both the # train test and the test set and print it in percentages. print( "Train acc {:.1f}%, test acc {:.1f}%".format( 100 * train_accuracy, 100 * test_accuracy ) ) if args.plot: def predict_simple(x): return ( sum( a[i] * train_target[i] * kernel(train_data[i], x) for i in range(len(a)) ) + b ) xs = np.linspace(np.min(data[:, 0]), np.max(data[:, 0]), 50) ys = np.linspace(np.min(data[:, 1]), np.max(data[:, 1]), 50) predictions = [[predict_simple(np.array([x, y])) for x in xs] for y in ys] plt.contourf(xs, ys, predictions, levels=0, cmap=plt.cm.RdBu) plt.contour(xs, ys, predictions, levels=[-1, 0, 1], colors="k", zorder=1) plt.scatter( train_data[:, 0], train_data[:, 1], c=train_target, marker="o", label="Train", cmap=plt.cm.RdBu, zorder=2, ) plt.scatter( train_data[a > args.tolerance, 0], train_data[a > args.tolerance, 1], marker="o", s=90, label="Support Vectors", c="#00dd00", ) plt.scatter( test_data[:, 0], test_data[:, 1], c=test_target, marker="*", label="Test", cmap=plt.cm.RdBu, zorder=2, ) plt.legend(loc="upper center", ncol=3) plt.show()
[ "numpy.minimum", "numpy.random.seed", "argparse.ArgumentParser", "matplotlib.pyplot.show", "numpy.multiply", "numpy.maximum", "matplotlib.pyplot.scatter", "matplotlib.pyplot.legend", "numpy.abs", "numpy.random.RandomState", "numpy.min", "numpy.mean", "matplotlib.pyplot.contourf", "matplotl...
[((299, 324), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (322, 324), False, 'import argparse\n'), ((1506, 1531), 'numpy.random.seed', 'np.random.seed', (['args.seed'], {}), '(args.seed)\n', (1520, 1531), True, 'import numpy as np\n'), ((3274, 3306), 'numpy.random.RandomState', 'np.random.RandomState', (['args.seed'], {}), '(args.seed)\n', (3295, 3306), True, 'import numpy as np\n'), ((2756, 2770), 'numpy.mean', 'np.mean', (['b_tmp'], {}), '(b_tmp)\n', (2763, 2770), True, 'import numpy as np\n'), ((6533, 6568), 'numpy.mean', 'np.mean', (['(pred_train == train_target)'], {}), '(pred_train == train_target)\n', (6540, 6568), True, 'import numpy as np\n'), ((6593, 6626), 'numpy.mean', 'np.mean', (['(pred_test == test_target)'], {}), '(pred_test == test_target)\n', (6600, 6626), True, 'import numpy as np\n'), ((7409, 7470), 'matplotlib.pyplot.contourf', 'plt.contourf', (['xs', 'ys', 'predictions'], {'levels': '(0)', 'cmap': 'plt.cm.RdBu'}), '(xs, ys, predictions, levels=0, cmap=plt.cm.RdBu)\n', (7421, 7470), True, 'import matplotlib.pyplot as plt\n'), ((7479, 7552), 'matplotlib.pyplot.contour', 'plt.contour', (['xs', 'ys', 'predictions'], {'levels': '[-1, 0, 1]', 'colors': '"""k"""', 'zorder': '(1)'}), "(xs, ys, predictions, levels=[-1, 0, 1], colors='k', zorder=1)\n", (7490, 7552), True, 'import matplotlib.pyplot as plt\n'), ((7561, 7683), 'matplotlib.pyplot.scatter', 'plt.scatter', (['train_data[:, 0]', 'train_data[:, 1]'], {'c': 'train_target', 'marker': '"""o"""', 'label': '"""Train"""', 'cmap': 'plt.cm.RdBu', 'zorder': '(2)'}), "(train_data[:, 0], train_data[:, 1], c=train_target, marker='o',\n label='Train', cmap=plt.cm.RdBu, zorder=2)\n", (7572, 7683), True, 'import matplotlib.pyplot as plt\n'), ((7783, 7925), 'matplotlib.pyplot.scatter', 'plt.scatter', (['train_data[a > args.tolerance, 0]', 'train_data[a > args.tolerance, 1]'], {'marker': '"""o"""', 's': '(90)', 'label': '"""Support Vectors"""', 'c': '"""#00dd00"""'}), "(train_data[a > args.tolerance, 0], train_data[a > args.\n tolerance, 1], marker='o', s=90, label='Support Vectors', c='#00dd00')\n", (7794, 7925), True, 'import matplotlib.pyplot as plt\n'), ((8012, 8130), 'matplotlib.pyplot.scatter', 'plt.scatter', (['test_data[:, 0]', 'test_data[:, 1]'], {'c': 'test_target', 'marker': '"""*"""', 'label': '"""Test"""', 'cmap': 'plt.cm.RdBu', 'zorder': '(2)'}), "(test_data[:, 0], test_data[:, 1], c=test_target, marker='*',\n label='Test', cmap=plt.cm.RdBu, zorder=2)\n", (8023, 8130), True, 'import matplotlib.pyplot as plt\n'), ((8230, 8268), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""upper center"""', 'ncol': '(3)'}), "(loc='upper center', ncol=3)\n", (8240, 8268), True, 'import matplotlib.pyplot as plt\n'), ((8277, 8287), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (8285, 8287), True, 'import matplotlib.pyplot as plt\n'), ((2629, 2677), 'numpy.exp', 'np.exp', (['(-args.kernel_gamma * ((x - y) @ (x - y)))'], {}), '(-args.kernel_gamma * ((x - y) @ (x - y)))\n', (2635, 2677), True, 'import numpy as np\n'), ((2724, 2740), 'numpy.dot', 'np.dot', (['w.T', 'X.T'], {}), '(w.T, X.T)\n', (2730, 2740), True, 'import numpy as np\n'), ((2828, 2849), 'numpy.multiply', 'np.multiply', (['alpha', 'y'], {}), '(alpha, y)\n', (2839, 2849), True, 'import numpy as np\n'), ((7205, 7223), 'numpy.min', 'np.min', (['data[:, 0]'], {}), '(data[:, 0])\n', (7211, 7223), True, 'import numpy as np\n'), ((7225, 7243), 'numpy.max', 'np.max', (['data[:, 0]'], {}), '(data[:, 0])\n', (7231, 7243), True, 'import numpy as np\n'), ((7274, 7292), 'numpy.min', 'np.min', (['data[:, 1]'], {}), '(data[:, 1])\n', (7280, 7292), True, 'import numpy as np\n'), ((7294, 7312), 'numpy.max', 'np.max', (['data[:, 1]'], {}), '(data[:, 1])\n', (7300, 7312), True, 'import numpy as np\n'), ((4441, 4476), 'numpy.maximum', 'np.maximum', (['(0)', '(a[i] + a[j] - args.C)'], {}), '(0, a[i] + a[j] - args.C)\n', (4451, 4476), True, 'import numpy as np\n'), ((4501, 4532), 'numpy.minimum', 'np.minimum', (['args.C', '(a[i] + a[j])'], {}), '(args.C, a[i] + a[j])\n', (4511, 4532), True, 'import numpy as np\n'), ((4579, 4605), 'numpy.maximum', 'np.maximum', (['(0)', '(a[j] - a[i])'], {}), '(0, a[j] - a[i])\n', (4589, 4605), True, 'import numpy as np\n'), ((4630, 4670), 'numpy.minimum', 'np.minimum', (['args.C', '(args.C + a[j] - a[i])'], {}), '(args.C, args.C + a[j] - a[i])\n', (4640, 4670), True, 'import numpy as np\n'), ((4842, 4864), 'numpy.abs', 'np.abs', (['(a_j_new - a[j])'], {}), '(a_j_new - a[j])\n', (4848, 4864), True, 'import numpy as np\n'), ((7357, 7373), 'numpy.array', 'np.array', (['[x, y]'], {}), '([x, y])\n', (7365, 7373), True, 'import numpy as np\n')]
#!/bin/env python3 # -*- coding: utf8 -*- import math import click import numpy as np import tensorflow as tf import torch from model import build_graph from torch import nn from torchvision import transforms from torchvision.datasets import cifar from utensor_cgen.utils import prepare_meta_graph def one_hot(labels, n_class=10): return np.eye(n_class)[labels] @click.command() @click.help_option("-h", "--help") @click.option( "--batch-size", default=50, show_default=True, help="the image batch size", type=int ) @click.option( "--lr", default=0.9, show_default=True, help="the learning rate of the optimizer", type=float, ) @click.option( "--epochs", default=10, show_default=True, help="the number of epochs", type=int ) @click.option( "--keep-prob", default=0.9, show_default=True, help="the dropout layer keep probability", type=float, ) @click.option( "--chkp-dir", default="chkp/cifar_cnn", show_default=True, help="directory where to save check point files", ) @click.option( "--output-pb", help="output model file name", default="cifar10_cnn.pb", show_default=True, ) def train(batch_size, lr, epochs, keep_prob, chkp_dir, output_pb): click.echo( click.style( "lr: {}, keep_prob: {}, output pbfile: {}".format(lr, keep_prob, output_pb), fg="cyan", bold=True, ) ) cifar10_train = cifar.CIFAR10("./cifar10_data", download=True, train=True) cifar10_test = cifar.CIFAR10("./cifar10_data", download=True, train=False) mean = ( (cifar10_train.train_data.astype("float32") / 255.0) .mean(axis=(0, 1, 2)) .tolist() ) std = ( (cifar10_train.train_data.astype("float32") / 255.0) .std(axis=(1, 2)) .mean(axis=0) .tolist() ) cifar10_train.transform = transforms.Compose( [ transforms.RandomHorizontalFlip(), transforms.RandomAffine(degrees=0, translate=(0.1, 0.1)), transforms.ToTensor(), transforms.Normalize(mean, std), ] ) cifar10_test.transform = transforms.Compose( [transforms.ToTensor(), transforms.Normalize(mean, std)] ) train_loader = torch.utils.data.DataLoader( cifar10_train, batch_size=batch_size, shuffle=True, num_workers=2 ) eval_loader = torch.utils.data.DataLoader( cifar10_test, batch_size=len(cifar10_test), shuffle=False, num_workers=2 ) graph = tf.Graph() with graph.as_default(): tf_image_batch = tf.placeholder(tf.float32, shape=[None, 32, 32, 3]) tf_labels = tf.placeholder(tf.float32, shape=[None, 10]) tf_keep_prob = tf.placeholder(tf.float32, name="keep_prob") tf_pred, train_op, tf_total_loss, saver = build_graph( tf_image_batch, tf_labels, tf_keep_prob, lr=lr ) best_acc = 0.0 chkp_cnt = 0 with tf.Session(graph=graph) as sess: tf.global_variables_initializer().run() for epoch in range(1, epochs + 1): for i, (img_batch, label_batch) in enumerate(train_loader, 1): np_img_batch = img_batch.numpy().transpose((0, 2, 3, 1)) np_label_batch = label_batch.numpy() _ = sess.run( train_op, feed_dict={ tf_image_batch: np_img_batch, tf_labels: one_hot(np_label_batch), tf_keep_prob: keep_prob, }, ) if (i % 100) == 0: img_batch, label_batch = next(iter(eval_loader)) np_img_batch = img_batch.numpy().transpose((0, 2, 3, 1)) np_label_batch = label_batch.numpy() pred_label = sess.run( tf_pred, feed_dict={tf_image_batch: np_img_batch, tf_keep_prob: 1.0}, ) acc = (pred_label == np_label_batch).sum() / np_label_batch.shape[0] click.echo( click.style( "[epoch {}: {}], accuracy {:0.2f}%".format( epoch, i, acc * 100 ), fg="yellow", bold=True, ) ) if acc >= best_acc: best_acc = acc chkp_cnt += 1 click.echo( click.style( "[epoch {}: {}] saving checkpoint, {} with acc {:0.2f}%".format( epoch, i, chkp_cnt, best_acc * 100 ), fg="white", bold=True, ) ) best_chkp = saver.save(sess, chkp_dir, global_step=chkp_cnt) best_graph_def = prepare_meta_graph( "{}.meta".format(best_chkp), output_nodes=[tf_pred.op.name] ) with open(output_pb, "wb") as fid: fid.write(best_graph_def.SerializeToString()) click.echo(click.style("{} saved".format(output_pb), fg="blue", bold=True)) if __name__ == "__main__": train()
[ "click.help_option", "torchvision.transforms.RandomAffine", "torch.utils.data.DataLoader", "torchvision.transforms.RandomHorizontalFlip", "model.build_graph", "tensorflow.global_variables_initializer", "click.option", "tensorflow.Session", "click.command", "tensorflow.placeholder", "torchvision....
[((373, 388), 'click.command', 'click.command', ([], {}), '()\n', (386, 388), False, 'import click\n'), ((390, 423), 'click.help_option', 'click.help_option', (['"""-h"""', '"""--help"""'], {}), "('-h', '--help')\n", (407, 423), False, 'import click\n'), ((425, 528), 'click.option', 'click.option', (['"""--batch-size"""'], {'default': '(50)', 'show_default': '(True)', 'help': '"""the image batch size"""', 'type': 'int'}), "('--batch-size', default=50, show_default=True, help=\n 'the image batch size', type=int)\n", (437, 528), False, 'import click\n'), ((531, 643), 'click.option', 'click.option', (['"""--lr"""'], {'default': '(0.9)', 'show_default': '(True)', 'help': '"""the learning rate of the optimizer"""', 'type': 'float'}), "('--lr', default=0.9, show_default=True, help=\n 'the learning rate of the optimizer', type=float)\n", (543, 643), False, 'import click\n'), ((663, 762), 'click.option', 'click.option', (['"""--epochs"""'], {'default': '(10)', 'show_default': '(True)', 'help': '"""the number of epochs"""', 'type': 'int'}), "('--epochs', default=10, show_default=True, help=\n 'the number of epochs', type=int)\n", (675, 762), False, 'import click\n'), ((765, 884), 'click.option', 'click.option', (['"""--keep-prob"""'], {'default': '(0.9)', 'show_default': '(True)', 'help': '"""the dropout layer keep probability"""', 'type': 'float'}), "('--keep-prob', default=0.9, show_default=True, help=\n 'the dropout layer keep probability', type=float)\n", (777, 884), False, 'import click\n'), ((904, 1029), 'click.option', 'click.option', (['"""--chkp-dir"""'], {'default': '"""chkp/cifar_cnn"""', 'show_default': '(True)', 'help': '"""directory where to save check point files"""'}), "('--chkp-dir', default='chkp/cifar_cnn', show_default=True,\n help='directory where to save check point files')\n", (916, 1029), False, 'import click\n'), ((1046, 1154), 'click.option', 'click.option', (['"""--output-pb"""'], {'help': '"""output model file name"""', 'default': '"""cifar10_cnn.pb"""', 'show_default': '(True)'}), "('--output-pb', help='output model file name', default=\n 'cifar10_cnn.pb', show_default=True)\n", (1058, 1154), False, 'import click\n'), ((1444, 1502), 'torchvision.datasets.cifar.CIFAR10', 'cifar.CIFAR10', (['"""./cifar10_data"""'], {'download': '(True)', 'train': '(True)'}), "('./cifar10_data', download=True, train=True)\n", (1457, 1502), False, 'from torchvision.datasets import cifar\n'), ((1522, 1581), 'torchvision.datasets.cifar.CIFAR10', 'cifar.CIFAR10', (['"""./cifar10_data"""'], {'download': '(True)', 'train': '(False)'}), "('./cifar10_data', download=True, train=False)\n", (1535, 1581), False, 'from torchvision.datasets import cifar\n'), ((2267, 2366), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['cifar10_train'], {'batch_size': 'batch_size', 'shuffle': '(True)', 'num_workers': '(2)'}), '(cifar10_train, batch_size=batch_size, shuffle=\n True, num_workers=2)\n', (2294, 2366), False, 'import torch\n'), ((2522, 2532), 'tensorflow.Graph', 'tf.Graph', ([], {}), '()\n', (2530, 2532), True, 'import tensorflow as tf\n'), ((346, 361), 'numpy.eye', 'np.eye', (['n_class'], {}), '(n_class)\n', (352, 361), True, 'import numpy as np\n'), ((2587, 2638), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '[None, 32, 32, 3]'}), '(tf.float32, shape=[None, 32, 32, 3])\n', (2601, 2638), True, 'import tensorflow as tf\n'), ((2659, 2703), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '[None, 10]'}), '(tf.float32, shape=[None, 10])\n', (2673, 2703), True, 'import tensorflow as tf\n'), ((2727, 2771), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'name': '"""keep_prob"""'}), "(tf.float32, name='keep_prob')\n", (2741, 2771), True, 'import tensorflow as tf\n'), ((2822, 2881), 'model.build_graph', 'build_graph', (['tf_image_batch', 'tf_labels', 'tf_keep_prob'], {'lr': 'lr'}), '(tf_image_batch, tf_labels, tf_keep_prob, lr=lr)\n', (2833, 2881), False, 'from model import build_graph\n'), ((2949, 2972), 'tensorflow.Session', 'tf.Session', ([], {'graph': 'graph'}), '(graph=graph)\n', (2959, 2972), True, 'import tensorflow as tf\n'), ((1927, 1960), 'torchvision.transforms.RandomHorizontalFlip', 'transforms.RandomHorizontalFlip', ([], {}), '()\n', (1958, 1960), False, 'from torchvision import transforms\n'), ((1974, 2030), 'torchvision.transforms.RandomAffine', 'transforms.RandomAffine', ([], {'degrees': '(0)', 'translate': '(0.1, 0.1)'}), '(degrees=0, translate=(0.1, 0.1))\n', (1997, 2030), False, 'from torchvision import transforms\n'), ((2044, 2065), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (2063, 2065), False, 'from torchvision import transforms\n'), ((2079, 2110), 'torchvision.transforms.Normalize', 'transforms.Normalize', (['mean', 'std'], {}), '(mean, std)\n', (2099, 2110), False, 'from torchvision import transforms\n'), ((2186, 2207), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (2205, 2207), False, 'from torchvision import transforms\n'), ((2209, 2240), 'torchvision.transforms.Normalize', 'transforms.Normalize', (['mean', 'std'], {}), '(mean, std)\n', (2229, 2240), False, 'from torchvision import transforms\n'), ((2990, 3023), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (3021, 3023), True, 'import tensorflow as tf\n')]
""" .. currentmodule:: pylayers.antprop.diffRT .. autosummary:: :members: """ from __future__ import print_function import doctest import os import glob #!/usr/bin/python # -*- coding: latin1 -*- import numpy as np import scipy.special as sps import matplotlib.pyplot as plt import pdb def diff(fGHz,phi0,phi,si,sd,N,mat0,matN,beta=np.pi/2,mode='tab',debug=False): """ Luebbers Diffration coefficient for Ray tracing Parameters ---------- Nf : number of frequencies Nr : number of rays fGHz : np.array (Nf) phi0 : np.array (Nr) phi : np.array (Nr) si : np.array (Nr) sd : np.array (Nr) N: np.array (Nb) mat0 : Mat matN : Mat beta : np.array (Nb) skew incidence angle (rad) mode : str ( 'tab','exact') if 'tab': the Fresnel function is interpolated ( increase speed) if 'exact': the Fresnel function is computed for each values ( increase accuracy) (see FreF) Returns ------- Ds : numpy array Diffraction soft Dh : numpy array Diffraction hard Examples -------- .. plot:: :include-source: >>> import numpy as np >>> from pylayers.antprop.slab import * >>> Nf=3 >>> Nr=10 >>> Nb=5 >>> fGHz = np.linspace(0,10,Nf) >>> N = np.linspace(1,10,Nb)#320/180. >>> phi0 = np.linspace(0.01,2*np.pi-0.01,Nr)#40*np.pi/180. >>> phi = np.linspace(0.01,2*np.pi-0.01,Nr) >>> dm = MatDB() >>> mat0 = dm['METAL'] >>> matN = dm['METAL'] >>> si = 10000.*np.ones(Nr) >>> sd = 1.*np.ones(Nr) >>> plt.ion() >>> Ds,Dh,D1,D2,D3,D4 = diff(fGHz,phi0,phi,si,sd,N,mat0,matN) """ if not isinstance(fGHz,np.ndarray): fGHz = np.array([fGHz]) if not isinstance(phi0,np.ndarray): phi0 = np.array([phi0]) if not isinstance(phi,np.ndarray): phi = np.array([phi]) if not isinstance(si,np.ndarray): si = np.array([si]) if not isinstance(sd,np.ndarray): sd = np.array([sd]) if not isinstance(N,np.ndarray): N = np.array([N]) if not isinstance(beta,np.ndarray): beta = np.array([beta]) fGHz = fGHz[:,None] phi0 = phi0[None,:] phi = phi[None,:] si = si[None,:] sd = sd[None,:] N = N[None,:] beta = beta[None,:] L = si*sd/(si+sd) k = 2*np.pi*fGHz/0.3 #-------------------------------------------------- # R on faces 'o' and 'n' #-------------------------------------------------- tho = np.empty((fGHz.shape[0],phi.shape[1])) thn = np.empty((fGHz.shape[0],phi.shape[1])) # PHI0 = phi0 * np.ones(phi.shape) # PHI = np.ones(phi0.shape)*phi # BN = np.ones(phi0.shape)*N c1 = phi>phi0 c2 = ~c1 tho[:,c1[0,:]] = phi0[:,c1[0,:]] thn[:,c1[0,:]] = N[:,c1[0,:]]*np.pi-phi[:,c1[0,:]] tho[:,c2[0,:]] = phi[:,c2[0,:]] thn[:,c2[0,:]] = N[:,c2[0,:]]*np.pi-phi0[:,c2[0,:]] er0 = np.real(mat0['epr']) err0 = np.imag(mat0['epr']) ur0 = np.real(mat0['mur']) urr0 = np.imag(mat0['mur']) sigma0 = mat0['sigma'] deltah0 = mat0['roughness'] erN = np.real(matN['epr']) errN = np.imag(matN['epr']) urN = np.real(mat0['mur']) urrN = np.imag(mat0['mur']) sigmaN = matN['sigma'] deltahN = matN['roughness'] Rsofto,Rhardo = R(tho,k,er0,err0,sigma0,ur0,urr0,deltah0) Rsoftn,Rhardn = R(thn,k,erN,errN,sigmaN,urN,urrN,deltahN) #-------------------------------------------------- # grazing angle Go et Gn #-------------------------------------------------- Gsofto,Gsoftn = G(N,phi0,Rsofto,Rsoftn) Ghardo,Ghardn = G(N,phi0,Rhardo,Rhardn) #-------------------------------------------------- #calcul des 4 termes du coeff diff #-------------------------------------------------- #by construction #0 < KLA < 2*k*L klamax = 2*np.max(k)*np.max(L) if mode == 'tab': #xF0 = np.logspace(-6,-2,1000) #xF1 = np.logspace(-2,np.log10(klamax),1000) #xF = np.hstack((xF0,xF1)) #pdb.set_trace() # xF = np.logspace(-6,np.log10(klamax),1000) xF = np.linspace(-8,np.log10(klamax),2000) pxF = 10**xF F = FreF(pxF)[0] else : xF = [] F=[] sign = 1.0 D1 = Dfunc(sign,k,N,phi-phi0,si,sd,xF,F,beta) sign = -1.0 D2 = Dfunc(sign,k,N,phi-phi0,si,sd,xF,F,beta) sign = +1.0 D3 = Dfunc(sign,k,N,phi+phi0,si,sd,xF,F,beta) sign = -1.0 D4 = Dfunc(sign,k,N,phi+phi0,si,sd,xF,F,beta) #-------------------------------------- #n>=1 : exterior wedge #-------------------------------------- Dsoft =np.empty(np.shape(D1),dtype=complex) Dhard =np.empty(np.shape(D1),dtype=complex) #c1 = BN>=1.0 Dsoft = D1+D2+Rsoftn*D3+Rsofto*D4 Dhard = D1+D2+Rhardn*D3+Rhardo*D4 # Dsoft = D2-D4 # Dhard = D2+D4 #Dsoft = D1+D2-D3-D4 #Dhard = D1+D2+D3+D4 # Dsoft = Gsoftn*(D1+Rsoftn*D3)+Gsofto*(D2+Rsofto*D4) # Dhard = Ghardn*(D1+Rhardn*D3)+Ghardo*(D2+Rhardo*D4) # c1 = abs(Gsoftn+1.0) < 1e-6 # c2 = abs(Gsofto+1.0) < 1e-6 # c3 = abs(Ghardn+1.0) < 1e-6 # c4 = abs(Ghardo+1.0) < 1e-6 # # Dsoft[c1]= 0.5*(D1[c1]+D3[c1])+Gsofto[c1]*(D2[c1]+Rsofto[c1]*D4[c1]) # Dsoft[c2]= Gsoftn[c2]*(D1[c2]+Rsoftn[c2]*D3[c2])+0.5*(D2[c2]+D4[c2]) # Dhard[c3]= 0.5*(D1[c3]+D3[c3])+Ghardo[c3]*(D2[c3]+Rhardo[c3]*D4[c3]) # Dhard[c4]= Ghardn[c4]*(D1[c4]+Rhardn[c4]*D3[c4])+0.5*(D2[c4]+D4[c4]) #-------------------------------------- #traitement des cas ou Go (ou Gn) = -1 #-------------------------------------- # if (abs(Gsoftn+1.0) < 1e-6): # DTsoft = 0.5*(D1+D3)+Gsofto*(D2+Rsofto*D4) # # if (abs(Gsofto+1.0)<1e-6): # DTsoft = Gsoftn*(D1+Rsoftn*D3)+0.5*(D2+D4) # # if (abs(Ghardn+1.0) < 1.0e-6): # DThard = 0.5*(D1+D3)+Ghardo*(D2+Rhardo*D4) # # if (abs(Ghardo+1.0)<1e-6): # DThard = Ghardn*(D1+Rhardn*D3)+0.5*(D2+D4) # ##-------------------------------------- ##cas ou n<1 : interior wedge ##-------------------------------------- # else: # # thoz = N*np.pi-tho # thnz = N*np.pi-thn # # # [Rsoftnz,Rhardnz] = R(thnz,k,ero,erro,condo,uro,deltaho) # [Rsoftoz,Rhardoz] = R(thoz,k,ern,errn,condn,urn,deltahn) # # DTsoft = Rsoftoz*Rsoftnz*D1+Rsoftn*D3+(Rsofto*Rsoftn*D2+Rsofto*D4) # # DThard = Rhardoz*Rhardnz*D1+Rhardn*D3+(Rhardo*Rhardn*D2+Rhardo*D4) if np.isnan(Dsoft).any(): u = np.isnan(Dsoft) pdb.set_trace() if np.isnan(Dhard).any(): v = np.where(Dhard==np.nan) pdb.set_trace() if debug: return Dsoft,Dhard,D1,D2,D3,D4 else : return Dsoft,Dhard#,D1,D2,D3,D4 def G(N,phi0,Ro,Rn): """ grazing angle correction Parameters ---------- N : wedge parameter phi0 : incidence angle (rad) Ro : R coefficient on face o Rn : R coefficient on face n Luebbers 89 "a heuristique UTD slope diffraction coefficient for rough lossy wedges" """ if not isinstance(phi0,np.ndarray): phi0 = np.array([phi0]) if not isinstance(N,np.ndarray): N = np.array([N]) PHI0 = phi0 * np.ones(Ro.shape) BN = N * np.ones(Ro.shape) # face o Go = np.ones(np.shape(Ro),dtype='complex') c1 = (abs(PHI0) < 1.0e-6) * (abs(Ro+1.0)>1.0e-6) c2 = (abs(PHI0) < 1.0e-6) * (abs(Ro+1.0)<1.0e-6) c3 = abs(PHI0-BN*np.pi) < 1.0e-6 Go[c1] = 1.0/(1.0+Ro[c1]) Go[c2] = -1. Go[c3] = 0.5 # face n Gn = np.ones(np.shape(Rn),dtype='complex') c1 = (abs(PHI0-BN*np.pi) < 1.0e-6) * (abs(Rn+1.0)>1.0e-6) c2 = (abs(PHI0-BN*np.pi) < 1.0e-6) * (abs(Rn+1.0)<1.0e-6) c3 = abs(PHI0) < 1.0e-6 Gn[c1] = 1.0/(1.0+Rn[c1]) Gn[c2] = -1. Gn[c3] = 0.5 return Go,Gn def Dfunc(sign,k,N,dphi,si,sd,xF=[],F=[],beta=np.pi/2): """ Parameters ---------- sign : int +1 | -1 k : wave number N : wedge parameter dphi : phi-phi0 or phi+phi0 si : distance source-D sd : distance D-observation beta : skew incidence angle xF : array support of Fresnel function. F : array Values of Fresnel function in regard of support if F =[], fresnel function is computed otherwise the passed interpolation F is used. Reference --------- [1] KOUYOUMJIAN-PATHAK a uniform geometrical theory of diffraction for an edge in a perfectly conducting surface" IEEE AP nov 74 vol 62 N11 Notes ----- e-jnp.pi/4 1 Di= ------------------ * ----------- * F(kla) ([1] eq 25) 2n*racine(2*np.pi*k) np.tan(dphi/n)sin(beta) """ cste = (1.0-1.0*1j)*(1.0/(4.0*N*np.sqrt(k*np.pi)*np.sin(beta))) rnn = (dphi+np.pi*sign)/(2.0*N*np.pi) nn = np.zeros(np.shape(rnn)) nn[rnn>0.5] = 1 nn[rnn>1.5] = 2 nn[rnn<-0.5] = -1 nn[rnn<-1.5] = -2 # KLA ref[1] eq 27 L = ((si*sd)*np.sin(beta)**2)/(1.*(si+sd)) AC = np.cos( (2.0*N*nn*np.pi-dphi) / 2.0 ) A = 2*AC**2 KLA = k * L * A epsi = AC*2.0 angle = (np.pi+sign*dphi)/(2.0*N) tan = np.tan(angle) Di = np.empty(KLA.shape) if len(F) == 0: Fkla,ys,yL = FreF(KLA) else : #pxF = 10**xF #uF = (np.abs(KLA[:,:]-pxF[:,None,None])).argmin(axis=0) val = np.maximum(np.log10(np.abs(KLA))-xF[0,None,None],0) uF2 = (len(F)-1)*(val)/(xF[-1,None,None]-xF[0,None,None]) uF2_int = np.floor(uF2).astype('int') Fkla = F[uF2_int] #if np.max(Fkla) > 1: # Warning('diffRT : Fkla tab probably wrong') # 4.56 Mac Namara try: Di = -cste*Fkla/tan except: print('tan=0 : It can happen') pdb.set_trace() c5 = np.where(np.abs(tan)<1e-9) BL = np.ones(Di.shape)*L Di[:,c5] = 0.5*np.sqrt(BL[c5]) # if np.isinf(Di).any(): # pdb.set_trace() return(Di) def FresnelI(x) : """ calculates Fresnel integral Parameters ---------- x : array real argument """ v = np.empty(x.shape,dtype=complex) y = np.abs(x) z = .25*y u1 = np.where(z>1) u2 = np.where(z<=1) y1 = y[u1] y2 = y[u2] d1 = np.cos(y1) d2 = np.cos(y2) e1 = np.sin(y1) e2 = np.sin(y2) z1 = z[u1] z2 = z[u2] c1 = np.sqrt(z1) c2 = np.sqrt(z2) # ---------------------------------------- # x>4, z>1 # ---------------------------------------- v1 = 0.5 - 0.5*1j c1 = (1.0)/c1 z1 = c1*c1 a1=(((((((((( .23393900e-3*z1 -.12179300e-2)*z1 +.21029670e-2)*z1 +.2464200e-3)*z1 -.67488730e-2)*z1 +.11948809e-1)*z1 -.9497136e-2)*z1 +.68989200e-3)*z1 +.57709560e-2)*z1 +.3936000e-5)*z1 -.24933975e-1)*z1*c1 b1=((((((((((( .838386000e-3*z1 -.55985150e-2)*z1 +.16497308e-1)*z1 -.27928955e-1)*z1 +.29064067e-1)*z1 -.17122914e-1)*z1 +.19032180e-2)*z1 +.48514660e-2)*z1 +.23006000e-4)*z1 -.93513410e-2)*z1 +.23000000e-7)*z1 +.19947114000)*c1 # ---------------------------------------- # x<4, z<1 # ---------------------------------------- a2=((((((((((( 0.34404779e-1 *z2 - 0.15023096)*z2 - 0.25639041e-1)*z2 +0.850663781 )*z2 - 0.75752419e-1 )*z2 - 0.305048566e1)*z2 -0.16898657e-1 )*z2 + 0.6920691902e1)*z2 - 0.576361e-3 )*z2 -0.6808568854e1)*z2 - 0.1702e-5)*z2 + 0.159576914e1)*c2 b2=((((((((((( .19547031e-1 *z2 -.216195929e0 )*z2 +.702222016e0)*z2 -.4033492760e0)*z2 -.1363729124e1)*z2 -.138341947e0)*z2 +.5075161298e1)*z2 -.952089500e-2)*z2 -.778002040e1)*z2 -.928100000e-4)*z2 +.4255387524e1)*z2 -.33000000e-7)*c2 w1 = a1*d1+b1*e1+ 1j*(b1*d1-a1*e1) + v1 w2 = a2*d2+b2*e2+ 1j*(b2*d2-a2*e2) v[u1] = w1 v[u2] = w2 y = v*(np.sqrt(np.pi/2.0)) return y def FreF(x) : """ F function from Pathack Parameters ---------- x : array real argument Examples -------- .. plot:: :include-source: >>> import matplotlib.pyplot as plt >>> import numpy as np >>> x = np.logspace(-4,2,400); >>> F = FreF(x) >>> plt.semilogx(x,,np.abs(F)) >>> plt.grid() """ ejp4 = np.exp(1j*np.pi/4) emjp4 = np.exp(-1j*np.pi/4) y = np.empty(x.shape,dtype=complex) u1 = np.where(x>10)[0] u2 = np.where(x<=10)[0] xu1 = x[u1] xu2 = x[u2] x2 = xu1*xu1 x3 = x2*xu1 x4 = x3*xu1 w1 = 1-0.75/x2+4.6875/x4 + 1j*( 0.5/xu1 -1.875/x3) cst = (1.0 - 1j )*0.5*np.sqrt(np.pi/2) carx = abs(xu2) racx = np.sqrt(carx) modx = np.mod(xu2,2*np.pi) expjx = np.exp(1j*modx) fr = FresnelI(carx) into = cst - fr w2 = 2.0*racx*1j*expjx*into y[u1] = w1 y[u2] = w2 # [1] eq 30 ys = (np.sqrt(np.pi*x)-2*x*ejp4-(2/3.)*x**2*emjp4)*np.exp(1j*(np.pi/4+x)) yl = 1-0.75/(x*x)+4.6875/(x*x*x*x) + 1j*( 0.5/x -1.875/(x*x*x)) return y,ys,yl def FreF2(x): """ F function using numpy fresnel function Parameters ---------- Not working for large argument """ y = np.empty(x.shape,dtype=complex) u1 = np.where(x>5)[0] u2 = np.where(x<=5)[0] xu1 = x[u1] xu2 = x[u2] x2 = xu1*xu1 x3 = x2*xu1 x4 = x3*xu1 w1 = 1-0.75/x2+4.6875/x4 + 1j*( 0.5/xu1 -1.875/x3) cst = np.sqrt(np.pi/2.) sF,cF = sps.fresnel(np.sqrt(xu2/cst)) Fc = (0.5-cF)*cst Fs = (0.5-sF)*cst modx = np.mod(xu2,2*np.pi) expjx = np.exp(1j*modx) w2 = 2*1j*np.sqrt(xu2)*expjx*(Fc-1j*Fs) y[u1] = w1 y[u2] = w2 return(y) def R(th,k,er,err,sigma,ur,urr,deltah): """ R coeff Parameters ---------- th : np.array incidence angle (axe 0) k : np.array wave number (axe 1) er : real part of permittivity err : imaginary part of permittivity sigma : conductivity ur : real part of permeability urr : imaginary part of permeability deltah : height standard deviation Examples -------- .. plot:: :include-source: >>> import numpy as np >>> th = np.linspace(0,np.pi/2,180)[None,:] >>> fGHz = 0.3 >>> lamda = 0.3/fGHz >>> k = np.array([2*np.pi/2])[:,None] >>> Rs,Rh = R(th,k,9,0,0.01,1,0,0) """ cel = 299792458 #-------------------------------------------- #cas des surfaces dielectriques (sinon er=-1) #-------------------------------------------- if (er >= 0.0 ): if ( (( ur-1.0)<1e-16) & ((er-1.0)<1e-16) ): Rs = np.zeros(len(th),dtype=complex) Rh = np.zeros(len(th),dtype=complex) u1 = np.where(th >= 1.5*np.pi) u2 = np.where(th >= np.pi ) u3 = np.where(th >= 0.5*np.pi) th[u1] = 2.0*np.pi - th[u1] th[u2] = th[u2] - np.pi th[u3] = np.pi - th[u3] #if (th >= 1.5*np.pi ): # th = 2.0*np.pi - th #elif (th >= np.pi ): # th = th - np.pi #elif (th >= 0.5*np.pi): # th = np.pi - th uo = 4.0*np.pi*1e-7 eo = 1.0/(uo*cel*cel) pulse = k*cel permi = (er-1j*err)-(1j*sigma)/(pulse*eo) perme = ur - 1j*urr yy = (permi/perme) st = np.sin(th) ct = np.cos(th) bb = np.sqrt(yy-ct**2) Rs = (st - bb) / (st + bb ) Rh = (yy*st-bb)/(yy*st+bb) else: # metalic case Rs = -np.ones(th.shape,dtype=complex) Rh = np.ones(th.shape,dtype=complex) roughness = 1.0 Rs = Rs* roughness Rh = Rh* roughness return Rs,Rh
[ "numpy.abs", "numpy.empty", "numpy.floor", "numpy.ones", "numpy.isnan", "numpy.shape", "numpy.imag", "numpy.sin", "numpy.exp", "numpy.max", "numpy.tan", "numpy.real", "numpy.log10", "numpy.mod", "numpy.cos", "numpy.where", "numpy.array", "pdb.set_trace", "numpy.sqrt" ]
[((2609, 2648), 'numpy.empty', 'np.empty', (['(fGHz.shape[0], phi.shape[1])'], {}), '((fGHz.shape[0], phi.shape[1]))\n', (2617, 2648), True, 'import numpy as np\n'), ((2659, 2698), 'numpy.empty', 'np.empty', (['(fGHz.shape[0], phi.shape[1])'], {}), '((fGHz.shape[0], phi.shape[1]))\n', (2667, 2698), True, 'import numpy as np\n'), ((3041, 3061), 'numpy.real', 'np.real', (["mat0['epr']"], {}), "(mat0['epr'])\n", (3048, 3061), True, 'import numpy as np\n'), ((3073, 3093), 'numpy.imag', 'np.imag', (["mat0['epr']"], {}), "(mat0['epr'])\n", (3080, 3093), True, 'import numpy as np\n'), ((3105, 3125), 'numpy.real', 'np.real', (["mat0['mur']"], {}), "(mat0['mur'])\n", (3112, 3125), True, 'import numpy as np\n'), ((3137, 3157), 'numpy.imag', 'np.imag', (["mat0['mur']"], {}), "(mat0['mur'])\n", (3144, 3157), True, 'import numpy as np\n'), ((3229, 3249), 'numpy.real', 'np.real', (["matN['epr']"], {}), "(matN['epr'])\n", (3236, 3249), True, 'import numpy as np\n'), ((3261, 3281), 'numpy.imag', 'np.imag', (["matN['epr']"], {}), "(matN['epr'])\n", (3268, 3281), True, 'import numpy as np\n'), ((3293, 3313), 'numpy.real', 'np.real', (["mat0['mur']"], {}), "(mat0['mur'])\n", (3300, 3313), True, 'import numpy as np\n'), ((3325, 3345), 'numpy.imag', 'np.imag', (["mat0['mur']"], {}), "(mat0['mur'])\n", (3332, 3345), True, 'import numpy as np\n'), ((9090, 9133), 'numpy.cos', 'np.cos', (['((2.0 * N * nn * np.pi - dphi) / 2.0)'], {}), '((2.0 * N * nn * np.pi - dphi) / 2.0)\n', (9096, 9133), True, 'import numpy as np\n'), ((9236, 9249), 'numpy.tan', 'np.tan', (['angle'], {}), '(angle)\n', (9242, 9249), True, 'import numpy as np\n'), ((9260, 9279), 'numpy.empty', 'np.empty', (['KLA.shape'], {}), '(KLA.shape)\n', (9268, 9279), True, 'import numpy as np\n'), ((10170, 10202), 'numpy.empty', 'np.empty', (['x.shape'], {'dtype': 'complex'}), '(x.shape, dtype=complex)\n', (10178, 10202), True, 'import numpy as np\n'), ((10211, 10220), 'numpy.abs', 'np.abs', (['x'], {}), '(x)\n', (10217, 10220), True, 'import numpy as np\n'), ((10246, 10261), 'numpy.where', 'np.where', (['(z > 1)'], {}), '(z > 1)\n', (10254, 10261), True, 'import numpy as np\n'), ((10269, 10285), 'numpy.where', 'np.where', (['(z <= 1)'], {}), '(z <= 1)\n', (10277, 10285), True, 'import numpy as np\n'), ((10326, 10336), 'numpy.cos', 'np.cos', (['y1'], {}), '(y1)\n', (10332, 10336), True, 'import numpy as np\n'), ((10347, 10357), 'numpy.cos', 'np.cos', (['y2'], {}), '(y2)\n', (10353, 10357), True, 'import numpy as np\n'), ((10369, 10379), 'numpy.sin', 'np.sin', (['y1'], {}), '(y1)\n', (10375, 10379), True, 'import numpy as np\n'), ((10390, 10400), 'numpy.sin', 'np.sin', (['y2'], {}), '(y2)\n', (10396, 10400), True, 'import numpy as np\n'), ((10445, 10456), 'numpy.sqrt', 'np.sqrt', (['z1'], {}), '(z1)\n', (10452, 10456), True, 'import numpy as np\n'), ((10467, 10478), 'numpy.sqrt', 'np.sqrt', (['z2'], {}), '(z2)\n', (10474, 10478), True, 'import numpy as np\n'), ((12366, 12390), 'numpy.exp', 'np.exp', (['(1.0j * np.pi / 4)'], {}), '(1.0j * np.pi / 4)\n', (12372, 12390), True, 'import numpy as np\n'), ((12397, 12422), 'numpy.exp', 'np.exp', (['(-1.0j * np.pi / 4)'], {}), '(-1.0j * np.pi / 4)\n', (12403, 12422), True, 'import numpy as np\n'), ((12429, 12461), 'numpy.empty', 'np.empty', (['x.shape'], {'dtype': 'complex'}), '(x.shape, dtype=complex)\n', (12437, 12461), True, 'import numpy as np\n'), ((12756, 12769), 'numpy.sqrt', 'np.sqrt', (['carx'], {}), '(carx)\n', (12763, 12769), True, 'import numpy as np\n'), ((12782, 12804), 'numpy.mod', 'np.mod', (['xu2', '(2 * np.pi)'], {}), '(xu2, 2 * np.pi)\n', (12788, 12804), True, 'import numpy as np\n'), ((12814, 12833), 'numpy.exp', 'np.exp', (['(1.0j * modx)'], {}), '(1.0j * modx)\n', (12820, 12833), True, 'import numpy as np\n'), ((13279, 13311), 'numpy.empty', 'np.empty', (['x.shape'], {'dtype': 'complex'}), '(x.shape, dtype=complex)\n', (13287, 13311), True, 'import numpy as np\n'), ((13534, 13554), 'numpy.sqrt', 'np.sqrt', (['(np.pi / 2.0)'], {}), '(np.pi / 2.0)\n', (13541, 13554), True, 'import numpy as np\n'), ((13656, 13678), 'numpy.mod', 'np.mod', (['xu2', '(2 * np.pi)'], {}), '(xu2, 2 * np.pi)\n', (13662, 13678), True, 'import numpy as np\n'), ((13688, 13707), 'numpy.exp', 'np.exp', (['(1.0j * modx)'], {}), '(1.0j * modx)\n', (13694, 13707), True, 'import numpy as np\n'), ((1817, 1833), 'numpy.array', 'np.array', (['[fGHz]'], {}), '([fGHz])\n', (1825, 1833), True, 'import numpy as np\n'), ((1889, 1905), 'numpy.array', 'np.array', (['[phi0]'], {}), '([phi0])\n', (1897, 1905), True, 'import numpy as np\n'), ((1959, 1974), 'numpy.array', 'np.array', (['[phi]'], {}), '([phi])\n', (1967, 1974), True, 'import numpy as np\n'), ((2026, 2040), 'numpy.array', 'np.array', (['[si]'], {}), '([si])\n', (2034, 2040), True, 'import numpy as np\n'), ((2092, 2106), 'numpy.array', 'np.array', (['[sd]'], {}), '([sd])\n', (2100, 2106), True, 'import numpy as np\n'), ((2156, 2169), 'numpy.array', 'np.array', (['[N]'], {}), '([N])\n', (2164, 2169), True, 'import numpy as np\n'), ((2225, 2241), 'numpy.array', 'np.array', (['[beta]'], {}), '([beta])\n', (2233, 2241), True, 'import numpy as np\n'), ((3958, 3967), 'numpy.max', 'np.max', (['L'], {}), '(L)\n', (3964, 3967), True, 'import numpy as np\n'), ((4748, 4760), 'numpy.shape', 'np.shape', (['D1'], {}), '(D1)\n', (4756, 4760), True, 'import numpy as np\n'), ((4796, 4808), 'numpy.shape', 'np.shape', (['D1'], {}), '(D1)\n', (4804, 4808), True, 'import numpy as np\n'), ((6571, 6586), 'numpy.isnan', 'np.isnan', (['Dsoft'], {}), '(Dsoft)\n', (6579, 6586), True, 'import numpy as np\n'), ((6595, 6610), 'pdb.set_trace', 'pdb.set_trace', ([], {}), '()\n', (6608, 6610), False, 'import pdb\n'), ((6653, 6678), 'numpy.where', 'np.where', (['(Dhard == np.nan)'], {}), '(Dhard == np.nan)\n', (6661, 6678), True, 'import numpy as np\n'), ((6685, 6700), 'pdb.set_trace', 'pdb.set_trace', ([], {}), '()\n', (6698, 6700), False, 'import pdb\n'), ((7187, 7203), 'numpy.array', 'np.array', (['[phi0]'], {}), '([phi0])\n', (7195, 7203), True, 'import numpy as np\n'), ((7253, 7266), 'numpy.array', 'np.array', (['[N]'], {}), '([N])\n', (7261, 7266), True, 'import numpy as np\n'), ((7286, 7303), 'numpy.ones', 'np.ones', (['Ro.shape'], {}), '(Ro.shape)\n', (7293, 7303), True, 'import numpy as np\n'), ((7319, 7336), 'numpy.ones', 'np.ones', (['Ro.shape'], {}), '(Ro.shape)\n', (7326, 7336), True, 'import numpy as np\n'), ((7365, 7377), 'numpy.shape', 'np.shape', (['Ro'], {}), '(Ro)\n', (7373, 7377), True, 'import numpy as np\n'), ((7631, 7643), 'numpy.shape', 'np.shape', (['Rn'], {}), '(Rn)\n', (7639, 7643), True, 'import numpy as np\n'), ((8910, 8923), 'numpy.shape', 'np.shape', (['rnn'], {}), '(rnn)\n', (8918, 8923), True, 'import numpy as np\n'), ((9901, 9918), 'numpy.ones', 'np.ones', (['Di.shape'], {}), '(Di.shape)\n', (9908, 9918), True, 'import numpy as np\n'), ((9940, 9955), 'numpy.sqrt', 'np.sqrt', (['BL[c5]'], {}), '(BL[c5])\n', (9947, 9955), True, 'import numpy as np\n'), ((11927, 11947), 'numpy.sqrt', 'np.sqrt', (['(np.pi / 2.0)'], {}), '(np.pi / 2.0)\n', (11934, 11947), True, 'import numpy as np\n'), ((12474, 12490), 'numpy.where', 'np.where', (['(x > 10)'], {}), '(x > 10)\n', (12482, 12490), True, 'import numpy as np\n'), ((12504, 12521), 'numpy.where', 'np.where', (['(x <= 10)'], {}), '(x <= 10)\n', (12512, 12521), True, 'import numpy as np\n'), ((12706, 12724), 'numpy.sqrt', 'np.sqrt', (['(np.pi / 2)'], {}), '(np.pi / 2)\n', (12713, 12724), True, 'import numpy as np\n'), ((13016, 13046), 'numpy.exp', 'np.exp', (['(1.0j * (np.pi / 4 + x))'], {}), '(1.0j * (np.pi / 4 + x))\n', (13022, 13046), True, 'import numpy as np\n'), ((13323, 13338), 'numpy.where', 'np.where', (['(x > 5)'], {}), '(x > 5)\n', (13331, 13338), True, 'import numpy as np\n'), ((13352, 13368), 'numpy.where', 'np.where', (['(x <= 5)'], {}), '(x <= 5)\n', (13360, 13368), True, 'import numpy as np\n'), ((13576, 13594), 'numpy.sqrt', 'np.sqrt', (['(xu2 / cst)'], {}), '(xu2 / cst)\n', (13583, 13594), True, 'import numpy as np\n'), ((14870, 14897), 'numpy.where', 'np.where', (['(th >= 1.5 * np.pi)'], {}), '(th >= 1.5 * np.pi)\n', (14878, 14897), True, 'import numpy as np\n'), ((14909, 14930), 'numpy.where', 'np.where', (['(th >= np.pi)'], {}), '(th >= np.pi)\n', (14917, 14930), True, 'import numpy as np\n'), ((14945, 14972), 'numpy.where', 'np.where', (['(th >= 0.5 * np.pi)'], {}), '(th >= 0.5 * np.pi)\n', (14953, 14972), True, 'import numpy as np\n'), ((15482, 15492), 'numpy.sin', 'np.sin', (['th'], {}), '(th)\n', (15488, 15492), True, 'import numpy as np\n'), ((15511, 15521), 'numpy.cos', 'np.cos', (['th'], {}), '(th)\n', (15517, 15521), True, 'import numpy as np\n'), ((15541, 15562), 'numpy.sqrt', 'np.sqrt', (['(yy - ct ** 2)'], {}), '(yy - ct ** 2)\n', (15548, 15562), True, 'import numpy as np\n'), ((15719, 15751), 'numpy.ones', 'np.ones', (['th.shape'], {'dtype': 'complex'}), '(th.shape, dtype=complex)\n', (15726, 15751), True, 'import numpy as np\n'), ((3948, 3957), 'numpy.max', 'np.max', (['k'], {}), '(k)\n', (3954, 3957), True, 'import numpy as np\n'), ((4224, 4240), 'numpy.log10', 'np.log10', (['klamax'], {}), '(klamax)\n', (4232, 4240), True, 'import numpy as np\n'), ((6536, 6551), 'numpy.isnan', 'np.isnan', (['Dsoft'], {}), '(Dsoft)\n', (6544, 6551), True, 'import numpy as np\n'), ((6618, 6633), 'numpy.isnan', 'np.isnan', (['Dhard'], {}), '(Dhard)\n', (6626, 6633), True, 'import numpy as np\n'), ((9839, 9854), 'pdb.set_trace', 'pdb.set_trace', ([], {}), '()\n', (9852, 9854), False, 'import pdb\n'), ((9874, 9885), 'numpy.abs', 'np.abs', (['tan'], {}), '(tan)\n', (9880, 9885), True, 'import numpy as np\n'), ((15673, 15705), 'numpy.ones', 'np.ones', (['th.shape'], {'dtype': 'complex'}), '(th.shape, dtype=complex)\n', (15680, 15705), True, 'import numpy as np\n'), ((8835, 8847), 'numpy.sin', 'np.sin', (['beta'], {}), '(beta)\n', (8841, 8847), True, 'import numpy as np\n'), ((9050, 9062), 'numpy.sin', 'np.sin', (['beta'], {}), '(beta)\n', (9056, 9062), True, 'import numpy as np\n'), ((9580, 9593), 'numpy.floor', 'np.floor', (['uF2'], {}), '(uF2)\n', (9588, 9593), True, 'import numpy as np\n'), ((12971, 12989), 'numpy.sqrt', 'np.sqrt', (['(np.pi * x)'], {}), '(np.pi * x)\n', (12978, 12989), True, 'import numpy as np\n'), ((13721, 13733), 'numpy.sqrt', 'np.sqrt', (['xu2'], {}), '(xu2)\n', (13728, 13733), True, 'import numpy as np\n'), ((8818, 8836), 'numpy.sqrt', 'np.sqrt', (['(k * np.pi)'], {}), '(k * np.pi)\n', (8825, 8836), True, 'import numpy as np\n'), ((9464, 9475), 'numpy.abs', 'np.abs', (['KLA'], {}), '(KLA)\n', (9470, 9475), True, 'import numpy as np\n')]
""" Given a file --infile pointing to a npz archive with X and y vectors, and assuming training has been run for both precomputed and computed GD, plots stuff nicely. assuming --infile is input.npz, writes plots input.npz-time.pdf input.npz-time-avg.pdf input.npz-samples.pdf input.npz-samples-avg.pdf """ from absl import app, flags import os from time import time import numpy as np from .. import log from ..utils import import_matplotlib flags.DEFINE_string( "infile", None, "the input X, true beta, and y arrays, as a npz file" ) flags.mark_flag_as_required("infile") flags.DEFINE_string("out", None, "output prefix") def _main(_argv): log.init() infile = flags.FLAGS.infile out = flags.FLAGS.out or infile values = np.load(flags.FLAGS.infile) X, beta_true, y = values["X"], values["beta"], values["y"] n, p = X.shape plt = import_matplotlib() st = np.load(infile + "-trace/time.npy") sl = np.load(infile + "-trace/loss_avg.npy") ft = np.load(infile + "-tracep/time.npy") fl = np.load(infile + "-tracep/loss_avg.npy") plt.semilogy(st, sl, ls="--", color="blue", label="stochastic") plt.semilogy(ft, fl, color="red", label="precompute") plt.legend() plt.title("loss v time") f = out + "-time.pdf" log.debug("writing to {}", f) plt.savefig(f, format="pdf", bbox_inches="tight") plt.clf() st = np.load(infile + "-trace/samples.npy") st = st * (p * 3) sl = np.load(infile + "-trace/loss_avg.npy") ft = np.load(infile + "-tracep/samples.npy") ft = np.ones_like(ft) ft *= 2 * p ** 2 ft = np.cumsum(ft) fl = np.load(infile + "-tracep/loss_avg.npy") plt.loglog(st, sl, ls="--", color="blue", label="stochastic") plt.loglog(ft, fl, color="red", label="precompute") plt.legend() plt.title("loss v flops") f = out + "-flop.pdf" log.debug("writing to {}", f) plt.savefig(f, format="pdf", bbox_inches="tight") plt.clf() if __name__ == "__main__": app.run(_main)
[ "numpy.load", "numpy.ones_like", "absl.flags.mark_flag_as_required", "absl.flags.DEFINE_string", "numpy.cumsum", "absl.app.run" ]
[((447, 541), 'absl.flags.DEFINE_string', 'flags.DEFINE_string', (['"""infile"""', 'None', '"""the input X, true beta, and y arrays, as a npz file"""'], {}), "('infile', None,\n 'the input X, true beta, and y arrays, as a npz file')\n", (466, 541), False, 'from absl import app, flags\n'), ((544, 581), 'absl.flags.mark_flag_as_required', 'flags.mark_flag_as_required', (['"""infile"""'], {}), "('infile')\n", (571, 581), False, 'from absl import app, flags\n'), ((583, 632), 'absl.flags.DEFINE_string', 'flags.DEFINE_string', (['"""out"""', 'None', '"""output prefix"""'], {}), "('out', None, 'output prefix')\n", (602, 632), False, 'from absl import app, flags\n'), ((751, 778), 'numpy.load', 'np.load', (['flags.FLAGS.infile'], {}), '(flags.FLAGS.infile)\n', (758, 778), True, 'import numpy as np\n'), ((901, 936), 'numpy.load', 'np.load', (["(infile + '-trace/time.npy')"], {}), "(infile + '-trace/time.npy')\n", (908, 936), True, 'import numpy as np\n'), ((946, 985), 'numpy.load', 'np.load', (["(infile + '-trace/loss_avg.npy')"], {}), "(infile + '-trace/loss_avg.npy')\n", (953, 985), True, 'import numpy as np\n'), ((995, 1031), 'numpy.load', 'np.load', (["(infile + '-tracep/time.npy')"], {}), "(infile + '-tracep/time.npy')\n", (1002, 1031), True, 'import numpy as np\n'), ((1041, 1081), 'numpy.load', 'np.load', (["(infile + '-tracep/loss_avg.npy')"], {}), "(infile + '-tracep/loss_avg.npy')\n", (1048, 1081), True, 'import numpy as np\n'), ((1393, 1431), 'numpy.load', 'np.load', (["(infile + '-trace/samples.npy')"], {}), "(infile + '-trace/samples.npy')\n", (1400, 1431), True, 'import numpy as np\n'), ((1463, 1502), 'numpy.load', 'np.load', (["(infile + '-trace/loss_avg.npy')"], {}), "(infile + '-trace/loss_avg.npy')\n", (1470, 1502), True, 'import numpy as np\n'), ((1512, 1551), 'numpy.load', 'np.load', (["(infile + '-tracep/samples.npy')"], {}), "(infile + '-tracep/samples.npy')\n", (1519, 1551), True, 'import numpy as np\n'), ((1561, 1577), 'numpy.ones_like', 'np.ones_like', (['ft'], {}), '(ft)\n', (1573, 1577), True, 'import numpy as np\n'), ((1608, 1621), 'numpy.cumsum', 'np.cumsum', (['ft'], {}), '(ft)\n', (1617, 1621), True, 'import numpy as np\n'), ((1631, 1671), 'numpy.load', 'np.load', (["(infile + '-tracep/loss_avg.npy')"], {}), "(infile + '-tracep/loss_avg.npy')\n", (1638, 1671), True, 'import numpy as np\n'), ((2003, 2017), 'absl.app.run', 'app.run', (['_main'], {}), '(_main)\n', (2010, 2017), False, 'from absl import app, flags\n')]
import numpy as np from cwFitter import Simulator class Evaluator(object): def __init__(self, sampleData, sim_params, bio_params): self.sampleData = sampleData self.sim_params = sim_params self.bio_params = bio_params if 'protoco_start_I' in sim_params: self.steps = np.arange(sim_params['protocol_start_I'], sim_params['protocol_end_I'], sim_params['protocol_steps_I']) else: self.steps = np.arange(sim_params['protocol_start'], sim_params['protocol_end'], sim_params['protocol_steps']) def evaluate(self, candidates, args): """ Runs VClamp and/or IClamp simulation to calculate the cost value for each candidate. I/V curve is also considered as an evaluation factor and coming from VClamp or IClamp simulations. The approach is based on Gurkiewicz & Korngreen study (doi:10.1371/journal.pcbi.0030169.) :return: total_cost """ #TODO: Include weights and minimization function (e.g. prAxis) #Based on Gurkiewicz & Korngreen approach (doi:10.1371/journal.pcbi.0030169.) fitness = 1e10 total_fitness = [] Vcost = 0 Icost = 0 IVcost = 0 IVFlag = False samples = 0 for candidate in candidates: cand_var = dict(zip(self.bio_params['channel_params'],candidate)) cell_var = dict(zip(self.bio_params['cell_params'],self.bio_params['val_cell_params'])) mySimulator = Simulator.Simulator(self.sim_params,cand_var,cell_var) if ('VClamp' in self.sampleData) or (('IV' in self.sampleData) and (('VClamp' and 'IClamp') not in self.sampleData)): VClampSim_t,VClampSim_I,VClampSim_Vmax,VClampSim_Imax = mySimulator.VClamp() tempCost = 0 M = 0 N = 0 if 'VClamp' in self.sampleData: for trace in self.sampleData['VClamp']['traces']: index = int((trace['vol'] - self.sim_params['protocol_start']) / self.sim_params['protocol_steps']) if VClampSim_I[index] : tempCost , N = self.cost([VClampSim_t,VClampSim_I[index]],[trace['t'],trace['I']]) Vcost += tempCost N += N M += 1 if (N * M) != 0: Vcost /= (N * M) samples += 1 if 'IV' in self.sampleData: IVcost , N = self.cost([VClampSim_Vmax,VClampSim_Imax],[self.sampleData['IV']['V'],self.sampleData['IV']['I']]) if N != 0: IVcost /= N IVFlag = True samples += 1 if 'IClamp' in self.sampleData: IClampSim_t,IClampSim_v,IClampSim_Vmax,IClampSim_Imax = mySimulator.IClamp() tempCost = 0 M = 0 N = 0 for trace in self.sampleData['IClamp']['traces']: index = int((trace['amp'] - self.sim_params['protocol_start_I']) / self.sim_params['protocol_steps_I']) if IClampSim_v[index]: tempCost , N = self.cost([IClampSim_t,IClampSim_v[index]],[trace['t'],trace['V']]) Icost += tempCost N += N M += 1 if (N * M) != 0: Icost /= (N * M) samples += 1 if IVFlag == False and 'IV' in self.sampleData: IVcost , N = self.cost([IClampSim_Vmax,IClampSim_Imax],[self.sampleData['IV']['V'],self.sampleData['IV']['I']]) if N != 0: IVcost /= N IVFlag = True samples += 1 fitness = (Vcost + Icost + IVcost) / samples total_fitness.append(fitness) return total_fitness def cost(self, sim, target): """ Get simulation data and target data (experimental/digitazed) to calculate cost. Cost function calculation is based on Gurkiewicz & Korngreen approach (doi:10.1371/journal.pcbi.0030169.) :return: """ #TODO: a better way to calculate cost is to measure the area between two plots!! sim_x = sim[0] cost_val = 1e9 N = 0 for target_x in target[0]: index = sim_x.index(min(sim_x, key=lambda x:abs(x-target_x))) #TODO: check if the distance is in a reasonable range (consider a sigma) if sim[1][index]: #if there is a comparable data and it's the first time, initialize the cost value with zero to calculate the total cost #else return a big number, to ignore this candidate if cost_val == 1e9: cost_val = 0 sim_y = sim[1][index] target_y = target[1][target[0].index(target_x)] #TODO: look for a better way to work with indices cost_val += (target_y - sim_y)**2 #TODO: normalize distance N += 1 return cost_val , N
[ "cwFitter.Simulator.Simulator", "numpy.arange" ]
[((320, 427), 'numpy.arange', 'np.arange', (["sim_params['protocol_start_I']", "sim_params['protocol_end_I']", "sim_params['protocol_steps_I']"], {}), "(sim_params['protocol_start_I'], sim_params['protocol_end_I'],\n sim_params['protocol_steps_I'])\n", (329, 427), True, 'import numpy as np\n'), ((463, 564), 'numpy.arange', 'np.arange', (["sim_params['protocol_start']", "sim_params['protocol_end']", "sim_params['protocol_steps']"], {}), "(sim_params['protocol_start'], sim_params['protocol_end'],\n sim_params['protocol_steps'])\n", (472, 564), True, 'import numpy as np\n'), ((1505, 1561), 'cwFitter.Simulator.Simulator', 'Simulator.Simulator', (['self.sim_params', 'cand_var', 'cell_var'], {}), '(self.sim_params, cand_var, cell_var)\n', (1524, 1561), False, 'from cwFitter import Simulator\n')]
# ------------------------------------------------------ # Merge ERA20c and ERA5 by adjusting the mean over 1979. # Average the results into annual means # Compute wind stress from wind fields # ------------------------------------------------------ import numpy as np from netCDF4 import Dataset import os import mod_gentools as gentools def main(): settings = {} settings['dir_data'] = os.getenv('HOME') + '/Data/' settings['fn_ERA5'] = settings['dir_data'] + 'Reanalyses/ERA5/ERA5.nc' settings['fn_ERA20c'] = settings['dir_data'] + 'Reanalyses/ERA20c/ERA20c_1900_1980_sfc.nc' settings['fn_save'] = settings['dir_data'] + 'Budget_20c/tg/ERA.nc' settings['years'] = np.arange(1900,2019) ERA5 = read_dataset(settings['fn_ERA5']) ERA20c = read_dataset(settings['fn_ERA20c']) ERA = merge_datasets(ERA5, ERA20c, settings) save_data(ERA,settings) return def read_dataset(fn): Data = {} file_handle = Dataset(fn) file_handle.set_auto_mask(False) Data['time'] = 1900 + file_handle.variables['time'][:]/365/24 Data['lon'] = file_handle.variables['longitude'][:] Data['lat'] = np.flipud(file_handle.variables['latitude'][:]) Data['uwind'] = np.fliplr(file_handle.variables['u10'][:]) Data['vwind'] = np.fliplr(file_handle.variables['v10'][:]) Data['mslp'] = np.fliplr(file_handle.variables['msl'][:]) file_handle.close() return(Data) def merge_datasets(ERA5,ERA20c,settings): # overlap indices ERA5_ovl = (ERA5['time'] >=1979) & (ERA5['time'] < 1980) ERA20c_ovl = (ERA20c['time'] >=1979) & (ERA20c['time'] < 1980) # Remove bias in 1979 ERA20c['mslp'] = ERA20c['mslp'] - ERA20c['mslp'][ERA20c_ovl,:,:].mean(axis=0)[np.newaxis,:,:] + ERA5['mslp'][ERA5_ovl,:,:].mean(axis=0)[np.newaxis,:,:] ERA20c['uwind'] = ERA20c['uwind'] - ERA20c['uwind'][ERA20c_ovl,:,:].mean(axis=0)[np.newaxis,:,:] + ERA5['uwind'][ERA5_ovl,:,:].mean(axis=0)[np.newaxis,:,:] ERA20c['vwind'] = ERA20c['vwind'] - ERA20c['vwind'][ERA20c_ovl,:,:].mean(axis=0)[np.newaxis,:,:] + ERA5['vwind'][ERA5_ovl,:,:].mean(axis=0)[np.newaxis,:,:] total_time = gentools.monthly_time(1900,2018) mslp = np.vstack([ERA20c['mslp'][:-12,:,:],ERA5['mslp']]) uwind = np.vstack([ERA20c['uwind'][:-12,:,:],ERA5['uwind']]) vwind = np.vstack([ERA20c['vwind'][:-12,:,:],ERA5['vwind']]) # Annual means from monthly means mslp_annual = np.zeros([len(settings['years']),len(ERA5['lat']),len(ERA5['lon'])]) uwind_annual = np.zeros([len(settings['years']),len(ERA5['lat']),len(ERA5['lon'])]) vwind_annual = np.zeros([len(settings['years']),len(ERA5['lat']),len(ERA5['lon'])]) for idx,yr in enumerate(settings['years']): yr_idx = (total_time>=yr)&(total_time<yr+1) mslp_annual[idx,:,:] = mslp[yr_idx,:,:].mean(axis=0) uwind_annual[idx,:,:] = uwind[yr_idx,:,:].mean(axis=0) vwind_annual[idx,:,:] = vwind[yr_idx,:,:].mean(axis=0) # From wind speed to wind stress uws_annual = (0.8 + 0.065 * np.sqrt(uwind_annual ** 2 + vwind_annual ** 2)) * uwind_annual * np.sqrt(uwind_annual ** 2 + vwind_annual ** 2) vws_annual = (0.8 + 0.065 * np.sqrt(uwind_annual ** 2 + vwind_annual ** 2)) * vwind_annual * np.sqrt(uwind_annual ** 2 + vwind_annual ** 2) ERA = {} ERA['lat'] = ERA5['lat'] ERA['lon'] = ERA5['lon'] ERA['time'] = settings['years'] ERA['mslp'] = mslp_annual ERA['uws'] = uws_annual ERA['vws'] = vws_annual return(ERA) def save_data(ERA,settings): file_handle = Dataset(settings['fn_save'], 'w') file_handle.createDimension('x', len(ERA['lon'])) file_handle.createDimension('y', len(ERA['lat'])) file_handle.createDimension('t', len(ERA['time'])) file_handle.createVariable('x', 'f4', ('x',),zlib=True)[:] = ERA['lon'] file_handle.createVariable('y', 'f4', ('y',),zlib=True)[:] = ERA['lat'] file_handle.createVariable('t', 'i4', ('t',),zlib=True)[:] = ERA['time'] file_handle.createVariable('mslp', 'f4', ('t', 'y', 'x',),zlib=True)[:] = ERA['mslp'] file_handle.createVariable('uws', 'f4', ('t', 'y', 'x',),zlib=True)[:] = ERA['uws'] file_handle.createVariable('vws', 'f4', ('t', 'y', 'x',),zlib=True)[:] = ERA['vws'] file_handle.close() return
[ "netCDF4.Dataset", "numpy.flipud", "numpy.fliplr", "numpy.arange", "mod_gentools.monthly_time", "os.getenv", "numpy.vstack", "numpy.sqrt" ]
[((700, 721), 'numpy.arange', 'np.arange', (['(1900)', '(2019)'], {}), '(1900, 2019)\n', (709, 721), True, 'import numpy as np\n'), ((964, 975), 'netCDF4.Dataset', 'Dataset', (['fn'], {}), '(fn)\n', (971, 975), False, 'from netCDF4 import Dataset\n'), ((1153, 1200), 'numpy.flipud', 'np.flipud', (["file_handle.variables['latitude'][:]"], {}), "(file_handle.variables['latitude'][:])\n", (1162, 1200), True, 'import numpy as np\n'), ((1221, 1263), 'numpy.fliplr', 'np.fliplr', (["file_handle.variables['u10'][:]"], {}), "(file_handle.variables['u10'][:])\n", (1230, 1263), True, 'import numpy as np\n'), ((1284, 1326), 'numpy.fliplr', 'np.fliplr', (["file_handle.variables['v10'][:]"], {}), "(file_handle.variables['v10'][:])\n", (1293, 1326), True, 'import numpy as np\n'), ((1346, 1388), 'numpy.fliplr', 'np.fliplr', (["file_handle.variables['msl'][:]"], {}), "(file_handle.variables['msl'][:])\n", (1355, 1388), True, 'import numpy as np\n'), ((2144, 2177), 'mod_gentools.monthly_time', 'gentools.monthly_time', (['(1900)', '(2018)'], {}), '(1900, 2018)\n', (2165, 2177), True, 'import mod_gentools as gentools\n'), ((2189, 2242), 'numpy.vstack', 'np.vstack', (["[ERA20c['mslp'][:-12, :, :], ERA5['mslp']]"], {}), "([ERA20c['mslp'][:-12, :, :], ERA5['mslp']])\n", (2198, 2242), True, 'import numpy as np\n'), ((2252, 2307), 'numpy.vstack', 'np.vstack', (["[ERA20c['uwind'][:-12, :, :], ERA5['uwind']]"], {}), "([ERA20c['uwind'][:-12, :, :], ERA5['uwind']])\n", (2261, 2307), True, 'import numpy as np\n'), ((2317, 2372), 'numpy.vstack', 'np.vstack', (["[ERA20c['vwind'][:-12, :, :], ERA5['vwind']]"], {}), "([ERA20c['vwind'][:-12, :, :], ERA5['vwind']])\n", (2326, 2372), True, 'import numpy as np\n'), ((3548, 3581), 'netCDF4.Dataset', 'Dataset', (["settings['fn_save']", '"""w"""'], {}), "(settings['fn_save'], 'w')\n", (3555, 3581), False, 'from netCDF4 import Dataset\n'), ((398, 415), 'os.getenv', 'os.getenv', (['"""HOME"""'], {}), "('HOME')\n", (407, 415), False, 'import os\n'), ((3095, 3141), 'numpy.sqrt', 'np.sqrt', (['(uwind_annual ** 2 + vwind_annual ** 2)'], {}), '(uwind_annual ** 2 + vwind_annual ** 2)\n', (3102, 3141), True, 'import numpy as np\n'), ((3239, 3285), 'numpy.sqrt', 'np.sqrt', (['(uwind_annual ** 2 + vwind_annual ** 2)'], {}), '(uwind_annual ** 2 + vwind_annual ** 2)\n', (3246, 3285), True, 'import numpy as np\n'), ((3030, 3076), 'numpy.sqrt', 'np.sqrt', (['(uwind_annual ** 2 + vwind_annual ** 2)'], {}), '(uwind_annual ** 2 + vwind_annual ** 2)\n', (3037, 3076), True, 'import numpy as np\n'), ((3174, 3220), 'numpy.sqrt', 'np.sqrt', (['(uwind_annual ** 2 + vwind_annual ** 2)'], {}), '(uwind_annual ** 2 + vwind_annual ** 2)\n', (3181, 3220), True, 'import numpy as np\n')]
import tensorflow as tf import numpy as np def accuracy_gpu(prediction, target): pred_label = tf.argmax(prediction, axis=1) target_label = tf.argmax(target, axis=1) counts = tf.to_float(tf.equal(pred_label, target_label)) return tf.reduce_mean(counts) def accuracy_cpu(prediction, target): pred_label = np.argmax(prediction, axis=1) target_label = np.argmax(target, axis=1) return np.mean(pred_label==target_label)
[ "numpy.argmax", "tensorflow.argmax", "tensorflow.reduce_mean", "numpy.mean", "tensorflow.equal" ]
[((100, 129), 'tensorflow.argmax', 'tf.argmax', (['prediction'], {'axis': '(1)'}), '(prediction, axis=1)\n', (109, 129), True, 'import tensorflow as tf\n'), ((149, 174), 'tensorflow.argmax', 'tf.argmax', (['target'], {'axis': '(1)'}), '(target, axis=1)\n', (158, 174), True, 'import tensorflow as tf\n'), ((247, 269), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['counts'], {}), '(counts)\n', (261, 269), True, 'import tensorflow as tf\n'), ((327, 356), 'numpy.argmax', 'np.argmax', (['prediction'], {'axis': '(1)'}), '(prediction, axis=1)\n', (336, 356), True, 'import numpy as np\n'), ((376, 401), 'numpy.argmax', 'np.argmax', (['target'], {'axis': '(1)'}), '(target, axis=1)\n', (385, 401), True, 'import numpy as np\n'), ((413, 448), 'numpy.mean', 'np.mean', (['(pred_label == target_label)'], {}), '(pred_label == target_label)\n', (420, 448), True, 'import numpy as np\n'), ((200, 234), 'tensorflow.equal', 'tf.equal', (['pred_label', 'target_label'], {}), '(pred_label, target_label)\n', (208, 234), True, 'import tensorflow as tf\n')]
import gc import logging import traceback from collections import defaultdict from datetime import datetime, timedelta from multiprocessing import Process, Queue import numpy as np import pandas as pd import xarray as xr from typhon.geodesy import great_circle_distance from typhon.geographical import GeoIndex from typhon.utils import add_xarray_groups, get_xarray_groups from typhon.utils.timeutils import to_datetime, to_timedelta, Timer __all__ = [ "Collocator", "check_collocation_data" ] logger = logging.getLogger(__name__) # The names for the processes. This started as an easter egg, but it actually # helps to identify different processes during debugging. PROCESS_NAMES = [ 'Newton', 'Einstein', 'Bohr', 'Darwin', 'Pasteur', 'Freud', 'Galilei', 'Lavoisier', 'Kepler', 'Copernicus', 'Faraday', 'Maxwell', 'Bernard', 'Boas', 'Heisenberg', 'Pauling', 'Virchow', 'Schrodinger', 'Rutherford', 'Dirac', 'Vesalius', 'Brahe', 'Buffon', 'Boltzmann', 'Planck', 'Curie', 'Herschel', 'Lyell', 'Laplace', 'Hubble', 'Thomson', 'Born', 'Crick', 'Fermi', 'Euler', 'Liebig', 'Eddington', 'Harvey', 'Malpighi', 'Huygens', 'Gauss', 'Haller', 'Kekule', 'Koch', 'Gell-Mann', 'Fischer', 'Mendeleev', 'Glashow', 'Watson', 'Bardeen', 'Neumann', 'Feynman', 'Wegener', 'Hawking', 'Leeuwenhoek', 'Laue', 'Kirchhoff', 'Bethe', 'Euclid', 'Mendel', 'Onnes', 'Morgan', 'Helmholtz', 'Ehrlich', 'Mayr', 'Sherrington', 'Dobzhansky', 'Delbruck', 'Lamarck', 'Bayliss', 'Chomsky', 'Sanger', 'Lucretius', 'Dalton', 'Broglie', 'Linnaeus', 'Piaget', 'Simpson', 'Levi-Strauss', 'Margulis', 'Landsteiner', 'Lorenz', 'Wilson', 'Hopkins', 'Elion', 'Selye', 'Oppenheimer', 'Teller', 'Libby', 'Haeckel', 'Salk', 'Kraepelin', 'Lysenko', 'Galton', 'Binet', 'Kinsey', 'Fleming', 'Skinner', 'Wundt', 'Archimedes' ] class ProcessCrashed(Exception): """Helper exception for crashed processes""" pass class Collocator: def __init__( self, threads=None, name=None, #log_dir=None ): """Initialize a collocator object that can find collocations Args: threads: Finding collocations can be parallelized in threads. Give here the maximum number of threads that you want to use. Which number of threads is the best, may be machine-dependent. So this is a parameter that you can use to fine-tune the performance. Note: Not yet implemented due to GIL usage of sklearn BallTree. name: The name of this collocator, will be used in log statements. """ self.empty = None # xr.Dataset() self.index = None self.index_with_primary = False self.threads = threads # These optimization parameters will be overwritten in collocate self.bin_factor = None self.magnitude_factor = None self.tunnel_limit = None self.leaf_size = None self.name = name if name is not None else "Collocator" # If no collocations are found, this will be returned. We need empty # arrays to concatenate the results without problems: @property def no_pairs(self): return np.array([[], []]) @property def no_intervals(self): return np.array([], dtype='timedelta64[ns]') @property def no_distances(self): return np.array([]) def __call__(self, *args, **kwargs): return self.collocate(*args, **kwargs) def _debug(self, msg): logger.debug(f"[{self.name}] {msg}") def _info(self, msg): logger.info(f"[{self.name}] {msg}") def _error(self, msg): logger.error(f"[{self.name}] {msg}") def collocate_filesets( self, filesets, start=None, end=None, processes=None, output=None, bundle=None, skip_file_errors=False, post_processor=None, post_processor_kwargs=None, **kwargs ): """Find collocation between the data of two filesets If you want to save the collocations directly to disk, it may be easier to use :meth:`~typhon.collocations.Collocations.search` directly. Args: filesets: A list of two :class:`FileSet` objects, the primary and the secondary fileset. Can be also :class:`~typhon.collocations.common.Collocations` objects with `read_mode=collapse`. The order of the filesets is irrelevant for the results of the collocation search but files from the secondary fileset might be read multiple times if using parallel processing (`processes` is greater than one). The number of output files could be different (see also the option `bundle`). start: Start date either as datetime object or as string ("YYYY-MM-DD hh:mm:ss"). Year, month and day are required. Hours, minutes and seconds are optional. If not given, it is datetime.min per default. end: End date. Same format as "start". If not given, it is datetime.max per default. processes: Collocating can be parallelized which improves the performance significantly. Pass here the number of processes to use. output: Fileset object where the collocated data should be stored. bundle: Set this to *primary* if you want to bundle the output files by their collocated primaries, i.e. there will be only one output file per primary. *daily* is also possible, then all files from one day are bundled together. Per default, all collocations for each file match will be saved separately. This might lead to a high number of output files. Note: *daily* means one process bundles all collocations from one day into one output file. If using multiple processes, this could still produce several daily output files per day. skip_file_errors: If this is *True* and a file could not be read, the file and its match will be skipped and a warning will be printed. Otheriwse the program will stop (default). post_processor: A function for post-processing the collocated data before saving it to `output`. Must accept two parameters: a xarray.Dataset with the collocated data and a dictionary with the path attributes from the collocated files. post_processor_kwargs: A dictionary with keyword arguments that should be passed to `post_processor`. **kwargs: Further keyword arguments that are allowed for :meth:`collocate`. Yields: A xarray.Dataset with the collocated data if `output` is not set. If `output` is set to a FileSet-like object, only the filename of the stored collocations is yielded. The results are not ordered if you use more than one process. For more information about the yielded xarray.Dataset have a look at :meth:`collocate`. Examples: .. code-block:: python """ timer = Timer().start() if len(filesets) != 2: raise ValueError("Only collocating two filesets at once is allowed" "at the moment!") # Check the max_interval argument because we need it later max_interval = kwargs.get("max_interval", None) if max_interval is None: raise ValueError("Collocating filesets without max_interval is" " not yet implemented!") if start is None: start = datetime.min else: start = to_datetime(start) if end is None: end = datetime.max else: end = to_datetime(end) self._info(f"Collocate from {start} to {end}") # Find the files from both filesets which overlap tempoerally. matches = list(filesets[0].match( filesets[1], start=start, end=end, max_interval=max_interval, )) if processes is None: processes = 1 # Make sure that there are never more processes than matches processes = min(processes, len(matches)) total_matches = sum(len(match[1]) for match in matches) self._info(f"using {processes} process(es) on {total_matches} matches") # MAGIC with processes # Each process gets a list with matches. Important: the matches should # be continuous to guarantee a good performance. After finishing one # match, the process pushes its results to the result queue. If errors # are raised during collocating, the raised errors are pushed to the # error queue, matches_chunks = np.array_split(matches, processes) # This queue collects all results: results = Queue(maxsize=processes) # This queue collects all error exceptions errors = Queue() # Extend the keyword arguments that we are going to pass to # _collocate_files: kwargs.update({ "start": start, "end": end, "filesets": filesets, "output": output, "bundle": bundle, "skip_file_errors": skip_file_errors, "post_processor": post_processor, "post_processor_kwargs": post_processor_kwargs, }) # This list contains all running processes process_list = [ Process( target=Collocator._process_caller, args=( self, results, errors, PROCESS_NAMES[i], ), kwargs={**kwargs, "matches": matches_chunk}, daemon=True, ) for i, matches_chunk in enumerate(matches_chunks) ] # We want to keep track of the progress of the collocation search since # it may take a while. process_progress = { name: 0. # Each process is at 0 percent at the beginning for name in PROCESS_NAMES[:processes] } # Start all processes: for process in process_list: process.start() # As long as some processes are still running, wait for their results: running = process_list.copy() processed_matches = 0 # The main process has two tasks during its child processes are # collocating. # 1) Collect their results and yield them to the user # 2) Display the progress and estimate the remaining processing time while running: # Filter out all processes that are dead: they either crashed or # complete their task running = [ process for process in running if process.is_alive() ] # Get all results from the result queue while not results.empty(): process, progress, result = results.get() # The process might be crashed. To keep the remaining time # estimation useful, we exclude the crashed process from the # calculation. if result is ProcessCrashed: del process_progress[process] else: process_progress[process] = progress try: nerrors = errors.qsize() except NotImplementedError: nerrors = 'unknown' self._print_progress( timer.elapsed, process_progress, len(running), nerrors) if result is not None: yield result # Explicit free up memory: gc.collect() for process in process_list: process.join() if not errors.empty(): self._error("Some processes terminated due to errors:") while not errors.empty(): error = errors.get() msg = '\n'.join([ "-"*79, error[2], "".join(traceback.format_tb(error[1])), "-" * 79 + "\n" ]) self._error(msg) @staticmethod def _print_progress(elapsed_time, process_progress, processes, errors): elapsed_time -= timedelta(microseconds=elapsed_time.microseconds) if len(process_progress) == 0: msg = "-"*79 + "\n" msg += f"100% | {elapsed_time} hours elapsed | " \ f"{errors} processes failed\n" msg += "-"*79 + "\n" logger.error(msg) return progress = sum(process_progress.values()) / len(process_progress) try: expected_time = elapsed_time * (100 / progress - 1) expected_time -= timedelta( microseconds=expected_time.microseconds) except ZeroDivisionError: expected_time = "unknown" msg = "-"*79 + "\n" msg += f"{progress:.0f}% | {elapsed_time} hours elapsed, " \ f"{expected_time} hours left | {processes} proc running, " \ f"{errors} failed\n" msg += "-"*79 + "\n" logger.error(msg) @staticmethod def _process_caller( self, results, errors, name, output, bundle, post_processor, post_processor_kwargs, **kwargs): """Wrapper around _collocate_matches This function is called for each process. It communicates with the main process via the result and error queue. Result Queue: Adds for each collocated file match the process name, its progress and the actual results. Error Queue: If an error is raised, the name of this proces and the error messages is put to this queue. """ self.name = name # We keep track of how many file pairs we have already processed to # make the error debugging easier. We need the match in flat form: matches = [ [match[0], secondary] for match in kwargs['matches'] for secondary in match[1] ] # If we want to bundle the output, we need to collect some contents. # The current_bundle_tag stores a certain information for the current # bundle (e.g. filename of primary or day of the year). If it changes, # the bundle is stored to disk and a new bundle is created. cached_data = [] cached_attributes = {} current_bundle_tag = None try: processed = 0 collocated_matches = self._collocate_matches(**kwargs) for collocations, attributes in collocated_matches: match = matches[processed] processed += 1 progress = 100 * processed / len(matches) if collocations is None: results.put([name, progress, None]) continue # The user does not want to bundle anything therefore just save # the current collocations if bundle is None: result = self._save_and_return( collocations, attributes, output, post_processor, post_processor_kwargs ) results.put([name, progress, result]) continue # The user may want to bundle the collocations before writing # them to disk, e.g. by their primaries. save_cache = self._should_save_cache( bundle, current_bundle_tag, match, to_datetime(collocations.attrs["start_time"]) ) if save_cache: result = self._save_and_return( cached_data, cached_attributes, output, post_processor, post_processor_kwargs ) results.put([name, progress, result]) cached_data = [] cached_attributes = {} # So far, we have not cached any collocations or we still need # to wait before saving them to disk. cached_data.append(collocations) cached_attributes.update(**attributes) if bundle == "primary": current_bundle_tag = match[0].path elif bundle == "daily": current_bundle_tag = \ to_datetime(collocations.attrs["start_time"]).date() # After all iterations, save last cached data to disk: if cached_data: result = self._save_and_return( cached_data, cached_attributes, output, post_processor, post_processor_kwargs ) results.put([name, progress, result]) except Exception as exception: # Tell the main process to stop considering this process for the # remaining processing time: results.put( [name, 100., ProcessCrashed] ) self._error("ERROR: I got a problem and terminate!") # Build a message that contains all important information for # debugging: msg = f"Process {name} ({matches[0][0].times[0]} -" \ f"{matches[-1][0].times[1]}) failed\n" \ f"Failed to collocate {matches[processed]} with"\ f"{matches[processed]}\n" # The main process needs to know about this exception! error = [ name, exception.__traceback__, msg + "ERROR: " + str(exception) ] errors.put(error) self._error(exception) # Finally, raise the exception to terminate this process: raise exception self._info(f"Finished all {len(matches)} matches") def _save_and_return(self, collocations, attributes, output, post_processor, post_processor_kwargs): """Save collocations to disk or return them""" if isinstance(collocations, list): collocations = concat_collocations( collocations ) if output is None: return collocations, attributes else: filename = output.get_filename( [to_datetime(collocations.attrs["start_time"]), to_datetime(collocations.attrs["end_time"])], fill=attributes ) # Apply a post processor function from the user if post_processor is not None: if post_processor_kwargs is None: post_processor_kwargs = {} collocations = post_processor( collocations, attributes, **post_processor_kwargs ) if collocations is None: return None self._info(f"Store collocations to\n{filename}") # Write the data to the file. output.write(collocations, filename) return filename @staticmethod def _should_save_cache(bundle, current_bundle_tag, match, start_time): """Return true if the cache should be saved otherwise false """ if current_bundle_tag is None: return False elif bundle == "primary": # Check whether the primary has changed since the last time: return current_bundle_tag != match[0].path elif bundle == "daily": # Has the day changed since last time? return current_bundle_tag != start_time.date() # In all other cases, the bundle should not be saved yet: return False def _collocate_matches( self, filesets, matches, skip_file_errors, **kwargs ): """Load file matches and collocate their content Yields: A tuple of two items: the first is always the current percentage of progress. If output is True, the second is only the filename of the saved collocations. Otherwise, it is a tuple of collocations and their collected :class:`~typhon.files.handlers.common.FileInfo` attributes as a dictionary. """ # Load all matches in a parallized queue: loaded_matches = filesets[0].align( filesets[1], matches=matches, return_info=True, compact=False, skip_errors=skip_file_errors, ) for loaded_match in loaded_matches: # The FileInfo objects of the matched files: files = loaded_match[0][0], loaded_match[1][0] # We copy the data from the matches since they might be used for # other matches as well: primary, secondary = \ loaded_match[0][1].copy(), loaded_match[1][1].copy() self._debug(f"Collocate {files[0].path}\nwith {files[1].path}") collocations = self.collocate( (filesets[0].name, primary), (filesets[1].name, secondary), **kwargs, ) if collocations is None: self._debug("Found no collocations!") # At least, give the process caller a progress update: yield None, None continue # Check whether the collocation data is compatible and was build # correctly check_collocation_data(collocations) found = [ collocations[f"{filesets[0].name}/time"].size, collocations[f"{filesets[1].name}/time"].size ] self._debug( f"Found {found[0]} ({filesets[0].name}) and " f"{found[1]} ({filesets[1].name}) collocations" ) # Add the names of the processed files: for f in range(2): if f"{filesets[f].name}/__file" in collocations.variables: continue collocations[f"{filesets[f].name}/__file"] = files[f].path # Collect the attributes of the input files. The attributes get a # prefix, primary or secondary, to allow not-unique names. attributes = { f"primary.{p}" if f == 0 else f"secondary.{p}": v for f, file in enumerate(files) for p, v in file.attr.items() } yield collocations, attributes def collocate( self, primary, secondary, max_interval=None, max_distance=None, bin_factor=1, magnitude_factor=10, tunnel_limit=None, start=None, end=None, leaf_size=40 ): """Find collocations between two xarray.Dataset objects Collocations are two or more data points that are located close to each other in space and/or time. Each xarray.Dataset contain the variables *time*, *lat*, *lon*. They must be - if they are coordinates - unique. Otherwise, their coordinates must be unique, i.e. they cannot contain duplicated values. *time* must be a 1-dimensional array with a *numpy.datetime64*-like data type. *lat* and *lon* can be gridded, i.e. they can be multi- dimensional. However, they must always share the first dimension with *time*. *lat* must be latitudes between *-90* (south) and *90* (north) and *lon* must be longitudes between *-180* (west) and *180* (east) degrees. See below for examples. The collocation searched is performed with a fast ball tree implementation by scikit-learn. The ball tree is cached and reused whenever the data points from `primary` or `secondary` have not changed. If you want to find collocations between FileSet objects, use :class:`collocate_filesets` instead. Args: primary: A tuple of a string with the dataset name and a xarray.Dataset that fulfill the specifications from above. Can be also a xarray.Dataset only, the name is then automatically set to *primary*. secondary: A tuple of a string with the dataset name and a xarray.Dataset that fulfill the specifications from above. Can be also a xarray.Dataset only, the name is then automatically set to *secondary*. max_interval: Either a number as a time interval in seconds, a string containing a time with a unit (e.g. *100 minutes*) or a timedelta object. This is the maximum time interval between two data points. If this is None, the data will be searched for spatial collocations only. max_distance: Either a number as a length in kilometers or a string containing a length with a unit (e.g. *100 meters*). This is the maximum distance between two data points to meet the collocation criteria. If this is None, the data will be searched for temporal collocations only. Either `max_interval` or *max_distance* must be given. tunnel_limit: Maximum distance in kilometers at which to switch from tunnel to haversine distance metric. Per default this algorithm uses the tunnel metric, which simply transform all latitudes and longitudes to 3D-cartesian space and calculate their euclidean distance. This is faster than the haversine metric but produces an error that grows with larger distances. When searching for distances exceeding this limit (`max_distance` is greater than this parameter), the haversine metric is used, which is more accurate but takes more time. Default is 1000 kilometers. magnitude_factor: Since building new trees is expensive, this algorithm tries to use the last tree when possible (e.g. for data with fixed grid). However, building the tree with the larger dataset and query it with the smaller dataset is faster than vice versa. Depending on which premise to follow, there might have a different performance in the end. This parameter is the factor of that one dataset must be larger than the other to throw away an already-built ball tree and rebuild it with the larger dataset. leaf_size: The size of one leaf in the Ball Tree. The higher the leaf size the faster is the tree building but the slower is the tree query. The optimal leaf size is dataset-dependent. Default is 40. bin_factor: When using a temporal criterion via `max_interval`, the data will be temporally binned to speed-up the search. The bin size is `bin_factor` * `max_interval`. Which bin factor is the best, may be dataset-dependent. So this is a parameter that you can use to fine-tune the performance. start: Limit the collocated data from this start date. Can be either as datetime object or as string ("YYYY-MM-DD hh:mm:ss"). Year, month and day are required. Hours, minutes and seconds are optional. If not given, it is datetime.min per default. end: End date. Same format as "start". If not given, it is datetime.max per default. Returns: None if no collocations were found. Otherwise, a xarray.Dataset with the collocated data in *compact* form. It consists of three groups (groups of variables containing */* in their name): the *primary*, *secondary* and the *Collocations* group. If you passed `primary` or `secondary` with own names, they will be used in the output. The *Collocations* group contains information about the found collocations. *Collocations/pairs* is a 2xN array where N is the number of found collocations. It contains the indices of the *primary* and *secondary* data points which are collocations. The indices refer to the data points stored in the *primary* or *secondary* group. *Collocations/interval* and *Collocations/distance* are the intervals and distances between the collocations in seconds and kilometers, respectively. Collocations in *compact* form are efficient when saving them to disk but it might be complicated to use them directly. Consider applying :func:`~typhon.collocations.common.collapse` or :func:`~typhon.collocations.common.expand` on them. Examples: .. code-block: python # TODO: Update this example! import numpy as np from typhon.collocations import Collocator # Create the data. primary and secondary can also be # xarray.Dataset objects: primary = { "time": np.arange( "2018-01-01", "2018-01-02", dtype="datetime64[h]" ), "lat": 30.*np.sin(np.linspace(-3.14, 3.14, 24))+20, "lon": np.linspace(0, 90, 24), } secondary = { "time": np.arange( "2018-01-01", "2018-01-02", dtype="datetime64[h]" ), "lat": 30.*np.sin(np.linspace(-3.14, 3.14, 24)+1.)+20, "lon": np.linspace(0, 90, 24), } # Find collocations with a maximum distance of 300 kilometers # and a maximum interval of 1 hour collocator = Collocator() collocated = collocator.collocate( primary, secondary, max_distance="300km", max_interval="1h" ) print(collocated) """ if max_distance is None and max_interval is None: raise ValueError( "Either max_distance or max_interval must be given!" ) if max_interval is not None: max_interval = to_timedelta(max_interval, numbers_as="seconds") # The user can give strings instead of datetime objects: start = datetime.min if start is None else to_datetime(start) end = datetime.max if end is None else to_datetime(end) # Did the user give the datasets specific names? primary_name, primary, secondary_name, secondary = self._get_names( primary, secondary ) # Select the common time period of both datasets and flat them. primary, secondary = self._prepare_data( primary, secondary, max_interval, start, end ) # Maybe there is no data left after selection? if primary is None: return self.empty self.bin_factor = bin_factor self.magnitude_factor = magnitude_factor self.tunnel_limit = tunnel_limit self.leaf_size = leaf_size timer = Timer().start() # We cannot allow NaNs in the time, lat or lon fields not_nans1 = self._get_not_nans(primary) not_nans2 = self._get_not_nans(secondary) # Retrieve the important fields from the data. To avoid any overhead by # xarray, we use the plain numpy.arrays and do not use the isel method # (see https://github.com/pydata/xarray/issues/2227). We rather use # index arrays that we use later to select the rest of the data lat1 = primary.lat.values[not_nans1] lon1 = primary.lon.values[not_nans1] time1 = primary.time.values[not_nans1] lat2 = secondary.lat.values[not_nans2] lon2 = secondary.lon.values[not_nans2] time2 = secondary.time.values[not_nans2] original_indices = [ np.arange(primary.time.size)[not_nans1], np.arange(secondary.time.size)[not_nans2] ] self._debug(f"{timer} for filtering NaNs") # We can search for spatial collocations (max_interval=None), temporal # collocations (max_distance=None) or both. if max_interval is None: # Search for spatial collocations only: pairs, distances = self.spatial_search( lat1, lon1, lat2, lon2, max_distance, ) intervals = self._get_intervals( time1[pairs[0]], time2[pairs[1]] ) return self._create_return( primary, secondary, primary_name, secondary_name, self._to_original(pairs, original_indices), intervals, distances, max_interval, max_distance ) elif max_distance is None: # Search for temporal collocations only: pairs, intervals = self.temporal_search( time1, time2, max_interval ) distances = self._get_distances( lat1[pairs[0]], lon1[pairs[0]], lat2[pairs[1]], lon2[pairs[1]], ) return self._create_return( primary, secondary, primary_name, secondary_name, self._to_original(pairs, original_indices), intervals, distances, max_interval, max_distance ) # The user wants to use both criteria and search for spatial and # temporal collocations. At first, we do a coarse temporal pre-binning # so that we only search for collocations between points that might # also be temporally collocated. Unfortunately, this also produces an # overhead that is only negligible if we have a lot of data: data_magnitude = time1.size * time2.size if data_magnitude > 100_0000: # We have enough data, do temporal pre-binning! pairs, distances = self.spatial_search_with_temporal_binning( {"lat": lat1, "lon": lon1, "time": time1}, {"lat": lat2, "lon": lon2, "time": time2}, max_distance, max_interval ) else: # We do not have enough data to justify that whole pre-binning. # Simply do it directly! pairs, distances = self.spatial_search( lat1, lon1, lat2, lon2, max_distance, ) # Did we find any spatial collocations? if not pairs.any(): return self.empty # Check now whether the spatial collocations really pass the temporal # condition: passed_temporal_check, intervals = self._temporal_check( time1[pairs[0]], time2[pairs[1]], max_interval ) # Return only the values that passed the time check return self._create_return( primary, secondary, primary_name, secondary_name, self._to_original( pairs[:, passed_temporal_check], original_indices), intervals, distances[passed_temporal_check], max_interval, max_distance ) @staticmethod def _to_original(pairs, original_indices): return np.array([ original_indices[i][pair_array] for i, pair_array in enumerate(pairs) ]) @staticmethod def _get_names(primary, secondary): # Check out whether the user gave the primary and secondary any name: if isinstance(primary, (tuple, list)): primary_name, primary = primary else: primary_name = "primary" if isinstance(secondary, (tuple, list)): secondary_name, secondary = secondary else: secondary_name = "secondary" return primary_name, primary, secondary_name, secondary def _prepare_data(self, primary, secondary, max_interval, start, end): """Prepare the data for the collocation search This method selects the time period which should be searched for collocations and flats the input datasets if they have gridded variables. Returns: The datasets constraint to the common time period, sorted by time and flattened. If no common time period could be found, two None objects are returned. """ if max_interval is not None: timer = Timer().start() # We do not have to collocate everything, just the common time # period expanded by max_interval and limited by the global start # and end parameter: primary_period, secondary_period = self._get_common_time_period( primary, secondary, max_interval, start, end ) # Check whether something is left: if not primary_period.size or not secondary_period.size: return None, None # We need everything sorted by the time, otherwise xarray's stack # method makes problems: primary_period = primary_period.sortby(primary_period) primary_dim = primary_period.dims[0] secondary_period = secondary_period.sortby(secondary_period) secondary_dim = secondary_period.dims[0] # Select the common time period and while using sorted indices: primary = primary.sel(**{primary_dim: primary_period[primary_dim]}) secondary = secondary.sel( **{secondary_dim: secondary_period[secondary_dim]} ) # Check whether something is left: if not primary_period.size or not secondary_period.size: return None, None self._debug(f"{timer} for selecting common time period") # Flat the data: For collocating, we need a flat data structure. # Fortunately, xarray provides the very convenient stack method # where we can flat multiple dimensions to one. Which dimensions do # we have to stack together? We need the fields *time*, *lat* and # *lon* to be flat. So we choose their dimensions to be stacked. timer = Timer().start() primary = self._flat_to_main_coord(primary) secondary = self._flat_to_main_coord(secondary) self._debug(f"{timer} for flatting data") return primary, secondary @staticmethod def _get_common_time_period( primary, secondary, max_interval, start, end): max_interval = pd.Timedelta(max_interval) # We want to select a common time window from both datasets, # aligned to the primary's time coverage. Because xarray has a # very annoying bug in time retrieving # (https://github.com/pydata/xarray/issues/1240), this is a # little bit cumbersome: common_start = max( start, pd.Timestamp(primary.time.min().item(0)) - max_interval, pd.Timestamp(secondary.time.min().item(0)) - max_interval ) common_end = min( end, pd.Timestamp(primary.time.max().item(0)) + max_interval, pd.Timestamp(secondary.time.max().item(0)) + max_interval ) primary_period = primary.time.where( (primary.time.values >= np.datetime64(common_start)) & (primary.time.values <= np.datetime64(common_end)) ).dropna(primary.time.dims[0]) secondary_period = secondary.time.where( (secondary.time.values >= np.datetime64(common_start)) & (secondary.time.values <= np.datetime64(common_end)) ).dropna(secondary.time.dims[0]) return primary_period, secondary_period @staticmethod def _get_not_nans(dataset): return dataset.lat.notnull().values & dataset.lon.notnull().values @staticmethod def _flat_to_main_coord(data): """Make the dataset flat despite of its original structure We need a flat dataset structure for the collocation algorithms, i.e. time, lat and lon are not allowed to be gridded, they must be 1-dimensional and share the same dimension (namely *collocation*). There are three groups of original data structures that this method can handle: * linear (e.g. ship track measurements): time, lat and lon have the same dimension and are all 1-dimensional. Fulfills all criteria from above. No action has to be taken. * gridded_coords (e.g. instruments on satellites with gridded swaths): lat or lon are gridded (they have multiple dimensions). Stack the coordinates of them together to a new shared dimension. Args: data: xr.Dataset object Returns: A xr.Dataset where time, lat and lon are aligned on one shared dimension. """ # Flat: shared_dims = list( set(data.time.dims) | set(data.lat.dims) | set(data.lon.dims) ) # Check whether the dataset is flat (time, lat and lon share the same # dimension size and are 1-dimensional) if len(shared_dims) == 1: if shared_dims[0] in ("time", "lat", "lon"): # One of the key variables is the main dimension! Change this: data["collocation"] = shared_dims[0], np.arange( data[shared_dims[0]].size) data = data.swap_dims({shared_dims[0]: "collocation"}) data = data.reset_coords(shared_dims[0]) # So far, collocation is a coordinate. We want to make it to a # dimension, so drop its values: return data.drop("collocation") return data.rename({ shared_dims[0]: "collocation" }) # The coordinates are gridded: # Some field might be more deeply stacked than another. Choose the # dimensions of the most deeply stacked variable: dims = max( data["time"].dims, data["lat"].dims, data["lon"].dims, key=lambda x: len(x) ) # We want to be able to retrieve additional fields after collocating. # Therefore, we give each dimension that is no coordinate yet a value # to use them as indices later. for dim in dims: if dim not in data.coords: data[dim] = dim, np.arange(data.dims[dim]) # We assume that coordinates must be unique! Otherwise, we would have # to use this ugly work-around: # Replace the former coordinates with new coordinates that have unique # values. # new_dims = [] # for dim in dims: # new_dim = f"__replacement_{dim}" # data[new_dim] = dim, np.arange(data.dims[dim]) # data = data.swap_dims({dim: new_dim}) # new_dims.append(new_dim) return data.stack(collocation=dims) def _create_return( self, primary, secondary, primary_name, secondary_name, original_pairs, intervals, distances, max_interval, max_distance ): if not original_pairs.any(): return self.empty pairs = [] output = {} names = [primary_name, secondary_name] for i, dataset in enumerate([primary, secondary]): # name of the current dataset (primary or secondary) name = names[i] # These are the indices of the points in the original data that # have collocations. We remove the duplicates since we want to copy # the required data only once. They are called original_indices # because they are the indices in the original data array: original_indices = pd.unique(original_pairs[i]) # After selecting the collocated data, the original indices cannot # be applied any longer. We need new indices that indicate the # pairs in the collocated data. new_indices = np.empty(original_indices.max() + 1, dtype=int) new_indices[original_indices] = np.arange( original_indices.size ) collocation_indices = new_indices[original_pairs[i]] # Save the collocation indices in the metadata group: pairs.append(collocation_indices) output[names[i]] = dataset.isel(collocation=original_indices) # We have to convert the MultiIndex to a normal index because we # cannot store it to a file otherwise. We can convert it by simply # setting it to new values, but we are losing the sub-level # coordinates (the dimenisons that we stacked to create the # multi-index in the first place) with that step. Hence, we store # the sub-level coordinates in additional dataset to preserve them. main_coord_is_multiindex = isinstance( output[name].get_index("collocation"), pd.core.indexes.multi.MultiIndex ) if main_coord_is_multiindex: stacked_dims_data = xr.merge([ xr.DataArray( output[name][dim].values, name=dim, dims=["collocation"] ) for dim in output[name].get_index("collocation").names ]) # Okay, actually we want to get rid of the main coordinate. It # should stay as a dimension name but without own labels. I.e. we # want to drop it. Because it still may a MultiIndex, we cannot # drop it directly but we have to set it to something different. output[name]["collocation"] = \ np.arange(output[name]["collocation"].size) if main_coord_is_multiindex: # Now, since we unstacked the multi-index, we can add the # stacked dimensions back to the dataset: output[name] = xr.merge( [output[name], stacked_dims_data], ) # For the flattening we might have created temporal variables, # also collect them to drop: vars_to_drop = [ var for var in output[name].variables.keys() if var.startswith("__replacement_") ] output[name] = output[name].drop([ f"collocation", *vars_to_drop ]) # Merge all datasets into one: output = add_xarray_groups( xr.Dataset(), **output ) # This holds the collocation information (pairs, intervals and # distances): metadata = xr.Dataset() metadata["pairs"] = xr.DataArray( np.array(pairs, dtype=int), dims=("group", "collocation"), attrs={ "max_interval": f"Max. interval in secs: {max_interval}", "max_distance": f"Max. distance in kilometers: {max_distance}", "primary": primary_name, "secondary": secondary_name, } ) metadata["interval"] = xr.DataArray( intervals, dims=("collocation", ), attrs={ "max_interval": f"Max. interval in secs: {max_interval}", "max_distance": f"Max. distance in kilometers: {max_distance}", "primary": primary_name, "secondary": secondary_name, } ) metadata["distance"] = xr.DataArray( distances, dims=("collocation",), attrs={ "max_interval": f"Max. interval in secs: {max_interval}", "max_distance": f"Max. distance in kilometers: {max_distance}", "primary": primary_name, "secondary": secondary_name, "units": "kilometers", } ) metadata["group"] = xr.DataArray( [primary_name, secondary_name], dims=("group",), attrs={ "max_interval": f"Max. interval in secs: {max_interval}", "max_distance": f"Max. distance in kilometers: {max_distance}", } ) output = add_xarray_groups( output, Collocations=metadata ) start = pd.Timestamp( output[primary_name+"/time"].min().item(0) ) end = pd.Timestamp( output[primary_name+"/time"].max().item(0) ) output.attrs = { "start_time": str(start), "end_time": str(end), } return output @staticmethod def get_meta_group(): return f"Collocations" def spatial_search_with_temporal_binning( self, primary, secondary, max_distance, max_interval ): # For time-binning purposes, pandas Dataframe objects are a good choice primary = pd.DataFrame(primary).set_index("time") secondary = pd.DataFrame(secondary).set_index("time") # Now let's split the two data data along their time coordinate so # we avoid searching for spatial collocations that do not fulfill # the temporal condition in the first place. However, the overhead # of the finding algorithm must be considered too (for example the # BallTree creation time). This can be adjusted by the parameter # bin_factor: bin_duration = self.bin_factor * max_interval # The binning is more efficient if we use the largest dataset as # primary: swapped_datasets = secondary.size > primary.size if swapped_datasets: primary, secondary = secondary, primary # Let's bin the primaries along their time axis and search for the # corresponding secondary bins: bin_pairs = ( self._bin_pairs(start, chunk, primary, secondary, max_interval) for start, chunk in primary.groupby(pd.Grouper(freq=bin_duration)) ) # Add arguments to the bins (we need them for the spatial search # function): bins_with_args = ( [self, max_distance, *bin_pair] for bin_pair in bin_pairs ) # Unfortunately, a first attempt parallelizing this using threads # worsened the performance. Update: The BallTree code from scikit-learn # does not release the GIL. But apparently there will be a new version # coming that solves this problem, see this scikit-learn issue: # https://github.com/scikit-learn/scikit-learn/pull/10887. So stay # tuned! # threads = 1 if self.threads is None else self.threads t = Timer(verbose=False).start() # with ThreadPoolExecutor(max_workers=2) as pool: # results = list(pool.map( # Collocator._spatial_search_bin, bins_with_args # )) results = list(map( Collocator._spatial_search_bin, bins_with_args )) self._debug(f"Collocated {len(results)} bins in {t.stop()}") pairs_list, distances_list = zip(*results) pairs = np.hstack(pairs_list) # No collocations were found. if not pairs.any(): return self.no_pairs, self.no_distances # Stack the rest of the results together: distances = np.hstack(distances_list) if swapped_datasets: # Swap the rows of the results pairs[[0, 1]] = pairs[[1, 0]] return pairs.astype("int64"), distances @staticmethod def _bin_pairs(chunk1_start, chunk1, primary, secondary, max_interval): """""" chunk2_start = chunk1_start - max_interval chunk2_end = chunk1.index.max() + max_interval offset1 = primary.index.searchsorted(chunk1_start) offset2 = secondary.index.searchsorted(chunk2_start) chunk2 = secondary.loc[chunk2_start:chunk2_end] return offset1, chunk1, offset2, chunk2 @staticmethod def _spatial_search_bin(args): self, max_distance, offset1, data1, offset2, data2 = args if data1.empty or data2.empty: return self.no_pairs, self.no_distances pairs, distances = self.spatial_search( data1["lat"].values, data1["lon"].values, data2["lat"].values, data2["lon"].values, max_distance ) pairs[0] += offset1 pairs[1] += offset2 return pairs, distances def spatial_search(self, lat1, lon1, lat2, lon2, max_distance): # Finding collocations is expensive, therefore we want to optimize it # and have to decide which points to use for the index building. index_with_primary = self._choose_points_to_build_index( [lat1, lon1], [lat2, lon2], ) self.index_with_primary = index_with_primary if index_with_primary: build_points = lat1, lon1 query_points = lat2, lon2 else: build_points = lat2, lon2 query_points = lat1, lon1 self.index = self._build_spatial_index(*build_points) pairs, distances = self.index.query(*query_points, r=max_distance) # No collocations were found. if not pairs.any(): # We return empty arrays to have consistent return values: return self.no_pairs, self.no_distances if not index_with_primary: # The primary indices should be in the first row, the secondary # indices in the second: pairs[[0, 1]] = pairs[[1, 0]] return pairs, distances def _build_spatial_index(self, lat, lon): # Find out whether the cached index still works with the new points: if self._spatial_is_cached(lat, lon): self._debug("Spatial index is cached and can be reused") return self.index return GeoIndex(lat, lon, leaf_size=self.leaf_size) def _spatial_is_cached(self, lat, lon): """Return True if the cached ball tree is still applicable to the new data""" if self.index is None: return False try: return np.allclose(lat, self.index.lat) \ & np.allclose(lon, self.index.lon) except ValueError: # The shapes are different return False def _choose_points_to_build_index(self, primary, secondary): """Choose which points should be used for tree building This method helps to optimize the performance. Args: primary: Converted primary points secondary: Converted secondary points Returns: True if primary points should be used for tree building. False otherwise. """ # There are two options to optimize the performance: # A) Cache the index and reuse it if either the primary or the # secondary points have not changed (that is the case for data with a # fixed grid). Building the tree is normally very expensive, so it # should never be done without a reason. # B) Build the tree with the larger set of points and query it with the # smaller set. # Which option should be used if A and B cannot be applied at the same # time? If the magnitude of one point set is much larger (by # `magnitude factor` larger) than the other point set, we strictly # follow B. Otherwise, we prioritize A. if primary[0].size > secondary[0].size * self.magnitude_factor: # Use primary points return True elif secondary[0].size > primary[0].size * self.magnitude_factor: # Use secondary points return False # Apparently, none of the datasets is much larger than the others. So # just check whether we still have a cached tree. If we used the # primary points last time and they still fit, use them again: if self.index_with_primary and self._spatial_is_cached(*primary): return True # Check the same for the secondary data: if not self.index_with_primary and self._spatial_is_cached(*secondary): return False # Otherwise, just use the larger dataset: return primary[0].size > secondary[0].size def temporal_search(self, primary, secondary, max_interval): raise NotImplementedError("Not yet implemented!") #return self.no_pairs, self.no_intervals def _temporal_check( self, primary_time, secondary_time, max_interval ): """Checks whether the current collocations fulfill temporal conditions Returns: """ intervals = self._get_intervals(primary_time, secondary_time) # Check whether the time differences are less than the temporal # boundary: passed_time_check = intervals < max_interval return passed_time_check, intervals[passed_time_check] @staticmethod def _get_intervals(time1, time2): return np.abs((time1 - time2)).astype("timedelta64[s]") @staticmethod def _get_distances(lat1, lon1, lat2, lon2): return great_circle_distance(lat1, lon1, lat2, lon2) def concat_collocations(collocations): """Concat compact collocations Compact collocations cannot be concatenated directly because indices in *Collocations/pairs* won't be correct any longer afterwards. This concatenate function fixes this problem. Args: collocations: A list of xarray.Dataset objects with compact collocations. Returns: One xarray.Dataset object """ # We need to increment the pair indices when concatening the datasets primary = collocations[0]["Collocations/group"].item(0) secondary = collocations[0]["Collocations/group"].item(1) primary_size = 0 secondary_size = 0 collocation_coord = { "Collocations": "Collocations/collocation", primary: f"{primary}/collocation", secondary: f"{secondary}/collocation", } # Collect all collocations for each single group: groups = defaultdict(list) for obj in collocations: for group, data in get_xarray_groups(obj).items(): if group == "Collocations": # Correct the indices: data["Collocations/pairs"][0, :] += primary_size data["Collocations/pairs"][1, :] += secondary_size data = data.drop("Collocations/group") groups[group].append(data) primary_size += obj.dims[f"{primary}/collocation"] secondary_size += obj.dims[f"{secondary}/collocation"] starts = [] ends = [] for group, data_list in groups.items(): groups[group] = xr.concat( data_list, dim=collocation_coord[group] ) start = pd.Timestamp(groups[primary][primary+"/time"].min().item(0)) end = pd.Timestamp(groups[primary][primary+"/time"].max().item(0)) merged = xr.merge(groups.values()) merged.attrs = { "start_time": str(start), "end_time": str(end), } merged["Collocations/group"] = collocations[0]["Collocations/group"] return merged class InvalidCollocationData(Exception): """Error when trying to collapse / expand invalid collocation data """ def __init__(self, message, *args): Exception.__init__(self, message, *args) def check_collocation_data(dataset): """Check whether the dataset fulfills the standard of collocated data Args: dataset: A xarray.Dataset object Raises: A InvalidCollocationData Error if the dataset did not pass the test. """ mandatory_fields = ["Collocations/pairs", "Collocations/group"] for mandatory_field in mandatory_fields: if mandatory_field not in dataset.variables: raise InvalidCollocationData( f"Could not find the field '{mandatory_field}'!" )
[ "numpy.abs", "numpy.allclose", "traceback.format_tb", "collections.defaultdict", "gc.collect", "numpy.arange", "pandas.Grouper", "multiprocessing.Queue", "typhon.utils.timeutils.to_datetime", "typhon.geographical.GeoIndex", "pandas.DataFrame", "typhon.utils.timeutils.Timer", "xarray.merge", ...
[((515, 542), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (532, 542), False, 'import logging\n'), ((58781, 58798), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (58792, 58798), False, 'from collections import defaultdict\n'), ((3233, 3251), 'numpy.array', 'np.array', (['[[], []]'], {}), '([[], []])\n', (3241, 3251), True, 'import numpy as np\n'), ((3310, 3347), 'numpy.array', 'np.array', (['[]'], {'dtype': '"""timedelta64[ns]"""'}), "([], dtype='timedelta64[ns]')\n", (3318, 3347), True, 'import numpy as np\n'), ((3406, 3418), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (3414, 3418), True, 'import numpy as np\n'), ((8995, 9029), 'numpy.array_split', 'np.array_split', (['matches', 'processes'], {}), '(matches, processes)\n', (9009, 9029), True, 'import numpy as np\n'), ((9092, 9116), 'multiprocessing.Queue', 'Queue', ([], {'maxsize': 'processes'}), '(maxsize=processes)\n', (9097, 9116), False, 'from multiprocessing import Process, Queue\n'), ((9186, 9193), 'multiprocessing.Queue', 'Queue', ([], {}), '()\n', (9191, 9193), False, 'from multiprocessing import Process, Queue\n'), ((12535, 12584), 'datetime.timedelta', 'timedelta', ([], {'microseconds': 'elapsed_time.microseconds'}), '(microseconds=elapsed_time.microseconds)\n', (12544, 12584), False, 'from datetime import datetime, timedelta\n'), ((39148, 39174), 'pandas.Timedelta', 'pd.Timedelta', (['max_interval'], {}), '(max_interval)\n', (39160, 39174), True, 'import pandas as pd\n'), ((47368, 47380), 'xarray.Dataset', 'xr.Dataset', ([], {}), '()\n', (47378, 47380), True, 'import xarray as xr\n'), ((47809, 48051), 'xarray.DataArray', 'xr.DataArray', (['intervals'], {'dims': "('collocation',)", 'attrs': "{'max_interval': f'Max. interval in secs: {max_interval}', 'max_distance':\n f'Max. distance in kilometers: {max_distance}', 'primary': primary_name,\n 'secondary': secondary_name}"}), "(intervals, dims=('collocation',), attrs={'max_interval':\n f'Max. interval in secs: {max_interval}', 'max_distance':\n f'Max. distance in kilometers: {max_distance}', 'primary': primary_name,\n 'secondary': secondary_name})\n", (47821, 48051), True, 'import xarray as xr\n'), ((48185, 48450), 'xarray.DataArray', 'xr.DataArray', (['distances'], {'dims': "('collocation',)", 'attrs': "{'max_interval': f'Max. interval in secs: {max_interval}', 'max_distance':\n f'Max. distance in kilometers: {max_distance}', 'primary': primary_name,\n 'secondary': secondary_name, 'units': 'kilometers'}"}), "(distances, dims=('collocation',), attrs={'max_interval':\n f'Max. interval in secs: {max_interval}', 'max_distance':\n f'Max. distance in kilometers: {max_distance}', 'primary': primary_name,\n 'secondary': secondary_name, 'units': 'kilometers'})\n", (48197, 48450), True, 'import xarray as xr\n'), ((48596, 48796), 'xarray.DataArray', 'xr.DataArray', (['[primary_name, secondary_name]'], {'dims': "('group',)", 'attrs': "{'max_interval': f'Max. interval in secs: {max_interval}', 'max_distance':\n f'Max. distance in kilometers: {max_distance}'}"}), "([primary_name, secondary_name], dims=('group',), attrs={\n 'max_interval': f'Max. interval in secs: {max_interval}',\n 'max_distance': f'Max. distance in kilometers: {max_distance}'})\n", (48608, 48796), True, 'import xarray as xr\n'), ((48887, 48935), 'typhon.utils.add_xarray_groups', 'add_xarray_groups', (['output'], {'Collocations': 'metadata'}), '(output, Collocations=metadata)\n', (48904, 48935), False, 'from typhon.utils import add_xarray_groups, get_xarray_groups\n'), ((51789, 51810), 'numpy.hstack', 'np.hstack', (['pairs_list'], {}), '(pairs_list)\n', (51798, 51810), True, 'import numpy as np\n'), ((52001, 52026), 'numpy.hstack', 'np.hstack', (['distances_list'], {}), '(distances_list)\n', (52010, 52026), True, 'import numpy as np\n'), ((54535, 54579), 'typhon.geographical.GeoIndex', 'GeoIndex', (['lat', 'lon'], {'leaf_size': 'self.leaf_size'}), '(lat, lon, leaf_size=self.leaf_size)\n', (54543, 54579), False, 'from typhon.geographical import GeoIndex\n'), ((57823, 57868), 'typhon.geodesy.great_circle_distance', 'great_circle_distance', (['lat1', 'lon1', 'lat2', 'lon2'], {}), '(lat1, lon1, lat2, lon2)\n', (57844, 57868), False, 'from typhon.geodesy import great_circle_distance\n'), ((59414, 59464), 'xarray.concat', 'xr.concat', (['data_list'], {'dim': 'collocation_coord[group]'}), '(data_list, dim=collocation_coord[group])\n', (59423, 59464), True, 'import xarray as xr\n'), ((7903, 7921), 'typhon.utils.timeutils.to_datetime', 'to_datetime', (['start'], {}), '(start)\n', (7914, 7921), False, 'from typhon.utils.timeutils import to_datetime, to_timedelta, Timer\n'), ((8009, 8025), 'typhon.utils.timeutils.to_datetime', 'to_datetime', (['end'], {}), '(end)\n', (8020, 8025), False, 'from typhon.utils.timeutils import to_datetime, to_timedelta, Timer\n'), ((9717, 9874), 'multiprocessing.Process', 'Process', ([], {'target': 'Collocator._process_caller', 'args': '(self, results, errors, PROCESS_NAMES[i])', 'kwargs': "{**kwargs, 'matches': matches_chunk}", 'daemon': '(True)'}), "(target=Collocator._process_caller, args=(self, results, errors,\n PROCESS_NAMES[i]), kwargs={**kwargs, 'matches': matches_chunk}, daemon=True\n )\n", (9724, 9874), False, 'from multiprocessing import Process, Queue\n'), ((13033, 13083), 'datetime.timedelta', 'timedelta', ([], {'microseconds': 'expected_time.microseconds'}), '(microseconds=expected_time.microseconds)\n', (13042, 13083), False, 'from datetime import datetime, timedelta\n'), ((30859, 30907), 'typhon.utils.timeutils.to_timedelta', 'to_timedelta', (['max_interval'], {'numbers_as': '"""seconds"""'}), "(max_interval, numbers_as='seconds')\n", (30871, 30907), False, 'from typhon.utils.timeutils import to_datetime, to_timedelta, Timer\n'), ((31025, 31043), 'typhon.utils.timeutils.to_datetime', 'to_datetime', (['start'], {}), '(start)\n', (31036, 31043), False, 'from typhon.utils.timeutils import to_datetime, to_timedelta, Timer\n'), ((31091, 31107), 'typhon.utils.timeutils.to_datetime', 'to_datetime', (['end'], {}), '(end)\n', (31102, 31107), False, 'from typhon.utils.timeutils import to_datetime, to_timedelta, Timer\n'), ((44419, 44447), 'pandas.unique', 'pd.unique', (['original_pairs[i]'], {}), '(original_pairs[i])\n', (44428, 44447), True, 'import pandas as pd\n'), ((44765, 44797), 'numpy.arange', 'np.arange', (['original_indices.size'], {}), '(original_indices.size)\n', (44774, 44797), True, 'import numpy as np\n'), ((46420, 46463), 'numpy.arange', 'np.arange', (["output[name]['collocation'].size"], {}), "(output[name]['collocation'].size)\n", (46429, 46463), True, 'import numpy as np\n'), ((47222, 47234), 'xarray.Dataset', 'xr.Dataset', ([], {}), '()\n', (47232, 47234), True, 'import xarray as xr\n'), ((47435, 47461), 'numpy.array', 'np.array', (['pairs'], {'dtype': 'int'}), '(pairs, dtype=int)\n', (47443, 47461), True, 'import numpy as np\n'), ((7347, 7354), 'typhon.utils.timeutils.Timer', 'Timer', ([], {}), '()\n', (7352, 7354), False, 'from typhon.utils.timeutils import to_datetime, to_timedelta, Timer\n'), ((11957, 11969), 'gc.collect', 'gc.collect', ([], {}), '()\n', (11967, 11969), False, 'import gc\n'), ((31766, 31773), 'typhon.utils.timeutils.Timer', 'Timer', ([], {}), '()\n', (31771, 31773), False, 'from typhon.utils.timeutils import to_datetime, to_timedelta, Timer\n'), ((32580, 32608), 'numpy.arange', 'np.arange', (['primary.time.size'], {}), '(primary.time.size)\n', (32589, 32608), True, 'import numpy as np\n'), ((32633, 32663), 'numpy.arange', 'np.arange', (['secondary.time.size'], {}), '(secondary.time.size)\n', (32642, 32663), True, 'import numpy as np\n'), ((38805, 38812), 'typhon.utils.timeutils.Timer', 'Timer', ([], {}), '()\n', (38810, 38812), False, 'from typhon.utils.timeutils import to_datetime, to_timedelta, Timer\n'), ((46669, 46712), 'xarray.merge', 'xr.merge', (['[output[name], stacked_dims_data]'], {}), '([output[name], stacked_dims_data])\n', (46677, 46712), True, 'import xarray as xr\n'), ((49571, 49592), 'pandas.DataFrame', 'pd.DataFrame', (['primary'], {}), '(primary)\n', (49583, 49592), True, 'import pandas as pd\n'), ((49631, 49654), 'pandas.DataFrame', 'pd.DataFrame', (['secondary'], {}), '(secondary)\n', (49643, 49654), True, 'import pandas as pd\n'), ((51344, 51364), 'typhon.utils.timeutils.Timer', 'Timer', ([], {'verbose': '(False)'}), '(verbose=False)\n', (51349, 51364), False, 'from typhon.utils.timeutils import to_datetime, to_timedelta, Timer\n'), ((54808, 54840), 'numpy.allclose', 'np.allclose', (['lat', 'self.index.lat'], {}), '(lat, self.index.lat)\n', (54819, 54840), True, 'import numpy as np\n'), ((54864, 54896), 'numpy.allclose', 'np.allclose', (['lon', 'self.index.lon'], {}), '(lon, self.index.lon)\n', (54875, 54896), True, 'import numpy as np\n'), ((57692, 57713), 'numpy.abs', 'np.abs', (['(time1 - time2)'], {}), '(time1 - time2)\n', (57698, 57713), True, 'import numpy as np\n'), ((58855, 58877), 'typhon.utils.get_xarray_groups', 'get_xarray_groups', (['obj'], {}), '(obj)\n', (58872, 58877), False, 'from typhon.utils import add_xarray_groups, get_xarray_groups\n'), ((15932, 15977), 'typhon.utils.timeutils.to_datetime', 'to_datetime', (["collocations.attrs['start_time']"], {}), "(collocations.attrs['start_time'])\n", (15943, 15977), False, 'from typhon.utils.timeutils import to_datetime, to_timedelta, Timer\n'), ((18764, 18809), 'typhon.utils.timeutils.to_datetime', 'to_datetime', (["collocations.attrs['start_time']"], {}), "(collocations.attrs['start_time'])\n", (18775, 18809), False, 'from typhon.utils.timeutils import to_datetime, to_timedelta, Timer\n'), ((18828, 18871), 'typhon.utils.timeutils.to_datetime', 'to_datetime', (["collocations.attrs['end_time']"], {}), "(collocations.attrs['end_time'])\n", (18839, 18871), False, 'from typhon.utils.timeutils import to_datetime, to_timedelta, Timer\n'), ((37059, 37066), 'typhon.utils.timeutils.Timer', 'Timer', ([], {}), '()\n', (37064, 37066), False, 'from typhon.utils.timeutils import to_datetime, to_timedelta, Timer\n'), ((41996, 42032), 'numpy.arange', 'np.arange', (['data[shared_dims[0]].size'], {}), '(data[shared_dims[0]].size)\n', (42005, 42032), True, 'import numpy as np\n'), ((43051, 43076), 'numpy.arange', 'np.arange', (['data.dims[dim]'], {}), '(data.dims[dim])\n', (43060, 43076), True, 'import numpy as np\n'), ((50615, 50644), 'pandas.Grouper', 'pd.Grouper', ([], {'freq': 'bin_duration'}), '(freq=bin_duration)\n', (50625, 50644), True, 'import pandas as pd\n'), ((12307, 12336), 'traceback.format_tb', 'traceback.format_tb', (['error[1]'], {}), '(error[1])\n', (12326, 12336), False, 'import traceback\n'), ((45818, 45888), 'xarray.DataArray', 'xr.DataArray', (['output[name][dim].values'], {'name': 'dim', 'dims': "['collocation']"}), "(output[name][dim].values, name=dim, dims=['collocation'])\n", (45830, 45888), True, 'import xarray as xr\n'), ((39934, 39961), 'numpy.datetime64', 'np.datetime64', (['common_start'], {}), '(common_start)\n', (39947, 39961), True, 'import numpy as np\n'), ((40001, 40026), 'numpy.datetime64', 'np.datetime64', (['common_end'], {}), '(common_end)\n', (40014, 40026), True, 'import numpy as np\n'), ((40155, 40182), 'numpy.datetime64', 'np.datetime64', (['common_start'], {}), '(common_start)\n', (40168, 40182), True, 'import numpy as np\n'), ((40224, 40249), 'numpy.datetime64', 'np.datetime64', (['common_end'], {}), '(common_end)\n', (40237, 40249), True, 'import numpy as np\n'), ((16832, 16877), 'typhon.utils.timeutils.to_datetime', 'to_datetime', (["collocations.attrs['start_time']"], {}), "(collocations.attrs['start_time'])\n", (16843, 16877), False, 'from typhon.utils.timeutils import to_datetime, to_timedelta, Timer\n')]
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Implementation of the GraySynth algorithm for synthesizing CNOT-Phase circuits with efficient CNOT cost, and the Patel-Hayes-Markov algorithm for optimal synthesis of linear (CNOT-only) reversible circuits. """ import copy import numpy as np from qiskit.circuit import QuantumCircuit from qiskit.exceptions import QiskitError def graysynth(cnots, angles, section_size=2): """This function is an implementation of the GraySynth algorithm. GraySynth is a heuristic algorithm for synthesizing small parity networks. It is inspired by Gray codes. Given a set of binary strings S (called "cnots" bellow), the algorithm synthesizes a parity network for S by repeatedly choosing an index i to expand and then effectively recursing on the co-factors S_0 and S_1, consisting of the strings y in S, with y_i = 0 or 1 respectively. As a subset S is recursively expanded, CNOT gates are applied so that a designated target bit contains the (partial) parity ksi_y(x) where y_i = 1 if and only if y'_i = 1 for for all y' in S. If S is a singleton {y'}, then y = y', hence the target bit contains the value ksi_y'(x) as desired. Notably, rather than uncomputing this sequence of CNOT gates when a subset S is finished being synthesized, the algorithm maintains the invariant that the remaining parities to be computed are expressed over the current state of bits. This allows the algorithm to avoid the 'backtracking' inherent in uncomputing-based methods. The algorithm is described in detail in the following paper in section 4: "On the controlled-NOT complexity of controlled-NOT–phase circuits." Amy, Matthew, <NAME>, and <NAME>. Quantum Science and Technology 4.1 (2018): 015002. Args: cnots (list[list]): a matrix whose columns are the parities to be synthesized e.g.:: [[0, 1, 1, 1, 1, 1], [1, 0, 0, 1, 1, 1], [1, 0, 0, 1, 0, 0], [0, 0, 1, 0, 1, 0]] corresponds to:: x1^x2 + x0 + x0^x3 + x0^x1^x2 + x0^x1^x3 + x0^x1 angles (list): a list containing all the phase-shift gates which are to be applied, in the same order as in "cnots". A number is interpreted as the angle of u1(angle), otherwise the elements have to be 't', 'tdg', 's', 'sdg' or 'z'. section_size (int): the size of every section, used in _lwr_cnot_synth(), in the Patel–Markov–Hayes algorithm. section_size must be a factor of n_qubits. Returns: QuantumCircuit: the quantum circuit Raises: QiskitError: when dimensions of cnots and angles don't align """ n_qubits = len(cnots) # Create a quantum circuit on n_qubits qcir = QuantumCircuit(n_qubits) if len(cnots[0]) != len(angles): raise QiskitError('Size of "cnots" and "angles" do not match.') range_list = list(range(n_qubits)) epsilon = n_qubits sta = [] cnots_copy = np.transpose(np.array(copy.deepcopy(cnots))) state = np.eye(n_qubits).astype('int') # This matrix keeps track of the state in the algorithm # Check if some phase-shift gates can be applied, before adding any C-NOT gates for qubit in range(n_qubits): index = 0 for icnots in cnots_copy: if np.array_equal(icnots, state[qubit]): if angles[index] == 't': qcir.t(qubit) elif angles[index] == 'tdg': qcir.tdg(qubit) elif angles[index] == 's': qcir.s(qubit) elif angles[index] == 'sdg': qcir.sdg(qubit) elif angles[index] == 'z': qcir.z(qubit) else: qcir.u1(angles[index] % np.pi, qubit) del angles[index] cnots_copy = np.delete(cnots_copy, index, axis=0) if index == len(cnots_copy): break index -= 1 index += 1 # Implementation of the pseudo-code (Algorithm 1) in the aforementioned paper sta.append([cnots, range_list, epsilon]) while sta != []: [cnots, ilist, qubit] = sta.pop() if cnots == []: continue elif 0 <= qubit < n_qubits: condition = True while condition: condition = False for j in range(n_qubits): if (j != qubit) and (sum(cnots[j]) == len(cnots[j])): condition = True qcir.cx(j, qubit) state[qubit] ^= state[j] index = 0 for icnots in cnots_copy: if np.array_equal(icnots, state[qubit]): if angles[index] == 't': qcir.t(qubit) elif angles[index] == 'tdg': qcir.tdg(qubit) elif angles[index] == 's': qcir.s(qubit) elif angles[index] == 'sdg': qcir.sdg(qubit) elif angles[index] == 'z': qcir.z(qubit) else: qcir.u1(angles[index] % np.pi, qubit) del angles[index] cnots_copy = np.delete(cnots_copy, index, axis=0) if index == len(cnots_copy): break index -= 1 index += 1 for x in _remove_duplicates(sta + [[cnots, ilist, qubit]]): [cnotsp, _, _] = x if cnotsp == []: continue for ttt in range(len(cnotsp[j])): cnotsp[j][ttt] ^= cnotsp[qubit][ttt] if ilist == []: continue # See line 18 in pseudo-code of Algorithm 1 in the aforementioned paper # this choice of j maximizes the size of the largest subset (S_0 or S_1) # and the larger a subset, the closer it gets to the ideal in the # Gray code of one CNOT per string. j = ilist[np.argmax([[max(row.count(0), row.count(1)) for row in cnots][k] for k in ilist])] cnots0 = [] cnots1 = [] for y in list(map(list, zip(*cnots))): if y[j] == 0: cnots0.append(y) elif y[j] == 1: cnots1.append(y) cnots0 = list(map(list, zip(*cnots0))) cnots1 = list(map(list, zip(*cnots1))) if qubit == epsilon: sta.append([cnots1, list(set(ilist).difference([j])), j]) else: sta.append([cnots1, list(set(ilist).difference([j])), qubit]) sta.append([cnots0, list(set(ilist).difference([j])), qubit]) qcir += cnot_synth(state, section_size) return qcir def cnot_synth(state, section_size=2): """ This function is an implementation of the Patel–Markov–Hayes algorithm for optimal synthesis of linear reversible circuits, as specified by an n x n matrix. The algorithm is described in detail in the following paper: "Optimal synthesis of linear reversible circuits." Patel, <NAME>., <NAME>, and <NAME>. Quantum Information & Computation 8.3 (2008): 282-294. Args: state (list[list] or ndarray): n x n matrix, describing the state of the input circuit section_size (int): the size of each section, used in _lwr_cnot_synth(), in the Patel–Markov–Hayes algorithm. section_size must be a factor of n_qubits. Returns: QuantumCircuit: a CNOT-only circuit implementing the desired linear transformation Raises: QiskitError: when variable "state" isn't of type numpy.matrix """ if not isinstance(state, (list, np.ndarray)): raise QiskitError('state should be of type list or numpy.ndarray, ' 'but was of the type {}'.format(type(state))) state = np.array(state) # Synthesize lower triangular part [state, circuit_l] = _lwr_cnot_synth(state, section_size) state = np.transpose(state) # Synthesize upper triangular part [state, circuit_u] = _lwr_cnot_synth(state, section_size) circuit_l.reverse() for i in circuit_u: i.reverse() # Convert the list into a circuit of C-NOT gates circ = QuantumCircuit(state.shape[0]) for i in circuit_u + circuit_l: circ.cx(i[0], i[1]) return circ def _lwr_cnot_synth(state, section_size): """ This function is a helper function of the algorithm for optimal synthesis of linear reversible circuits (the Patel–Markov–Hayes algorithm). It works like gaussian elimination, except that it works a lot faster, and requires fewer steps (and therefore fewer CNOTs). It takes the matrix "state" and splits it into sections of size section_size. Then it eliminates all non-zero sub-rows within each section, which are the same as a non-zero sub-row above. Once this has been done, it continues with normal gaussian elimination. The benefit is that with small section sizes (m), most of the sub-rows will be cleared in the first step, resulting in a factor m fewer row row operations during Gaussian elimination. The algorithm is described in detail in the following paper "Optimal synthesis of linear reversible circuits." Patel, <NAME>., <NAME>, and <NAME>. Quantum Information & Computation 8.3 (2008): 282-294. Args: state (ndarray): n x n matrix, describing a linear quantum circuit section_size (int): the section size the matrix columns are divided into Returns: numpy.matrix: n by n matrix, describing the state of the output circuit list: a k by 2 list of C-NOT operations that need to be applied """ circuit = [] n_qubits = state.shape[0] # If the matrix is already an upper triangular one, # there is no need for any transformations if np.allclose(state, np.triu(state)): return [state, circuit] # Iterate over column sections for sec in range(1, int(np.ceil(n_qubits/section_size)+1)): # Remove duplicate sub-rows in section sec patt = {} for row in range((sec-1)*section_size, n_qubits): sub_row_patt = copy.deepcopy(state[row, (sec-1)*section_size:sec*section_size]) if np.sum(sub_row_patt) == 0: continue if str(sub_row_patt) not in patt: patt[str(sub_row_patt)] = row else: state[row, :] ^= state[patt[str(sub_row_patt)], :] circuit.append([patt[str(sub_row_patt)], row]) # Use gaussian elimination for remaining entries in column section for col in range((sec-1)*section_size, sec*section_size): # Check if 1 on diagonal diag_one = 1 if state[col, col] == 0: diag_one = 0 # Remove ones in rows below column col for row in range(col+1, n_qubits): if state[row, col] == 1: if diag_one == 0: state[col, :] ^= state[row, :] circuit.append([row, col]) diag_one = 1 state[row, :] ^= state[col, :] circuit.append([col, row]) return [state, circuit] def _remove_duplicates(lists): """ Remove duplicates in list Args: lists (list): a list which may contain duplicate elements. Returns: list: a list which contains only unique elements. """ unique_list = [] for element in lists: if element not in unique_list: unique_list.append(element) return unique_list
[ "copy.deepcopy", "numpy.triu", "numpy.ceil", "numpy.sum", "qiskit.exceptions.QiskitError", "numpy.transpose", "qiskit.circuit.QuantumCircuit", "numpy.array", "numpy.array_equal", "numpy.eye", "numpy.delete" ]
[((3313, 3337), 'qiskit.circuit.QuantumCircuit', 'QuantumCircuit', (['n_qubits'], {}), '(n_qubits)\n', (3327, 3337), False, 'from qiskit.circuit import QuantumCircuit\n'), ((8885, 8900), 'numpy.array', 'np.array', (['state'], {}), '(state)\n', (8893, 8900), True, 'import numpy as np\n'), ((9014, 9033), 'numpy.transpose', 'np.transpose', (['state'], {}), '(state)\n', (9026, 9033), True, 'import numpy as np\n'), ((9267, 9297), 'qiskit.circuit.QuantumCircuit', 'QuantumCircuit', (['state.shape[0]'], {}), '(state.shape[0])\n', (9281, 9297), False, 'from qiskit.circuit import QuantumCircuit\n'), ((3390, 3447), 'qiskit.exceptions.QiskitError', 'QiskitError', (['"""Size of "cnots" and "angles" do not match."""'], {}), '(\'Size of "cnots" and "angles" do not match.\')\n', (3401, 3447), False, 'from qiskit.exceptions import QiskitError\n'), ((10916, 10930), 'numpy.triu', 'np.triu', (['state'], {}), '(state)\n', (10923, 10930), True, 'import numpy as np\n'), ((3563, 3583), 'copy.deepcopy', 'copy.deepcopy', (['cnots'], {}), '(cnots)\n', (3576, 3583), False, 'import copy\n'), ((3598, 3614), 'numpy.eye', 'np.eye', (['n_qubits'], {}), '(n_qubits)\n', (3604, 3614), True, 'import numpy as np\n'), ((3872, 3908), 'numpy.array_equal', 'np.array_equal', (['icnots', 'state[qubit]'], {}), '(icnots, state[qubit])\n', (3886, 3908), True, 'import numpy as np\n'), ((11218, 11288), 'copy.deepcopy', 'copy.deepcopy', (['state[row, (sec - 1) * section_size:sec * section_size]'], {}), '(state[row, (sec - 1) * section_size:sec * section_size])\n', (11231, 11288), False, 'import copy\n'), ((4444, 4480), 'numpy.delete', 'np.delete', (['cnots_copy', 'index'], {'axis': '(0)'}), '(cnots_copy, index, axis=0)\n', (4453, 4480), True, 'import numpy as np\n'), ((11028, 11060), 'numpy.ceil', 'np.ceil', (['(n_qubits / section_size)'], {}), '(n_qubits / section_size)\n', (11035, 11060), True, 'import numpy as np\n'), ((11298, 11318), 'numpy.sum', 'np.sum', (['sub_row_patt'], {}), '(sub_row_patt)\n', (11304, 11318), True, 'import numpy as np\n'), ((5329, 5365), 'numpy.array_equal', 'np.array_equal', (['icnots', 'state[qubit]'], {}), '(icnots, state[qubit])\n', (5343, 5365), True, 'import numpy as np\n'), ((6125, 6161), 'numpy.delete', 'np.delete', (['cnots_copy', 'index'], {'axis': '(0)'}), '(cnots_copy, index, axis=0)\n', (6134, 6161), True, 'import numpy as np\n')]
import argparse import os import numpy as np import tensorflow as tf import tqdm import yaml from mixmatch import mixmatch_ot,mixmatch, semi_loss,linear_rampup,interleave,weight_decay,ema from model import WideResNet from preprocess import fetch_dataset config = tf.compat.v1.ConfigProto() config.gpu_options.allow_growth = True session = tf.compat.v1.InteractiveSession(config=config) def get_args(): parser = argparse.ArgumentParser('parameters') parser.add_argument('--seed', type=int, default=None, help='seed for repeatable results') parser.add_argument('--dataset', type=str, default='svhn', help='dataset used for training (e.g. cifar10, cifar100, svhn, svhn+extra)') parser.add_argument('--epochs', type=int, default=1024, help='number of epochs, (default: 1024)') parser.add_argument('--batch-size', type=int, default=64, help='examples per batch (default: 64)') parser.add_argument('--learning-rate', type=float, default=1e-2, help='learning_rate, (default: 0.01)') parser.add_argument('--labelled-examples', type=int, default=4000, help='number labelled examples (default: 4000') parser.add_argument('--validation-examples', type=int, default=5000, help='number validation examples (default: 5000') parser.add_argument('--val-iteration', type=int, default=1024, help='number of iterations before validation (default: 1024)') parser.add_argument('--T', type=float, default=0.5, help='temperature sharpening ratio (default: 0.5)') parser.add_argument('--K', type=int, default=2, help='number of rounds of augmentation (default: 2)') parser.add_argument('--alpha', type=float, default=0.75, help='param for sampling from Beta distribution (default: 0.75)') parser.add_argument('--lambda-u', type=int, default=100, help='multiplier for unlabelled loss (default: 100)') parser.add_argument('--rampup-length', type=int, default=16, help='rampup length for unlabelled loss multiplier (default: 16)') parser.add_argument('--weight-decay', type=float, default=0.02, help='decay rate for model vars (default: 0.02)') parser.add_argument('--ema-decay', type=float, default=0.999, help='ema decay for ema model vars (default: 0.999)') parser.add_argument('--config-path', type=str, default=None, help='path to yaml config file, overwrites args') parser.add_argument('--tensorboard', action='store_true', help='enable tensorboard visualization') parser.add_argument('--resume', action='store_true', help='whether to restore from previous training runs') return parser.parse_args() def load_config(args): dir_path = os.path.dirname(os.path.realpath(__file__)) config_path = os.path.join(dir_path, args['config_path']) with open(config_path, 'r') as config_file: config = yaml.load(config_file, Loader=yaml.FullLoader) for key in args.keys(): if key in config.keys(): args[key] = config[key] return args def main(): args = vars(get_args()) dir_path = os.path.dirname(os.path.realpath(__file__)) if args['config_path'] is not None and os.path.exists(os.path.join(dir_path, args['config_path'])): args = load_config(args) start_epoch = 0 log_path = f'./logs/ot/{args["dataset"]}@{args["labelled_examples"]}' ckpt_dir = f'{log_path}/checkpoints' #load the corresponding ground metric for OT groundmetric_path = "./groundmetrics/nm-"+args['dataset']+".npy" groundmetric = np.load(groundmetric_path) datasetX, datasetU, val_dataset, test_dataset, num_classes = fetch_dataset(args, log_path) model = WideResNet(num_classes, depth=28, width=2) model.build(input_shape=(None, 32, 32, 3)) optimizer = tf.keras.optimizers.Adam(lr=args['learning_rate']) model_ckpt = tf.train.Checkpoint(step=tf.Variable(0), optimizer=optimizer, net=model) manager = tf.train.CheckpointManager(model_ckpt, f'{ckpt_dir}/model', max_to_keep=3) ema_model = WideResNet(num_classes, depth=28, width=2) ema_model.build(input_shape=(None, 32, 32, 3)) ema_model.set_weights(model.get_weights()) ema_ckpt = tf.train.Checkpoint(step=tf.Variable(0), net=ema_model) ema_manager = tf.train.CheckpointManager(ema_ckpt, f'{ckpt_dir}/ema', max_to_keep=3) if args['resume']: model_ckpt.restore(manager.latest_checkpoint) ema_ckpt.restore(manager.latest_checkpoint) model_ckpt.step.assign_add(1) ema_ckpt.step.assign_add(1) start_epoch = int(model_ckpt.step) print(f'Restored @ epoch {start_epoch} from {manager.latest_checkpoint} and {ema_manager.latest_checkpoint}') train_writer = None if args['tensorboard']: train_writer = tf.summary.create_file_writer(f'{log_path}/train') val_writer = tf.summary.create_file_writer(f'{log_path}/validation') test_writer = tf.summary.create_file_writer(f'{log_path}/test') # assigning args used in functions wrapped with tf.function to tf.constant/tf.Variable to avoid memory leaks args['T'] = tf.constant(args['T']) args['beta'] = tf.Variable(0., shape=()) for epoch in range(start_epoch, args['epochs']): xe_loss, l2u_loss, total_loss, accuracy = train(datasetX, datasetU, model, ema_model, optimizer, epoch, args,groundmetric) val_xe_loss, val_accuracy = validate(val_dataset, ema_model, epoch, args, split='Validation') test_xe_loss, test_accuracy = validate(test_dataset, ema_model, epoch, args, split='Test') if (epoch - start_epoch) % 16 == 0: model_save_path = manager.save(checkpoint_number=int(model_ckpt.step)) ema_save_path = ema_manager.save(checkpoint_number=int(ema_ckpt.step)) print(f'Saved model checkpoint for epoch {int(model_ckpt.step)} @ {model_save_path}') print(f'Saved ema checkpoint for epoch {int(ema_ckpt.step)} @ {ema_save_path}') model_ckpt.step.assign_add(1) ema_ckpt.step.assign_add(1) step = args['val_iteration'] * (epoch + 1) if args['tensorboard']: with train_writer.as_default(): tf.summary.scalar('xe_loss', xe_loss.result(), step=step) tf.summary.scalar('l2u_loss', l2u_loss.result(), step=step) tf.summary.scalar('total_loss', total_loss.result(), step=step) tf.summary.scalar('accuracy', accuracy.result(), step=step) with val_writer.as_default(): tf.summary.scalar('xe_loss', val_xe_loss.result(), step=step) tf.summary.scalar('accuracy', val_accuracy.result(), step=step) with test_writer.as_default(): tf.summary.scalar('xe_loss', test_xe_loss.result(), step=step) tf.summary.scalar('accuracy', test_accuracy.result(), step=step) if args['tensorboard']: for writer in [train_writer, val_writer, test_writer]: writer.flush() def train(datasetX, datasetU, model, ema_model, optimizer, epoch, args, M,eps=None,niter=200,tol=1e-7): """ niter is for IBP ; groundcost is M, tol for convergance of IBP; eps = regularisation for IBP """ xe_loss_avg = tf.keras.metrics.Mean() l2u_loss_avg = tf.keras.metrics.Mean() total_loss_avg = tf.keras.metrics.Mean() accuracy = tf.keras.metrics.SparseCategoricalAccuracy() shuffle_and_batch = lambda dataset: dataset.shuffle(buffer_size=int(1e6)).batch(batch_size=args['batch_size'], drop_remainder=True) iteratorX = iter(shuffle_and_batch(datasetX)) iteratorU = iter(shuffle_and_batch(datasetU)) progress_bar = tqdm.tqdm(range(args['val_iteration']), unit='batch') for batch_num in progress_bar: lambda_u = args['lambda_u'] * linear_rampup(epoch + batch_num/args['val_iteration'], args['rampup_length']) try: batchX = next(iteratorX) except: iteratorX = iter(shuffle_and_batch(datasetX)) batchX = next(iteratorX) try: batchU = next(iteratorU) except: iteratorU = iter(shuffle_and_batch(datasetU)) batchU = next(iteratorU) args['beta'].assign(np.random.beta(args['alpha'], args['alpha'])) # run mixmatch XU, XUy = mixmatch_ot(model, batchX['image'], batchX['label'], batchU['image'], args['T'], args['K'], args['beta'], M,eps=eps,niter=niter,tol=tol) with tf.GradientTape() as tape: logits = [model(XU[0])] for batch in XU[1:]: logits.append(model(batch)) logits = interleave(logits, args['batch_size']) logits_x = logits[0] logits_u = tf.concat(logits[1:], axis=0) # compute loss xe_loss, l2u_loss = semi_loss(XUy[:args['batch_size']], logits_x, XUy[args['batch_size']:], logits_u) total_loss = xe_loss + lambda_u * l2u_loss # compute gradients and run optimizer step grads = tape.gradient(total_loss, model.trainable_variables) optimizer.apply_gradients(zip(grads, model.trainable_variables)) ema(model, ema_model, args['ema_decay']) weight_decay(model=model, decay_rate=args['weight_decay'] * args['learning_rate']) xe_loss_avg(xe_loss) l2u_loss_avg(l2u_loss) total_loss_avg(total_loss) accuracy(tf.argmax(batchX['label'], axis=1, output_type=tf.int32), model(tf.cast(batchX['image'], dtype=tf.float32), training=False)) progress_bar.set_postfix({ 'XE Loss': f'{xe_loss_avg.result():.4f}', 'L2U Loss': f'{l2u_loss_avg.result():.4f}', 'WeightU': f'{lambda_u:.3f}', 'Total Loss': f'{total_loss_avg.result():.4f}', 'Accuracy': f'{accuracy.result():.3%}' }) return xe_loss_avg, l2u_loss_avg, total_loss_avg, accuracy def validate(dataset, model, epoch, args, split): accuracy = tf.keras.metrics.Accuracy() xe_avg = tf.keras.metrics.Mean() dataset = dataset.batch(args['batch_size']) for batch in dataset: logits = model(batch['image'], training=False) xe_loss = tf.nn.softmax_cross_entropy_with_logits(labels=batch['label'], logits=logits) xe_avg(xe_loss) prediction = tf.argmax(logits, axis=1, output_type=tf.int32) accuracy(prediction, tf.argmax(batch['label'], axis=1, output_type=tf.int32)) print(f'Epoch {epoch:04d}: {split} XE Loss: {xe_avg.result():.4f}, {split} Accuracy: {accuracy.result():.3%}') return xe_avg, accuracy if __name__ == '__main__': main()
[ "numpy.load", "yaml.load", "mixmatch.linear_rampup", "argparse.ArgumentParser", "tensorflow.compat.v1.InteractiveSession", "tensorflow.keras.metrics.Mean", "tensorflow.Variable", "os.path.join", "mixmatch.interleave", "tensorflow.nn.softmax_cross_entropy_with_logits", "mixmatch.ema", "tensorfl...
[((266, 292), 'tensorflow.compat.v1.ConfigProto', 'tf.compat.v1.ConfigProto', ([], {}), '()\n', (290, 292), True, 'import tensorflow as tf\n'), ((342, 388), 'tensorflow.compat.v1.InteractiveSession', 'tf.compat.v1.InteractiveSession', ([], {'config': 'config'}), '(config=config)\n', (373, 388), True, 'import tensorflow as tf\n'), ((420, 457), 'argparse.ArgumentParser', 'argparse.ArgumentParser', (['"""parameters"""'], {}), "('parameters')\n", (443, 457), False, 'import argparse\n'), ((2744, 2787), 'os.path.join', 'os.path.join', (['dir_path', "args['config_path']"], {}), "(dir_path, args['config_path'])\n", (2756, 2787), False, 'import os\n'), ((3525, 3551), 'numpy.load', 'np.load', (['groundmetric_path'], {}), '(groundmetric_path)\n', (3532, 3551), True, 'import numpy as np\n'), ((3618, 3647), 'preprocess.fetch_dataset', 'fetch_dataset', (['args', 'log_path'], {}), '(args, log_path)\n', (3631, 3647), False, 'from preprocess import fetch_dataset\n'), ((3661, 3703), 'model.WideResNet', 'WideResNet', (['num_classes'], {'depth': '(28)', 'width': '(2)'}), '(num_classes, depth=28, width=2)\n', (3671, 3703), False, 'from model import WideResNet\n'), ((3767, 3817), 'tensorflow.keras.optimizers.Adam', 'tf.keras.optimizers.Adam', ([], {'lr': "args['learning_rate']"}), "(lr=args['learning_rate'])\n", (3791, 3817), True, 'import tensorflow as tf\n'), ((3922, 3996), 'tensorflow.train.CheckpointManager', 'tf.train.CheckpointManager', (['model_ckpt', 'f"""{ckpt_dir}/model"""'], {'max_to_keep': '(3)'}), "(model_ckpt, f'{ckpt_dir}/model', max_to_keep=3)\n", (3948, 3996), True, 'import tensorflow as tf\n'), ((4014, 4056), 'model.WideResNet', 'WideResNet', (['num_classes'], {'depth': '(28)', 'width': '(2)'}), '(num_classes, depth=28, width=2)\n', (4024, 4056), False, 'from model import WideResNet\n'), ((4244, 4314), 'tensorflow.train.CheckpointManager', 'tf.train.CheckpointManager', (['ema_ckpt', 'f"""{ckpt_dir}/ema"""'], {'max_to_keep': '(3)'}), "(ema_ckpt, f'{ckpt_dir}/ema', max_to_keep=3)\n", (4270, 4314), True, 'import tensorflow as tf\n'), ((5086, 5108), 'tensorflow.constant', 'tf.constant', (["args['T']"], {}), "(args['T'])\n", (5097, 5108), True, 'import tensorflow as tf\n'), ((5128, 5154), 'tensorflow.Variable', 'tf.Variable', (['(0.0)'], {'shape': '()'}), '(0.0, shape=())\n', (5139, 5154), True, 'import tensorflow as tf\n'), ((7236, 7259), 'tensorflow.keras.metrics.Mean', 'tf.keras.metrics.Mean', ([], {}), '()\n', (7257, 7259), True, 'import tensorflow as tf\n'), ((7279, 7302), 'tensorflow.keras.metrics.Mean', 'tf.keras.metrics.Mean', ([], {}), '()\n', (7300, 7302), True, 'import tensorflow as tf\n'), ((7324, 7347), 'tensorflow.keras.metrics.Mean', 'tf.keras.metrics.Mean', ([], {}), '()\n', (7345, 7347), True, 'import tensorflow as tf\n'), ((7363, 7407), 'tensorflow.keras.metrics.SparseCategoricalAccuracy', 'tf.keras.metrics.SparseCategoricalAccuracy', ([], {}), '()\n', (7405, 7407), True, 'import tensorflow as tf\n'), ((9966, 9993), 'tensorflow.keras.metrics.Accuracy', 'tf.keras.metrics.Accuracy', ([], {}), '()\n', (9991, 9993), True, 'import tensorflow as tf\n'), ((10007, 10030), 'tensorflow.keras.metrics.Mean', 'tf.keras.metrics.Mean', ([], {}), '()\n', (10028, 10030), True, 'import tensorflow as tf\n'), ((2698, 2724), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (2714, 2724), False, 'import os\n'), ((2853, 2899), 'yaml.load', 'yaml.load', (['config_file'], {'Loader': 'yaml.FullLoader'}), '(config_file, Loader=yaml.FullLoader)\n', (2862, 2899), False, 'import yaml\n'), ((3086, 3112), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (3102, 3112), False, 'import os\n'), ((4756, 4806), 'tensorflow.summary.create_file_writer', 'tf.summary.create_file_writer', (['f"""{log_path}/train"""'], {}), "(f'{log_path}/train')\n", (4785, 4806), True, 'import tensorflow as tf\n'), ((4828, 4883), 'tensorflow.summary.create_file_writer', 'tf.summary.create_file_writer', (['f"""{log_path}/validation"""'], {}), "(f'{log_path}/validation')\n", (4857, 4883), True, 'import tensorflow as tf\n'), ((4906, 4955), 'tensorflow.summary.create_file_writer', 'tf.summary.create_file_writer', (['f"""{log_path}/test"""'], {}), "(f'{log_path}/test')\n", (4935, 4955), True, 'import tensorflow as tf\n'), ((8309, 8453), 'mixmatch.mixmatch_ot', 'mixmatch_ot', (['model', "batchX['image']", "batchX['label']", "batchU['image']", "args['T']", "args['K']", "args['beta']", 'M'], {'eps': 'eps', 'niter': 'niter', 'tol': 'tol'}), "(model, batchX['image'], batchX['label'], batchU['image'], args[\n 'T'], args['K'], args['beta'], M, eps=eps, niter=niter, tol=tol)\n", (8320, 8453), False, 'from mixmatch import mixmatch_ot, mixmatch, semi_loss, linear_rampup, interleave, weight_decay, ema\n'), ((9156, 9196), 'mixmatch.ema', 'ema', (['model', 'ema_model', "args['ema_decay']"], {}), "(model, ema_model, args['ema_decay'])\n", (9159, 9196), False, 'from mixmatch import mixmatch_ot, mixmatch, semi_loss, linear_rampup, interleave, weight_decay, ema\n'), ((9205, 9292), 'mixmatch.weight_decay', 'weight_decay', ([], {'model': 'model', 'decay_rate': "(args['weight_decay'] * args['learning_rate'])"}), "(model=model, decay_rate=args['weight_decay'] * args[\n 'learning_rate'])\n", (9217, 9292), False, 'from mixmatch import mixmatch_ot, mixmatch, semi_loss, linear_rampup, interleave, weight_decay, ema\n'), ((10179, 10256), 'tensorflow.nn.softmax_cross_entropy_with_logits', 'tf.nn.softmax_cross_entropy_with_logits', ([], {'labels': "batch['label']", 'logits': 'logits'}), "(labels=batch['label'], logits=logits)\n", (10218, 10256), True, 'import tensorflow as tf\n'), ((10302, 10349), 'tensorflow.argmax', 'tf.argmax', (['logits'], {'axis': '(1)', 'output_type': 'tf.int32'}), '(logits, axis=1, output_type=tf.int32)\n', (10311, 10349), True, 'import tensorflow as tf\n'), ((3172, 3215), 'os.path.join', 'os.path.join', (['dir_path', "args['config_path']"], {}), "(dir_path, args['config_path'])\n", (3184, 3215), False, 'import os\n'), ((3860, 3874), 'tensorflow.Variable', 'tf.Variable', (['(0)'], {}), '(0)\n', (3871, 3874), True, 'import tensorflow as tf\n'), ((4195, 4209), 'tensorflow.Variable', 'tf.Variable', (['(0)'], {}), '(0)\n', (4206, 4209), True, 'import tensorflow as tf\n'), ((7793, 7872), 'mixmatch.linear_rampup', 'linear_rampup', (["(epoch + batch_num / args['val_iteration'])", "args['rampup_length']"], {}), "(epoch + batch_num / args['val_iteration'], args['rampup_length'])\n", (7806, 7872), False, 'from mixmatch import mixmatch_ot, mixmatch, semi_loss, linear_rampup, interleave, weight_decay, ema\n'), ((8222, 8266), 'numpy.random.beta', 'np.random.beta', (["args['alpha']", "args['alpha']"], {}), "(args['alpha'], args['alpha'])\n", (8236, 8266), True, 'import numpy as np\n'), ((8471, 8488), 'tensorflow.GradientTape', 'tf.GradientTape', ([], {}), '()\n', (8486, 8488), True, 'import tensorflow as tf\n'), ((8632, 8670), 'mixmatch.interleave', 'interleave', (['logits', "args['batch_size']"], {}), "(logits, args['batch_size'])\n", (8642, 8670), False, 'from mixmatch import mixmatch_ot, mixmatch, semi_loss, linear_rampup, interleave, weight_decay, ema\n'), ((8727, 8756), 'tensorflow.concat', 'tf.concat', (['logits[1:]'], {'axis': '(0)'}), '(logits[1:], axis=0)\n', (8736, 8756), True, 'import tensorflow as tf\n'), ((8817, 8902), 'mixmatch.semi_loss', 'semi_loss', (["XUy[:args['batch_size']]", 'logits_x', "XUy[args['batch_size']:]", 'logits_u'], {}), "(XUy[:args['batch_size']], logits_x, XUy[args['batch_size']:],\n logits_u)\n", (8826, 8902), False, 'from mixmatch import mixmatch_ot, mixmatch, semi_loss, linear_rampup, interleave, weight_decay, ema\n'), ((9401, 9457), 'tensorflow.argmax', 'tf.argmax', (["batchX['label']"], {'axis': '(1)', 'output_type': 'tf.int32'}), "(batchX['label'], axis=1, output_type=tf.int32)\n", (9410, 9457), True, 'import tensorflow as tf\n'), ((10379, 10434), 'tensorflow.argmax', 'tf.argmax', (["batch['label']"], {'axis': '(1)', 'output_type': 'tf.int32'}), "(batch['label'], axis=1, output_type=tf.int32)\n", (10388, 10434), True, 'import tensorflow as tf\n'), ((9465, 9507), 'tensorflow.cast', 'tf.cast', (["batchX['image']"], {'dtype': 'tf.float32'}), "(batchX['image'], dtype=tf.float32)\n", (9472, 9507), True, 'import tensorflow as tf\n')]
# Author: <NAME> <<EMAIL>> # # License: BSD (3-clause) import os.path as op import numpy as np from numpy.testing import assert_allclose from nose.tools import assert_raises, assert_equal, assert_true import warnings from mne.io import read_info, Raw from mne.io.chpi import _rot_to_quat, _quat_to_rot, get_chpi_positions from mne.utils import run_tests_if_main, _TempDir from mne.datasets import testing base_dir = op.join(op.dirname(__file__), '..', 'tests', 'data') test_fif_fname = op.join(base_dir, 'test_raw.fif') ctf_fname = op.join(base_dir, 'test_ctf_raw.fif') hp_fif_fname = op.join(base_dir, 'test_chpi_raw_sss.fif') hp_fname = op.join(base_dir, 'test_chpi_raw_hp.txt') data_path = testing.data_path(download=False) raw_fif_fname = op.join(data_path, 'SSS', 'test_move_anon_raw.fif') sss_fif_fname = op.join(data_path, 'SSS', 'test_move_anon_raw_sss.fif') warnings.simplefilter('always') def test_quaternions(): """Test quaternion calculations """ rots = [np.eye(3)] for fname in [test_fif_fname, ctf_fname, hp_fif_fname]: rots += [read_info(fname)['dev_head_t']['trans'][:3, :3]] for rot in rots: assert_allclose(rot, _quat_to_rot(_rot_to_quat(rot)), rtol=1e-5, atol=1e-5) rot = rot[np.newaxis, np.newaxis, :, :] assert_allclose(rot, _quat_to_rot(_rot_to_quat(rot)), rtol=1e-5, atol=1e-5) def test_get_chpi(): """Test CHPI position computation """ trans0, rot0 = get_chpi_positions(hp_fname)[:2] trans0, rot0 = trans0[:-1], rot0[:-1] raw = Raw(hp_fif_fname) out = get_chpi_positions(raw) trans1, rot1, t1 = out trans1, rot1 = trans1[2:], rot1[2:] # these will not be exact because they don't use equiv. time points assert_allclose(trans0, trans1, atol=1e-5, rtol=1e-1) assert_allclose(rot0, rot1, atol=1e-6, rtol=1e-1) # run through input checking assert_raises(TypeError, get_chpi_positions, 1) assert_raises(ValueError, get_chpi_positions, hp_fname, [1]) @testing.requires_testing_data def test_hpi_info(): """Test getting HPI info """ tempdir = _TempDir() temp_name = op.join(tempdir, 'temp_raw.fif') for fname in (raw_fif_fname, sss_fif_fname): with warnings.catch_warnings(record=True): warnings.simplefilter('always') raw = Raw(fname, allow_maxshield=True) assert_true(len(raw.info['hpi_subsystem']) > 0) raw.save(temp_name, overwrite=True) with warnings.catch_warnings(record=True): warnings.simplefilter('always') raw_2 = Raw(temp_name, allow_maxshield=True) assert_equal(len(raw_2.info['hpi_subsystem']), len(raw.info['hpi_subsystem'])) run_tests_if_main(False)
[ "warnings.simplefilter", "numpy.eye", "mne.utils._TempDir", "mne.io.Raw", "os.path.dirname", "mne.io.chpi._rot_to_quat", "mne.utils.run_tests_if_main", "mne.datasets.testing.data_path", "mne.io.chpi.get_chpi_positions", "warnings.catch_warnings", "nose.tools.assert_raises", "mne.io.read_info",...
[((489, 522), 'os.path.join', 'op.join', (['base_dir', '"""test_raw.fif"""'], {}), "(base_dir, 'test_raw.fif')\n", (496, 522), True, 'import os.path as op\n'), ((535, 572), 'os.path.join', 'op.join', (['base_dir', '"""test_ctf_raw.fif"""'], {}), "(base_dir, 'test_ctf_raw.fif')\n", (542, 572), True, 'import os.path as op\n'), ((588, 630), 'os.path.join', 'op.join', (['base_dir', '"""test_chpi_raw_sss.fif"""'], {}), "(base_dir, 'test_chpi_raw_sss.fif')\n", (595, 630), True, 'import os.path as op\n'), ((642, 683), 'os.path.join', 'op.join', (['base_dir', '"""test_chpi_raw_hp.txt"""'], {}), "(base_dir, 'test_chpi_raw_hp.txt')\n", (649, 683), True, 'import os.path as op\n'), ((697, 730), 'mne.datasets.testing.data_path', 'testing.data_path', ([], {'download': '(False)'}), '(download=False)\n', (714, 730), False, 'from mne.datasets import testing\n'), ((747, 798), 'os.path.join', 'op.join', (['data_path', '"""SSS"""', '"""test_move_anon_raw.fif"""'], {}), "(data_path, 'SSS', 'test_move_anon_raw.fif')\n", (754, 798), True, 'import os.path as op\n'), ((815, 870), 'os.path.join', 'op.join', (['data_path', '"""SSS"""', '"""test_move_anon_raw_sss.fif"""'], {}), "(data_path, 'SSS', 'test_move_anon_raw_sss.fif')\n", (822, 870), True, 'import os.path as op\n'), ((872, 903), 'warnings.simplefilter', 'warnings.simplefilter', (['"""always"""'], {}), "('always')\n", (893, 903), False, 'import warnings\n'), ((2755, 2779), 'mne.utils.run_tests_if_main', 'run_tests_if_main', (['(False)'], {}), '(False)\n', (2772, 2779), False, 'from mne.utils import run_tests_if_main, _TempDir\n'), ((427, 447), 'os.path.dirname', 'op.dirname', (['__file__'], {}), '(__file__)\n', (437, 447), True, 'import os.path as op\n'), ((1581, 1598), 'mne.io.Raw', 'Raw', (['hp_fif_fname'], {}), '(hp_fif_fname)\n', (1584, 1598), False, 'from mne.io import read_info, Raw\n'), ((1609, 1632), 'mne.io.chpi.get_chpi_positions', 'get_chpi_positions', (['raw'], {}), '(raw)\n', (1627, 1632), False, 'from mne.io.chpi import _rot_to_quat, _quat_to_rot, get_chpi_positions\n'), ((1776, 1829), 'numpy.testing.assert_allclose', 'assert_allclose', (['trans0', 'trans1'], {'atol': '(1e-05)', 'rtol': '(0.1)'}), '(trans0, trans1, atol=1e-05, rtol=0.1)\n', (1791, 1829), False, 'from numpy.testing import assert_allclose\n'), ((1834, 1883), 'numpy.testing.assert_allclose', 'assert_allclose', (['rot0', 'rot1'], {'atol': '(1e-06)', 'rtol': '(0.1)'}), '(rot0, rot1, atol=1e-06, rtol=0.1)\n', (1849, 1883), False, 'from numpy.testing import assert_allclose\n'), ((1921, 1968), 'nose.tools.assert_raises', 'assert_raises', (['TypeError', 'get_chpi_positions', '(1)'], {}), '(TypeError, get_chpi_positions, 1)\n', (1934, 1968), False, 'from nose.tools import assert_raises, assert_equal, assert_true\n'), ((1973, 2033), 'nose.tools.assert_raises', 'assert_raises', (['ValueError', 'get_chpi_positions', 'hp_fname', '[1]'], {}), '(ValueError, get_chpi_positions, hp_fname, [1])\n', (1986, 2033), False, 'from nose.tools import assert_raises, assert_equal, assert_true\n'), ((2139, 2149), 'mne.utils._TempDir', '_TempDir', ([], {}), '()\n', (2147, 2149), False, 'from mne.utils import run_tests_if_main, _TempDir\n'), ((2166, 2198), 'os.path.join', 'op.join', (['tempdir', '"""temp_raw.fif"""'], {}), "(tempdir, 'temp_raw.fif')\n", (2173, 2198), True, 'import os.path as op\n'), ((986, 995), 'numpy.eye', 'np.eye', (['(3)'], {}), '(3)\n', (992, 995), True, 'import numpy as np\n'), ((1496, 1524), 'mne.io.chpi.get_chpi_positions', 'get_chpi_positions', (['hp_fname'], {}), '(hp_fname)\n', (1514, 1524), False, 'from mne.io.chpi import _rot_to_quat, _quat_to_rot, get_chpi_positions\n'), ((2261, 2297), 'warnings.catch_warnings', 'warnings.catch_warnings', ([], {'record': '(True)'}), '(record=True)\n', (2284, 2297), False, 'import warnings\n'), ((2311, 2342), 'warnings.simplefilter', 'warnings.simplefilter', (['"""always"""'], {}), "('always')\n", (2332, 2342), False, 'import warnings\n'), ((2361, 2393), 'mne.io.Raw', 'Raw', (['fname'], {'allow_maxshield': '(True)'}), '(fname, allow_maxshield=True)\n', (2364, 2393), False, 'from mne.io import read_info, Raw\n'), ((2507, 2543), 'warnings.catch_warnings', 'warnings.catch_warnings', ([], {'record': '(True)'}), '(record=True)\n', (2530, 2543), False, 'import warnings\n'), ((2557, 2588), 'warnings.simplefilter', 'warnings.simplefilter', (['"""always"""'], {}), "('always')\n", (2578, 2588), False, 'import warnings\n'), ((2609, 2645), 'mne.io.Raw', 'Raw', (['temp_name'], {'allow_maxshield': '(True)'}), '(temp_name, allow_maxshield=True)\n', (2612, 2645), False, 'from mne.io import read_info, Raw\n'), ((1186, 1203), 'mne.io.chpi._rot_to_quat', '_rot_to_quat', (['rot'], {}), '(rot)\n', (1198, 1203), False, 'from mne.io.chpi import _rot_to_quat, _quat_to_rot, get_chpi_positions\n'), ((1342, 1359), 'mne.io.chpi._rot_to_quat', '_rot_to_quat', (['rot'], {}), '(rot)\n', (1354, 1359), False, 'from mne.io.chpi import _rot_to_quat, _quat_to_rot, get_chpi_positions\n'), ((1074, 1090), 'mne.io.read_info', 'read_info', (['fname'], {}), '(fname)\n', (1083, 1090), False, 'from mne.io import read_info, Raw\n')]
import numpy as np import matplotlib.pyplot as plt import sys import time from dataclasses import dataclass testdir = sys.argv[1] filebase = sys.argv[2] wallfile = sys.argv[3] tsave = int(sys.argv[4]) tfinal = int(sys.argv[5]) R = 1.0 NT = int(tfinal/tsave); theta = np.linspace(0,2*np.pi,100); xcirc = R*np.cos(theta); ycirc = R*np.sin(theta); fig = plt.figure(1); plt.ion(); plt.show() for i in range(NT): xy = np.genfromtxt(testdir + filebase + str(tsave*(i+1)) + '.csv', delimiter=',') for j in range(xy.shape[0]): plt.plot(xcirc + xy[j,0] , ycirc + xy[j,1] , 'b'); plt.gca().set_aspect('equal'); plt.xlim([-10,10]) plt.ylim([-4,16]) fig.canvas.draw() fig.canvas.flush_events() time.sleep(0.01) plt.clf() plt.ioff(); plt.show();
[ "matplotlib.pyplot.xlim", "matplotlib.pyplot.show", "matplotlib.pyplot.ioff", "matplotlib.pyplot.ylim", "matplotlib.pyplot.clf", "matplotlib.pyplot.plot", "matplotlib.pyplot.gca", "time.sleep", "matplotlib.pyplot.ion", "matplotlib.pyplot.figure", "numpy.sin", "numpy.linspace", "numpy.cos" ]
[((280, 310), 'numpy.linspace', 'np.linspace', (['(0)', '(2 * np.pi)', '(100)'], {}), '(0, 2 * np.pi, 100)\n', (291, 310), True, 'import numpy as np\n'), ((365, 378), 'matplotlib.pyplot.figure', 'plt.figure', (['(1)'], {}), '(1)\n', (375, 378), True, 'import matplotlib.pyplot as plt\n'), ((380, 389), 'matplotlib.pyplot.ion', 'plt.ion', ([], {}), '()\n', (387, 389), True, 'import matplotlib.pyplot as plt\n'), ((391, 401), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (399, 401), True, 'import matplotlib.pyplot as plt\n'), ((768, 778), 'matplotlib.pyplot.ioff', 'plt.ioff', ([], {}), '()\n', (776, 778), True, 'import matplotlib.pyplot as plt\n'), ((780, 790), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (788, 790), True, 'import matplotlib.pyplot as plt\n'), ((318, 331), 'numpy.cos', 'np.cos', (['theta'], {}), '(theta)\n', (324, 331), True, 'import numpy as np\n'), ((343, 356), 'numpy.sin', 'np.sin', (['theta'], {}), '(theta)\n', (349, 356), True, 'import numpy as np\n'), ((639, 658), 'matplotlib.pyplot.xlim', 'plt.xlim', (['[-10, 10]'], {}), '([-10, 10])\n', (647, 658), True, 'import matplotlib.pyplot as plt\n'), ((662, 680), 'matplotlib.pyplot.ylim', 'plt.ylim', (['[-4, 16]'], {}), '([-4, 16])\n', (670, 680), True, 'import matplotlib.pyplot as plt\n'), ((736, 752), 'time.sleep', 'time.sleep', (['(0.01)'], {}), '(0.01)\n', (746, 752), False, 'import time\n'), ((757, 766), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (764, 766), True, 'import matplotlib.pyplot as plt\n'), ((549, 598), 'matplotlib.pyplot.plot', 'plt.plot', (['(xcirc + xy[j, 0])', '(ycirc + xy[j, 1])', '"""b"""'], {}), "(xcirc + xy[j, 0], ycirc + xy[j, 1], 'b')\n", (557, 598), True, 'import matplotlib.pyplot as plt\n'), ((604, 613), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (611, 613), True, 'import matplotlib.pyplot as plt\n')]
# Importing libraries import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns # lightgbm for classification from numpy import mean from numpy import std #from sklearn.datasets import make_classification from lightgbm import LGBMClassifier from sklearn.model_selection import cross_val_score from sklearn.model_selection import RepeatedStratifiedKFold #from matplotlib import pyplot path = '../Data' train = pd.read_csv(path + "/train.csv") test = pd.read_csv(path + "/test.csv") # submission = pd.read_csv(path + "/sample_submission.csv") print(train.head()) """### Filling the null values in Number_Weeks_Used column""" train['Number_Weeks_Used'] = train['Number_Weeks_Used'].fillna( train.groupby('Pesticide_Use_Category')['Number_Weeks_Used'].transform('median')) test['Number_Weeks_Used'] = test['Number_Weeks_Used'].fillna( test.groupby('Pesticide_Use_Category')['Number_Weeks_Used'].transform('median')) """### Data Preprocessing""" training_labels = train.iloc[:, -1] X_train = train.iloc[:, 1:-1] X_test = test.iloc[:, 1:] data = pd.concat([X_train, X_test]) # data.head() columns_names_encod = data.columns[[3, 7]] data = pd.get_dummies(data, columns=columns_names_encod) # data """### Splitting the data back""" final_train = data[:train.shape[0]] final_test = data[train.shape[0]:] # final_train """### Creating cross validation set""" training_labels.value_counts() from sklearn.model_selection import train_test_split X_training, X_cv, y_training, y_cv = train_test_split(final_train, training_labels, test_size =0.2, random_state=21) """## Training model on training dataset""" # To check whether GPU is running or not # import tensorflow as tf # tf.test.gpu_device_name() #X, y = make_classification(n_samples=1000, n_features=10, n_informative=5, n_redundant=5, random_state=1) # evaluate the model model = LGBMClassifier() cv = RepeatedStratifiedKFold(n_splits=10, n_repeats=3, random_state=1) n_scores = cross_val_score(model, X_training, y_training, scoring='accuracy', cv=cv, n_jobs=-1, error_score='raise') print('Accuracy: %.3f (%.3f)' % (mean(n_scores), std(n_scores))) # fit the model on the whole dataset model = LGBMClassifier() model.fit(X_training, y_training) y_training_pred = model.predict(X_training) y_cv_pred = model.predict(X_cv) """### Checking accuracy score for training dataset and cross validation set""" from sklearn.metrics import accuracy_score training_accuracy_score = accuracy_score(y_training, y_training_pred) cv_accuracy_score = accuracy_score(y_cv, y_cv_pred) print(training_accuracy_score) print(cv_accuracy_score) """### Testing the model on test data""" predictions_test = model.predict(final_test) predictions_test = pd.Series(predictions_test) # frame = {'ID': test.ID, # 'Crop_Damage': predictions_test} # submission = pd.DataFrame(frame) # submission.to_csv(path + '/lgbm_submission.csv', index=False) # final_test # predictions_test import joblib joblib.dump(model,'lgbm.ml')
[ "lightgbm.LGBMClassifier", "pandas.read_csv", "pandas.get_dummies", "sklearn.model_selection.train_test_split", "sklearn.model_selection.RepeatedStratifiedKFold", "sklearn.model_selection.cross_val_score", "sklearn.metrics.accuracy_score", "joblib.dump", "numpy.std", "numpy.mean", "pandas.Series...
[((446, 478), 'pandas.read_csv', 'pd.read_csv', (["(path + '/train.csv')"], {}), "(path + '/train.csv')\n", (457, 478), True, 'import pandas as pd\n'), ((486, 517), 'pandas.read_csv', 'pd.read_csv', (["(path + '/test.csv')"], {}), "(path + '/test.csv')\n", (497, 517), True, 'import pandas as pd\n'), ((1139, 1167), 'pandas.concat', 'pd.concat', (['[X_train, X_test]'], {}), '([X_train, X_test])\n', (1148, 1167), True, 'import pandas as pd\n'), ((1234, 1283), 'pandas.get_dummies', 'pd.get_dummies', (['data'], {'columns': 'columns_names_encod'}), '(data, columns=columns_names_encod)\n', (1248, 1283), True, 'import pandas as pd\n'), ((1578, 1656), 'sklearn.model_selection.train_test_split', 'train_test_split', (['final_train', 'training_labels'], {'test_size': '(0.2)', 'random_state': '(21)'}), '(final_train, training_labels, test_size=0.2, random_state=21)\n', (1594, 1656), False, 'from sklearn.model_selection import train_test_split\n'), ((1938, 1954), 'lightgbm.LGBMClassifier', 'LGBMClassifier', ([], {}), '()\n', (1952, 1954), False, 'from lightgbm import LGBMClassifier\n'), ((1960, 2025), 'sklearn.model_selection.RepeatedStratifiedKFold', 'RepeatedStratifiedKFold', ([], {'n_splits': '(10)', 'n_repeats': '(3)', 'random_state': '(1)'}), '(n_splits=10, n_repeats=3, random_state=1)\n', (1983, 2025), False, 'from sklearn.model_selection import RepeatedStratifiedKFold\n'), ((2037, 2146), 'sklearn.model_selection.cross_val_score', 'cross_val_score', (['model', 'X_training', 'y_training'], {'scoring': '"""accuracy"""', 'cv': 'cv', 'n_jobs': '(-1)', 'error_score': '"""raise"""'}), "(model, X_training, y_training, scoring='accuracy', cv=cv,\n n_jobs=-1, error_score='raise')\n", (2052, 2146), False, 'from sklearn.model_selection import cross_val_score\n'), ((2254, 2270), 'lightgbm.LGBMClassifier', 'LGBMClassifier', ([], {}), '()\n', (2268, 2270), False, 'from lightgbm import LGBMClassifier\n'), ((2533, 2576), 'sklearn.metrics.accuracy_score', 'accuracy_score', (['y_training', 'y_training_pred'], {}), '(y_training, y_training_pred)\n', (2547, 2576), False, 'from sklearn.metrics import accuracy_score\n'), ((2597, 2628), 'sklearn.metrics.accuracy_score', 'accuracy_score', (['y_cv', 'y_cv_pred'], {}), '(y_cv, y_cv_pred)\n', (2611, 2628), False, 'from sklearn.metrics import accuracy_score\n'), ((2793, 2820), 'pandas.Series', 'pd.Series', (['predictions_test'], {}), '(predictions_test)\n', (2802, 2820), True, 'import pandas as pd\n'), ((3042, 3071), 'joblib.dump', 'joblib.dump', (['model', '"""lgbm.ml"""'], {}), "(model, 'lgbm.ml')\n", (3053, 3071), False, 'import joblib\n'), ((2176, 2190), 'numpy.mean', 'mean', (['n_scores'], {}), '(n_scores)\n', (2180, 2190), False, 'from numpy import mean\n'), ((2192, 2205), 'numpy.std', 'std', (['n_scores'], {}), '(n_scores)\n', (2195, 2205), False, 'from numpy import std\n')]
''' Etant donnée une liste d'accords, les trie par ordre de concordance, consonance, tension et concordance totale, en affichant en dessous les valeurs. Prend en entrée dans le fichier paramètre deux listes de même taille : partiels, qui contient l'emplacement des partiels (éventuellement inharmoniques), et amplitudes, avec leurs amplitudes respectives ''' #from mimetypes import init import numpy as np from operator import itemgetter, attrgetter from music21 import * #from music21 import note, stream, corpus, tree, chord, pitch, converter import parametres import tunings class ListeAccords: ''' Prend en attribut un objet Stream, les parametres d'instrument et d'accord: instrument = [liste des partiels, liste des amplitudes, liste des largeurs spectrales]. temperament = [Nom de la note de reference e partir de laquelle va etre fait l'accord, liste des deviations en cents des 11 notes restantes par rapport au temperament tempere] L'attribut 'grandeursHarmoniques' va stoker sous forme de liste les informations de concordance et de coherence de chaque accord, ainsi que son nombre de notes L'attribut normalisation va servir a normaliser les concordances des unissons de n notes ''' def __init__(self, stream): self.stream = stream self.tree = tree.fromStream.asTimespans(stream, flatten=True,classList=(note.Note, chord.Chord)) self.partiels = parametres.partiels self.amplitudes = parametres.amplitudes self.sig = parametres.sig self.temperament = tunings.Equal #[0,0,0,0,0,0,0,0,0,0,0,0]#Tempere# #[0,-10,+4,-6,+8,-2,-12,+2,-8,+6,-4,+10]#Pythagore #[0,+17,-7,+10,-14,+3,+20,-3,+14,-10,+7,-17]#Mesotonique 1/4 #[]#Mesotonique 1/6 #[0,-29,+4,+16,-14,-2,-31,+2,-27,-16,-4,-12]#Juste Majeur #[0,12,+4,+16,-13,-2,+32,+2,+14,-17,+18,-11]#Juste mineur self.noteDeReferencePourLeTunning = parametres.noteDeReferencePourLeTunning self.grandeursHarmoniques = [] self.normalisation = [2,3,4,5,6,7,8] #self.ConcordanceCoherenceConcordanceOrdre3Liste() def spectre(self,f0): '''Cette methode va etre appelee dans la classe Accord, mais elle est definie ici car le seul attribut d'objet qui en est parametre est l'instrument''' n = np.arange(0,16,0.001) S = np.zeros(np.shape(n)) for i in range(1, len(self.partiels) + 1): S = S + (self.amplitudes[i-1]) * np.exp(-(n - np.log2(self.partiels[i-1] * f0))**2 / (2 * self.sig**2)) return S #for i, elt in enumerate(self.instrument[0]): # S = S + self.instrument[1][i] * np.exp(-(n - np.log2(elt * f0))**2 / (2 * (self.instrument[2][i])**2)) #return S def Normalisation(self): """ Calcule la concordance d'ordre n de l'unisson a n notes, pour n allant de 2 a 8""" self.normalisation[0] = np.sum(self.spectre(100)*self.spectre(100)) self.normalisation[1] = (np.sum(self.spectre(100)*self.spectre(100)*self.spectre(100)))**(2/3) self.normalisation[2] = (np.sum(self.spectre(100)*self.spectre(100)*self.spectre(100)*self.spectre(100)))**(2/4) self.normalisation[3] = (np.sum(self.spectre(100)*self.spectre(100)*self.spectre(100)*self.spectre(100)*self.spectre(100)))**(2/5) self.normalisation[4] = (np.sum(self.spectre(100)*self.spectre(100)*self.spectre(100)*self.spectre(100)*self.spectre(100)*self.spectre(100)))**(2/6) self.normalisation[5] = (np.sum(self.spectre(100)*self.spectre(100)*self.spectre(100)*self.spectre(100)*self.spectre(100)*self.spectre(100)*self.spectre(100)))**(2/7) self.normalisation[6] = (np.sum(self.spectre(100)*self.spectre(100)*self.spectre(100)*self.spectre(100)*self.spectre(100)*self.spectre(100)*self.spectre(100)*self.spectre(100)))**(2/8) def frequenceAvecTemperament(self,pitch1): """Fonction qui prend en entree un pitch pour renvoyer une frequence, en tenant compte du temperament""" pitchRef = pitch.Pitch(self.noteDeReferencePourLeTunning) pitch1.microtone = self.temperament[(pitch1.pitchClass - pitchRef.pitchClass)%12] - 100*((pitch1.pitchClass - pitchRef.pitchClass)%12) return (pitch1.frequency) def ConcordanceCoherenceConcordanceOrdre3Liste (self): ''' Transforme chaque verticalite en objet Accord, calcule la concordance, la coherence et les concordances multiples, et stocke les resultats sous forme de liste d'Accords" ''' self.Normalisation() for verticality in self.tree.iterateVerticalities(): v = Accord(verticality, self.partiels, self.amplitudes, self.sig, self.normalisation, self.temperament,self.noteDeReferencePourLeTunning) if verticality.bassTimespan!=None : v.identifiant = verticality.bassTimespan.element.id v.ListeHauteursAvecMultiplicite() v.ListeConcordanceDesIntervallesDansAccord() v.NombreDeNotes() if v.nombreDeNotes>=2: v.Concordance() v.Dissonance() if v.nombreDeNotes>=3: v.Tension() v.ConcordanceTotale() self.grandeursHarmoniques.append(v) def getAnnotatedStream(self, resultList = ['concordance']): for gH in self.grandeursHarmoniques: if gH.verticality.bassTimespan != None : element = gH.verticality.bassTimespan.element if element.isNote or element.isChord: dataString = "" if 'concordance' in resultList: if dataString != '': dataString + " " dataString = dataString + str(round(gH.concordance,2)) if 'concordanceOrdre3' in resultList: if dataString != '': dataString + " " dataString = dataString + str(round(10 * gH.concordanceOrdre3,2)) if 'concordanceTotale' in resultList: if dataString != '': dataString + " " dataString = dataString + str(round(10 * gH.concordanceTotale,2)) if 'dissonance' in resultList: if dataString != '': dataString + " " dataString = dataString + str (round(gH.dissonance,2)) if 'tension' in resultList: if dataString != '': dataString + " " dataString = dataString + str (round(gH.tension,2)) element.lyric = dataString return tree.toStream.partwise(self.tree, self.stream) def moyenneConcordance (self): l = [] for accord in self.grandeursHarmoniques: l.append(accord.concordance) return np.mean(l) def moyenneConcordanceTotale (self): l = [] for accord in self.grandeursHarmoniques: l.append(accord.concordanceTotale) return np.mean(l) def moyenneConcordanceOrdre3 (self): l = [] for accord in self.grandeursHarmoniques: l.append(accord.concordanceOrdre3) return np.mean(l) def offsetList (self): '''Donne la liste de tous les offsets des verticalites''' l = [] for verticality in self.tree.iterateVerticalities(): v = Accord(verticality) l.append(v.offset) return l def idList (self): '''Donne la liste des identifiants des verticalites''' l = [] for verticality in self.tree.iterateVerticalities(): v = Accord(verticality) l.append(v.id) return l def classementConc(self): s = stream.Measure() ts1 = meter.TimeSignature('C') s.insert(0, ts1) s.insert(0, clef.TrebleClef()) self.stream.lyrics = {} self.getAnnotatedStream('concordance') self.grandeursHarmoniques.sort(key=attrgetter('concordance'), reverse=True) for gH in self.grandeursHarmoniques: element = gH.verticality.bassTimespan.element s.insert(-1, element) s[0].addLyric('Concordance') s.show() del s[0].lyrics[1] def classementConcTot(self): s2 = stream.Measure() ts1 = meter.TimeSignature('C') s2.insert(0, ts1) s2.insert(0, clef.TrebleClef()) self.stream.lyrics = {} self.getAnnotatedStream(['concordanceTotale']) self.grandeursHarmoniques.sort(key=attrgetter('concordanceTotale'), reverse=True) for gH in self.grandeursHarmoniques: element = gH.verticality.bassTimespan.element s2.insert(-1, element) s2[0].addLyric('ConcTot') s2.show() del s2[0].lyrics[1] def classementDiss(self): s1 = stream.Measure() ts1 = meter.TimeSignature('C') s1.insert(0, ts1) s1.insert(0, clef.TrebleClef()) self.stream.lyrics = {} self.getAnnotatedStream('dissonance') self.grandeursHarmoniques.sort(key=attrgetter('dissonance'), reverse=False) for gH in self.grandeursHarmoniques: element = gH.verticality.bassTimespan.element s1.insert(-1, element) s1[0].addLyric('Dissonance') s1.show() del s1[0].lyrics[1] def classementTens(self): s3 = stream.Measure() ts1 = meter.TimeSignature('C') s3.insert(0, ts1) s3.insert(0, clef.TrebleClef()) self.stream.lyrics = {} self.getAnnotatedStream('tension') self.grandeursHarmoniques.sort(key=attrgetter('tension'), reverse=False) for gH in self.grandeursHarmoniques: element = gH.verticality.bassTimespan.element s3.insert(-1, element) s3[0].addLyric('Tension') s3.show() del s3[0].lyrics[1] #sorted(self.grandeursHarmoniques, key=attrgetter('concordance')) #return tree.toStream.partwise(self.tree, self.stream) class Accord(ListeAccords): ''' Classe qui traite les verticalites en heritant de l'instrument et de la methode spectre de la classe ListeAccords, et ayant comme attributs supplementaires les grandeurs lies a la concordance Faiblesse pour l'instant : l'arbre de la classe mere est vide, un attribut 'verticality' vient le remplacer ''' def __init__(self, verticality, partiels, amplitudes, sig, normalisation, temperament, noteDeReferencePourLeTunning):# verticality self.partiels = partiels self.amplitudes = amplitudes self.sig = sig self.temperament = temperament self.noteDeReferencePourLeTunning = noteDeReferencePourLeTunning self.normalisation = normalisation self.listeHauteursAvecMultiplicite = [] self.listeConcordanceDesIntervallesDansAccord = [] self.verticality = verticality self.concordance = 0 self.concordanceTotale = 0 self.concordanceOrdre3 = 0 self.dissonance = 0 self.tension = 0 self.identifiant = 0 self.nombreDeNotes = 0 def __repr__(self): """Affichage""" return "Concordance: {0} \nConcordance d'ordre 3: {2} \nConcordance totale: {3}".format(self.concordance,self.concordanceOrdre3,self.concordanceTotale) def ListeHauteursAvecMultiplicite(self): """ Fonction qui donne la liste des pitches, comptes autant de fois qu'ils sont repetes a differentes voix""" #self.listeHauteursAvecMultiplicite = list for elt in self.verticality.startTimespans: if elt.element.isChord: for pitch in elt.element.pitches: if elt.element.duration.quarterLength != 0: self.listeHauteursAvecMultiplicite.append(pitch) elif elt.element.duration.quarterLength != 0: self.listeHauteursAvecMultiplicite.append(elt.element.pitch) for elt in self.verticality.overlapTimespans: if elt.element.isChord: for pitch in elt.element.pitches: self.listeHauteursAvecMultiplicite.append(pitch) else: self.listeHauteursAvecMultiplicite.append(elt.element.pitch) def ListeConcordanceDesIntervallesDansAccord(self): '''Cree la liste des concordances des intervalles qui constituent l'accord, et le fixe comme parametre, ceci afin d'eviter les redondances dans les calculs de la concordance ''' for i, pitch1 in enumerate(self.listeHauteursAvecMultiplicite): for j, pitch2 in enumerate(self.listeHauteursAvecMultiplicite): if (i<j): self.listeConcordanceDesIntervallesDansAccord.append(np.sum(self.spectre(self.frequenceAvecTemperament(pitch1))*self.spectre(self.frequenceAvecTemperament(pitch2)))) def NombreDeNotes(self): if self.listeHauteursAvecMultiplicite != None: self.nombreDeNotes = len(self.listeHauteursAvecMultiplicite) def Concordance(self): """ Normalisation logarithmique, de maniere a rendre egales les concordances des unissons de n notes""" self.concordance = np.sum(self.listeConcordanceDesIntervallesDansAccord) n = self.nombreDeNotes self.concordance = self.concordance/(self.nombreDeNotes*(self.nombreDeNotes - 1)/2) #self.concordance = np.log2(1 + self.concordance / (self.normalisation[0]*self.nombreDeNotes*(self.nombreDeNotes - 1)/2)) #self.concordance = np.log2(1 + self.concordance)/(np.log(1 + self.normalisation[0]*self.nombreDeNotes*(self.nombreDeNotes - 1)/2) / np.log(1 + self.normalisation[0])) def ConcordanceTotale(self): S = np.ones(16000) for pitch in self.listeHauteursAvecMultiplicite: S = S*self.spectre(self.frequenceAvecTemperament(pitch)) self.concordanceTotale = np.sum(S) self.concordanceTotale = self.concordanceTotale**(2/self.nombreDeNotes) def Dissonance(self): for i, pitch1 in enumerate(self.listeHauteursAvecMultiplicite): for j, pitch2 in enumerate(self.listeHauteursAvecMultiplicite): if (i<j): for k1 in range(1,len(self.partiels) + 1): for k2 in range(1,len(self.partiels) + 1): fmin = min(self.partiels[k2-1] * self.frequenceAvecTemperament(pitch2), self.partiels[k1-1] * self.frequenceAvecTemperament(pitch1)) fmax = max(self.partiels[k2-1] * self.frequenceAvecTemperament(pitch2), self.partiels[k1-1] * self.frequenceAvecTemperament(pitch1)) s=0.24/(0.021*fmin+19.) self.dissonance = self.dissonance + (100 * self.amplitudes[k1-1] * self.amplitudes[k2-1]) * (np.exp(-3.5*s*(fmax-fmin))-np.exp(-5.75*s*(fmax-fmin))) n = self.nombreDeNotes self.dissonance = self.dissonance/(self.nombreDeNotes*(self.nombreDeNotes - 1)/2) def Tension(self): for i, pitch1 in enumerate(self.listeHauteursAvecMultiplicite): for j, pitch2 in enumerate(self.listeHauteursAvecMultiplicite): for l, pitch3 in enumerate(self.listeHauteursAvecMultiplicite): if (i<j<l): for k1 in range(1,len(self.partiels) + 1): for k2 in range(1,len(self.partiels) + 1): for k3 in range(1,len(self.partiels) + 1): x = np.log2((self.partiels[k2-1] * self.frequenceAvecTemperament(pitch2)) / (self.partiels[k1-1] * self.frequenceAvecTemperament(pitch1))) y = np.log2((self.partiels[k3-1] * self.frequenceAvecTemperament(pitch3)) / (self.partiels[k2-1] * self.frequenceAvecTemperament(pitch2))) z = x + y X = abs(x) Y = abs(y) Z = abs(z) a = 0.6 self.tension = self.tension = self.tension + (self.amplitudes[k1-1] * self.amplitudes[k2-1] * self.amplitudes[k3-1]) * max(np.exp(-(12*(X-Y)/a)**2) , np.exp(-(12*(Y-Z)/a)**2) , np.exp(-(12*(X-Z)/a)**2)) n = self.nombreDeNotes self.tension = self.tension/(self.nombreDeNotes*(self.nombreDeNotes - 1)*(self.nombreDeNotes - 2)/6) def ConcordanceOrdre3(self): for i, pitch1 in enumerate(self.listeHauteursAvecMultiplicite): for j, pitch2 in enumerate(self.listeHauteursAvecMultiplicite): for k, pitch3 in enumerate(self.listeHauteursAvecMultiplicite): if (i<j<k): self.concordanceOrdre3 = self.concordanceOrdre3 + np.sum(self.spectre(self.frequenceAvecTemperament(pitch1))*self.spectre(self.frequenceAvecTemperament(pitch2))*self.spectre(self.frequenceAvecTemperament(pitch3))) self.concordanceOrdre3 = self.concordanceOrdre3**(2/3) #self.concordanceOrdre3 = np.log2(1 + self.concordanceOrdre3 / (self.normalisation[1]*(self.nombreDeNotes*(self.nombreDeNotes - 1)*(self.nombreDeNotes - 2)/6)**(2/3))) #self.concordanceOrdre3 = np.log2(1 + self.concordanceOrdre3)/(np.log(1 + self.normalisation[1] * (self.nombreDeNotes*(self.nombreDeNotes - 1)*(self.nombreDeNotes - 2)/6)**(2/3)) / np.log(1 + self.normalisation[1])) score = converter.parse('/Users/manuel/Github/DescripteursHarmoniques/Exemples/SuiteAccords.musicxml') #score = converter.parse('/Users/manuel/Dropbox (TMG)/Thèse/Disposition/AccordsMineur.musicxml') #score = converter.parse('/Users/manuel/Dropbox (TMG)/Thèse/Disposition/Majeur3et4notes.musicxml') #score = converter.parse('/Users/manuel/Dropbox (TMG)/Thèse/Disposition/Mineur3et4notes.musicxml') #score = converter.parse('/Users/manuel/Dropbox (TMG)/Thèse/Disposition/Tension.musicxml') #score = converter.parse('/Users/manuel/Dropbox (TMG)/Thèse/Disposition/DispoMajeurMineur.musicxml') l = ListeAccords(score) l.ConcordanceCoherenceConcordanceOrdre3Liste() l.classementConc() #l.classementDiss() #l.classementConcTot() #l.classementTens()
[ "numpy.sum", "numpy.log2", "numpy.ones", "numpy.shape", "operator.attrgetter", "numpy.mean", "numpy.arange", "numpy.exp" ]
[((2425, 2448), 'numpy.arange', 'np.arange', (['(0)', '(16)', '(0.001)'], {}), '(0, 16, 0.001)\n', (2434, 2448), True, 'import numpy as np\n'), ((6809, 6819), 'numpy.mean', 'np.mean', (['l'], {}), '(l)\n', (6816, 6819), True, 'import numpy as np\n'), ((6978, 6988), 'numpy.mean', 'np.mean', (['l'], {}), '(l)\n', (6985, 6988), True, 'import numpy as np\n'), ((7147, 7157), 'numpy.mean', 'np.mean', (['l'], {}), '(l)\n', (7154, 7157), True, 'import numpy as np\n'), ((12951, 13004), 'numpy.sum', 'np.sum', (['self.listeConcordanceDesIntervallesDansAccord'], {}), '(self.listeConcordanceDesIntervallesDansAccord)\n', (12957, 13004), True, 'import numpy as np\n'), ((13474, 13488), 'numpy.ones', 'np.ones', (['(16000)'], {}), '(16000)\n', (13481, 13488), True, 'import numpy as np\n'), ((2466, 2477), 'numpy.shape', 'np.shape', (['n'], {}), '(n)\n', (2474, 2477), True, 'import numpy as np\n'), ((13660, 13669), 'numpy.sum', 'np.sum', (['S'], {}), '(S)\n', (13666, 13669), True, 'import numpy as np\n'), ((7902, 7927), 'operator.attrgetter', 'attrgetter', (['"""concordance"""'], {}), "('concordance')\n", (7912, 7927), False, 'from operator import itemgetter, attrgetter\n'), ((8433, 8464), 'operator.attrgetter', 'attrgetter', (['"""concordanceTotale"""'], {}), "('concordanceTotale')\n", (8443, 8464), False, 'from operator import itemgetter, attrgetter\n'), ((8958, 8982), 'operator.attrgetter', 'attrgetter', (['"""dissonance"""'], {}), "('dissonance')\n", (8968, 8982), False, 'from operator import itemgetter, attrgetter\n'), ((9477, 9498), 'operator.attrgetter', 'attrgetter', (['"""tension"""'], {}), "('tension')\n", (9487, 9498), False, 'from operator import itemgetter, attrgetter\n'), ((2584, 2618), 'numpy.log2', 'np.log2', (['(self.partiels[i - 1] * f0)'], {}), '(self.partiels[i - 1] * f0)\n', (2591, 2618), True, 'import numpy as np\n'), ((14560, 14592), 'numpy.exp', 'np.exp', (['(-3.5 * s * (fmax - fmin))'], {}), '(-3.5 * s * (fmax - fmin))\n', (14566, 14592), True, 'import numpy as np\n'), ((14587, 14620), 'numpy.exp', 'np.exp', (['(-5.75 * s * (fmax - fmin))'], {}), '(-5.75 * s * (fmax - fmin))\n', (14593, 14620), True, 'import numpy as np\n'), ((15940, 15972), 'numpy.exp', 'np.exp', (['(-(12 * (X - Y) / a) ** 2)'], {}), '(-(12 * (X - Y) / a) ** 2)\n', (15946, 15972), True, 'import numpy as np\n'), ((15967, 15999), 'numpy.exp', 'np.exp', (['(-(12 * (Y - Z) / a) ** 2)'], {}), '(-(12 * (Y - Z) / a) ** 2)\n', (15973, 15999), True, 'import numpy as np\n'), ((15994, 16026), 'numpy.exp', 'np.exp', (['(-(12 * (X - Z) / a) ** 2)'], {}), '(-(12 * (X - Z) / a) ** 2)\n', (16000, 16026), True, 'import numpy as np\n')]
""" Copyright (c) 2019 Intel Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import numpy as np from .metric import Metric from .confusionmatrix import ConfusionMatrix class IoU(Metric): """Computes the intersection over union (IoU) per class and corresponding mean (mIoU). Intersection over union (IoU) is a common evaluation metric for semantic segmentation. The predictions are first accumulated in a confusion matrix and the IoU is computed from it as follows: IoU = true_positive / (true_positive + false_positive + false_negative). Keyword arguments: - num_classes (int): number of classes in the classification problem - normalized (boolean, optional): Determines whether or not the confusion matrix is normalized or not. Default: False. - ignore_index (int or iterable, optional): Index of the classes to ignore when computing the IoU. Can be an int, or any iterable of ints. """ def __init__(self, num_classes, normalized=False, ignore_index=None): super().__init__() self.conf_metric = ConfusionMatrix(num_classes, normalized) if ignore_index is None: self.ignore_index = None elif isinstance(ignore_index, int): self.ignore_index = (ignore_index,) else: try: self.ignore_index = tuple(ignore_index) except TypeError: raise ValueError("'ignore_index' must be an int or iterable") def reset(self): self.conf_metric.reset() def add(self, predicted, target): """Adds the predicted and target pair to the IoU metric. Keyword arguments: - predicted (Tensor): Can be a (N, K, H, W) tensor of predicted scores obtained from the model for N examples and K classes, or (N, H, W) tensor of integer values between 0 and K-1. - target (Tensor): Can be a (N, K, H, W) tensor of target scores for N examples and K classes, or (N, H, W) tensor of integer values between 0 and K-1. """ # Dimensions check assert predicted.size(0) == target.size(0), \ 'number of targets and predicted outputs do not match' assert predicted.dim() == 3 or predicted.dim() == 4, \ "predictions must be of dimension (N, H, W) or (N, K, H, W)" assert target.dim() == 3 or target.dim() == 4, \ "targets must be of dimension (N, H, W) or (N, K, H, W)" # If the tensor is in categorical format convert it to integer format if predicted.dim() == 4: _, predicted = predicted.max(1) if target.dim() == 4: _, target = target.max(1) self.conf_metric.add(predicted.view(-1), target.view(-1)) def value(self): """Computes the IoU and mean IoU. The mean computation ignores NaN elements of the IoU array. Returns: Tuple: (IoU, mIoU). The first output is the per class IoU, for K classes it's numpy.ndarray with K elements. The second output, is the mean IoU. """ conf_matrix = self.conf_metric.value() if self.ignore_index is not None: for _ in self.ignore_index: conf_matrix[:, self.ignore_index] = 0 conf_matrix[self.ignore_index, :] = 0 true_positive = np.diag(conf_matrix) false_positive = np.sum(conf_matrix, 0) - true_positive false_negative = np.sum(conf_matrix, 1) - true_positive # Just in case we get a division by 0, ignore/hide the error with np.errstate(divide='ignore', invalid='ignore'): iou = true_positive / (true_positive + false_positive + false_negative) if self.ignore_index is not None: iou_valid_cls = np.delete(iou, self.ignore_index) miou = np.nanmean(iou_valid_cls) else: miou = np.nanmean(iou) return iou, miou
[ "numpy.sum", "numpy.errstate", "numpy.diag", "numpy.delete", "numpy.nanmean" ]
[((3867, 3887), 'numpy.diag', 'np.diag', (['conf_matrix'], {}), '(conf_matrix)\n', (3874, 3887), True, 'import numpy as np\n'), ((3913, 3935), 'numpy.sum', 'np.sum', (['conf_matrix', '(0)'], {}), '(conf_matrix, 0)\n', (3919, 3935), True, 'import numpy as np\n'), ((3977, 3999), 'numpy.sum', 'np.sum', (['conf_matrix', '(1)'], {}), '(conf_matrix, 1)\n', (3983, 3999), True, 'import numpy as np\n'), ((4099, 4145), 'numpy.errstate', 'np.errstate', ([], {'divide': '"""ignore"""', 'invalid': '"""ignore"""'}), "(divide='ignore', invalid='ignore')\n", (4110, 4145), True, 'import numpy as np\n'), ((4302, 4335), 'numpy.delete', 'np.delete', (['iou', 'self.ignore_index'], {}), '(iou, self.ignore_index)\n', (4311, 4335), True, 'import numpy as np\n'), ((4355, 4380), 'numpy.nanmean', 'np.nanmean', (['iou_valid_cls'], {}), '(iou_valid_cls)\n', (4365, 4380), True, 'import numpy as np\n'), ((4414, 4429), 'numpy.nanmean', 'np.nanmean', (['iou'], {}), '(iou)\n', (4424, 4429), True, 'import numpy as np\n')]
# -*- coding:utf-8 -*- # Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. # This program is free software; you can redistribute it and/or modify # it under the terms of the MIT License. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MIT License for more details. """The trainer program for Auto Lane.""" import logging import os import time import numpy as np from pycocotools.coco import COCO from vega.common import ClassFactory, ClassType from vega.trainer.trainer_ms import TrainerMs from mindspore.train.callback import ModelCheckpoint, CheckpointConfig, LossMonitor import mindspore.common.dtype as mstype from mindspore.train import Model as MsModel from mindspore import Tensor from mindspore.nn import SGD from .src.model_utils.config import config from .src.dataset import data_to_mindrecord_byte_image, create_fasterrcnn_dataset from .src.lr_schedule import dynamic_lr from .src.network_define import WithLossCell, TrainOneStepCell, LossNet from .src.util import coco_eval, bbox2result_1image, results2json from vega.datasets.conf.dataset import DatasetConfig logger = logging.getLogger(__name__) def valid(): """Construct the trainer of SpNas.""" config = DatasetConfig().to_dict() config = config['_class_data'].val prefix = "FasterRcnn_eval.mindrecord" mindrecord_dir = config.mindrecord_dir mindrecord_file = os.path.join(mindrecord_dir, prefix) if not os.path.exists(mindrecord_file): if not os.path.isdir(mindrecord_dir): os.makedirs(mindrecord_dir) if config.dataset == "coco": if os.path.isdir(config.coco_root): data_to_mindrecord_byte_image(config, "coco", False, prefix, file_num=1) else: logging.info("coco_root not exits.") else: if os.path.isdir(config.IMAGE_DIR) and os.path.exists(config.ANNO_PATH): data_to_mindrecord_byte_image(config, "other", False, prefix, file_num=1) else: logging.info("IMAGE_DIR or ANNO_PATH not exits.") dataset = create_fasterrcnn_dataset(config, mindrecord_file, batch_size=config.test_batch_size, is_training=False) return dataset def train(): """Train fasterrcnn dataset.""" config = DatasetConfig().to_dict() config = config['_class_data'].train prefix = "FasterRcnn.mindrecord" mindrecord_dir = config.mindrecord_dir mindrecord_file = os.path.join(mindrecord_dir, prefix + "0") print("CHECKING MINDRECORD FILES ...") rank = int(os.getenv('RANK_ID', '0')) device_num = int(os.getenv('RANK_SIZE', '1')) if rank == 0 and not os.path.exists(mindrecord_file): if not os.path.isdir(mindrecord_dir): os.makedirs(mindrecord_dir) if config.dataset == "coco": if os.path.isdir(config.coco_root): if not os.path.exists(config.coco_root): logging.info("Please make sure config:coco_root is valid.") raise ValueError(config.coco_root) data_to_mindrecord_byte_image(config, "coco", True, prefix) else: logging.info("coco_root not exits.") else: if os.path.isdir(config.image_dir) and os.path.exists(config.anno_path): if not os.path.exists(config.image_dir): logging.info("Please make sure config:image_dir is valid.") raise ValueError(config.image_dir) data_to_mindrecord_byte_image(config, "other", True, prefix) else: logging.info("image_dir or anno_path not exits.") while not os.path.exists(mindrecord_file + ".db"): time.sleep(5) dataset = create_fasterrcnn_dataset(config, mindrecord_file, batch_size=config.batch_size, device_num=device_num, rank_id=rank, num_parallel_workers=config.num_parallel_workers, python_multiprocessing=config.python_multiprocessing) return dataset @ClassFactory.register(ClassType.TRAINER) class SpNasTrainerCallback(TrainerMs): """Construct the trainer of SpNas.""" disable_callbacks = ['ProgressLogger'] def build(self): """Construct the trainer of SpNas.""" logging.debug("Trainer Config: {}".format(self.config)) self._init_hps() self.use_syncbn = self.config.syncbn if not self.train_loader: self.train_loader = train() if not self.valid_loader: self.valid_loader = valid() self.batch_num_train = self.train_loader.get_dataset_size() self.batch_num_valid = self.valid_loader.get_dataset_size() self.valid_metrics = self._init_metrics() def _train_epoch(self): """Construct the trainer of SpNas.""" dataset = self.train_loader dataset_size = dataset.get_dataset_size() self.model = self.model.set_train() self.model.to_float(mstype.float16) self.loss = LossNet() lr = Tensor(dynamic_lr(config, dataset_size), mstype.float32) self.optimizer = SGD(params=self.model.trainable_params(), learning_rate=lr, momentum=config.momentum, weight_decay=config.weight_decay, loss_scale=config.loss_scale) net_with_loss = WithLossCell(self.model, self.loss) net = TrainOneStepCell(net_with_loss, self.optimizer, sens=config.loss_scale) config_ck = CheckpointConfig(save_checkpoint_steps=self.config.save_steps, keep_checkpoint_max=1) save_path = self.get_local_worker_path(self.step_name, self.worker_id) ckpoint_cb = ModelCheckpoint(config=config_ck, directory=save_path) loss_cb = LossMonitor(per_print_times=1) callback_list = [ckpoint_cb, loss_cb] self.ms_model = MsModel(net) try: self.ms_model.train(epoch=self.config.epochs, train_dataset=dataset, callbacks=callback_list, dataset_sink_mode=False) except RuntimeError as e: logging.warning(f"failed to train the model, skip it, message: {str(e)}") def _valid_epoch(self): """Construct the trainer of SpNas.""" dataset = self.valid_loader self.model.set_train(False) self.model.to_float(mstype.float16) outputs = [] dataset_coco = COCO(self.config.metric.params.anno_path) max_num = 128 for data in dataset.create_dict_iterator(num_epochs=1): img_data = data['image'] img_metas = data['image_shape'] gt_bboxes = data['box'] gt_labels = data['label'] gt_num = data['valid_num'] output = self.model(img_data, img_metas, gt_bboxes, gt_labels, gt_num) all_bbox = output[0] all_label = output[1] all_mask = output[2] for j in range(config.test_batch_size): all_bbox_squee = np.squeeze(all_bbox.asnumpy()[j, :, :]) all_label_squee = np.squeeze(all_label.asnumpy()[j, :, :]) all_mask_squee = np.squeeze(all_mask.asnumpy()[j, :, :]) all_bboxes_tmp_mask = all_bbox_squee[all_mask_squee, :] all_labels_tmp_mask = all_label_squee[all_mask_squee] if all_bboxes_tmp_mask.shape[0] > max_num: inds = np.argsort(-all_bboxes_tmp_mask[:, -1]) inds = inds[:max_num] all_bboxes_tmp_mask = all_bboxes_tmp_mask[inds] all_labels_tmp_mask = all_labels_tmp_mask[inds] outputs_tmp = bbox2result_1image(all_bboxes_tmp_mask, all_labels_tmp_mask, config.num_classes) outputs.append(outputs_tmp) eval_types = ["bbox"] result_files = results2json(dataset_coco, outputs, "./results.pkl") metrics = coco_eval(result_files, eval_types, dataset_coco, single_result=True) self.valid_metrics.update(metrics) valid_logs = dict() valid_logs['cur_valid_perfs'] = self.valid_metrics.results self.callbacks.after_valid(valid_logs)
[ "mindspore.train.callback.CheckpointConfig", "vega.common.ClassFactory.register", "os.makedirs", "mindspore.train.callback.ModelCheckpoint", "os.path.isdir", "os.path.exists", "mindspore.train.callback.LossMonitor", "mindspore.train.Model", "time.sleep", "numpy.argsort", "logging.info", "pycoc...
[((1255, 1282), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1272, 1282), False, 'import logging\n'), ((4237, 4277), 'vega.common.ClassFactory.register', 'ClassFactory.register', (['ClassType.TRAINER'], {}), '(ClassType.TRAINER)\n', (4258, 4277), False, 'from vega.common import ClassFactory, ClassType\n'), ((1525, 1561), 'os.path.join', 'os.path.join', (['mindrecord_dir', 'prefix'], {}), '(mindrecord_dir, prefix)\n', (1537, 1561), False, 'import os\n'), ((2582, 2624), 'os.path.join', 'os.path.join', (['mindrecord_dir', "(prefix + '0')"], {}), "(mindrecord_dir, prefix + '0')\n", (2594, 2624), False, 'import os\n'), ((1574, 1605), 'os.path.exists', 'os.path.exists', (['mindrecord_file'], {}), '(mindrecord_file)\n', (1588, 1605), False, 'import os\n'), ((2683, 2708), 'os.getenv', 'os.getenv', (['"""RANK_ID"""', '"""0"""'], {}), "('RANK_ID', '0')\n", (2692, 2708), False, 'import os\n'), ((2731, 2758), 'os.getenv', 'os.getenv', (['"""RANK_SIZE"""', '"""1"""'], {}), "('RANK_SIZE', '1')\n", (2740, 2758), False, 'import os\n'), ((3796, 3835), 'os.path.exists', 'os.path.exists', (["(mindrecord_file + '.db')"], {}), "(mindrecord_file + '.db')\n", (3810, 3835), False, 'import os\n'), ((3845, 3858), 'time.sleep', 'time.sleep', (['(5)'], {}), '(5)\n', (3855, 3858), False, 'import time\n'), ((5659, 5748), 'mindspore.train.callback.CheckpointConfig', 'CheckpointConfig', ([], {'save_checkpoint_steps': 'self.config.save_steps', 'keep_checkpoint_max': '(1)'}), '(save_checkpoint_steps=self.config.save_steps,\n keep_checkpoint_max=1)\n', (5675, 5748), False, 'from mindspore.train.callback import ModelCheckpoint, CheckpointConfig, LossMonitor\n'), ((5845, 5899), 'mindspore.train.callback.ModelCheckpoint', 'ModelCheckpoint', ([], {'config': 'config_ck', 'directory': 'save_path'}), '(config=config_ck, directory=save_path)\n', (5860, 5899), False, 'from mindspore.train.callback import ModelCheckpoint, CheckpointConfig, LossMonitor\n'), ((5918, 5948), 'mindspore.train.callback.LossMonitor', 'LossMonitor', ([], {'per_print_times': '(1)'}), '(per_print_times=1)\n', (5929, 5948), False, 'from mindspore.train.callback import ModelCheckpoint, CheckpointConfig, LossMonitor\n'), ((6019, 6031), 'mindspore.train.Model', 'MsModel', (['net'], {}), '(net)\n', (6026, 6031), True, 'from mindspore.train import Model as MsModel\n'), ((6627, 6668), 'pycocotools.coco.COCO', 'COCO', (['self.config.metric.params.anno_path'], {}), '(self.config.metric.params.anno_path)\n', (6631, 6668), False, 'from pycocotools.coco import COCO\n'), ((1353, 1368), 'vega.datasets.conf.dataset.DatasetConfig', 'DatasetConfig', ([], {}), '()\n', (1366, 1368), False, 'from vega.datasets.conf.dataset import DatasetConfig\n'), ((1622, 1651), 'os.path.isdir', 'os.path.isdir', (['mindrecord_dir'], {}), '(mindrecord_dir)\n', (1635, 1651), False, 'import os\n'), ((1665, 1692), 'os.makedirs', 'os.makedirs', (['mindrecord_dir'], {}), '(mindrecord_dir)\n', (1676, 1692), False, 'import os\n'), ((1745, 1776), 'os.path.isdir', 'os.path.isdir', (['config.coco_root'], {}), '(config.coco_root)\n', (1758, 1776), False, 'import os\n'), ((2413, 2428), 'vega.datasets.conf.dataset.DatasetConfig', 'DatasetConfig', ([], {}), '()\n', (2426, 2428), False, 'from vega.datasets.conf.dataset import DatasetConfig\n'), ((2786, 2817), 'os.path.exists', 'os.path.exists', (['mindrecord_file'], {}), '(mindrecord_file)\n', (2800, 2817), False, 'import os\n'), ((2834, 2863), 'os.path.isdir', 'os.path.isdir', (['mindrecord_dir'], {}), '(mindrecord_dir)\n', (2847, 2863), False, 'import os\n'), ((2877, 2904), 'os.makedirs', 'os.makedirs', (['mindrecord_dir'], {}), '(mindrecord_dir)\n', (2888, 2904), False, 'import os\n'), ((2957, 2988), 'os.path.isdir', 'os.path.isdir', (['config.coco_root'], {}), '(config.coco_root)\n', (2970, 2988), False, 'import os\n'), ((1901, 1937), 'logging.info', 'logging.info', (['"""coco_root not exits."""'], {}), "('coco_root not exits.')\n", (1913, 1937), False, 'import logging\n'), ((1967, 1998), 'os.path.isdir', 'os.path.isdir', (['config.IMAGE_DIR'], {}), '(config.IMAGE_DIR)\n', (1980, 1998), False, 'import os\n'), ((2003, 2035), 'os.path.exists', 'os.path.exists', (['config.ANNO_PATH'], {}), '(config.ANNO_PATH)\n', (2017, 2035), False, 'import os\n'), ((2161, 2210), 'logging.info', 'logging.info', (['"""IMAGE_DIR or ANNO_PATH not exits."""'], {}), "('IMAGE_DIR or ANNO_PATH not exits.')\n", (2173, 2210), False, 'import logging\n'), ((3292, 3328), 'logging.info', 'logging.info', (['"""coco_root not exits."""'], {}), "('coco_root not exits.')\n", (3304, 3328), False, 'import logging\n'), ((3358, 3389), 'os.path.isdir', 'os.path.isdir', (['config.image_dir'], {}), '(config.image_dir)\n', (3371, 3389), False, 'import os\n'), ((3394, 3426), 'os.path.exists', 'os.path.exists', (['config.anno_path'], {}), '(config.anno_path)\n', (3408, 3426), False, 'import os\n'), ((3731, 3780), 'logging.info', 'logging.info', (['"""image_dir or anno_path not exits."""'], {}), "('image_dir or anno_path not exits.')\n", (3743, 3780), False, 'import logging\n'), ((3013, 3045), 'os.path.exists', 'os.path.exists', (['config.coco_root'], {}), '(config.coco_root)\n', (3027, 3045), False, 'import os\n'), ((3067, 3126), 'logging.info', 'logging.info', (['"""Please make sure config:coco_root is valid."""'], {}), "('Please make sure config:coco_root is valid.')\n", (3079, 3126), False, 'import logging\n'), ((3451, 3483), 'os.path.exists', 'os.path.exists', (['config.image_dir'], {}), '(config.image_dir)\n', (3465, 3483), False, 'import os\n'), ((3505, 3564), 'logging.info', 'logging.info', (['"""Please make sure config:image_dir is valid."""'], {}), "('Please make sure config:image_dir is valid.')\n", (3517, 3564), False, 'import logging\n'), ((7638, 7677), 'numpy.argsort', 'np.argsort', (['(-all_bboxes_tmp_mask[:, -1])'], {}), '(-all_bboxes_tmp_mask[:, -1])\n', (7648, 7677), True, 'import numpy as np\n')]
import argparse import os import numpy as np task_name = ['MNLI', 'QNLI', 'QQP', 'RTE', 'SST-2', 'MRPC', 'CoLA', 'STS-B'] dataset_dir_name = ['MNLI-bin', 'QNLI-bin', 'QQP-bin', 'RTE-bin', 'SST-2-bin', 'MRPC-bin', 'CoLA-bin', 'STS-B-bin'] num_classes = [3,2,2,2,2,2,2,1] lrs = [1e-5, 1e-5, 1e-5, 2e-5, 1e-5, 1e-5, 1e-5, 2e-5] max_sentences = [32,32,32,16,32,16,16,16] total_num_updates = [123873, 33112, 113272, 2036, 20935, 2296, 5336, 3598] warm_updates = [7432, 1986, 28318, 122, 1256, 137, 320, 214] if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--arch', type=str, default='robert_base', choices=['roberta_base', 'roberta_leaner', 'roberta_base_deepsup', 'roberta_base_norm_fl', 'roberta_base-se']) parser.add_argument('--task', type=str, default='SST-2', choices=task_name) parser.add_argument('-d', type=int, default=0) parser.add_argument('-p', type=str) args = parser.parse_args() index = task_name.index(args.task) rand_int = np.random.randint(0, 1000000000) print('Random Seed: {}'.format(rand_int)) cmds =["CUDA_VISIBLE_DEVICES={}".format(args.d), " python3 train.py ~/data/glue-32768-fast/{}/ ".format(dataset_dir_name[index]), "--restore-file {} ".format(args.p), "--max-positions 512 --max-sentences {} ".format(max_sentences[index]), "--max-tokens 4400 --task sentence_prediction --reset-optimizer ", "--reset-dataloader --reset-meters --required-batch-size-multiple 1 \ --init-token 0 --separator-token 2 ", "--arch {} ".format(args.arch), "--criterion sentence_prediction ", "--num-classes {} ".format(num_classes[index]), "--dropout 0.1 --attention-dropout 0.1 --weight-decay 0.1 \ --optimizer adam --adam-betas '(0.9, 0.98)' --adam-eps 1e-06 \ --clip-norm 0.0 --lr-scheduler polynomial_decay ", "--lr {} --total-num-update {} ".format(lrs[index], total_num_updates[index]), "--warmup-updates {} --seed {} ".format(warm_updates[index], rand_int), "--max-epoch 10 \ --find-unused-parameters \ --best-checkpoint-metric accuracy --maximize-best-checkpoint-metric;" ] cmd = ' ' for c in cmds: cmd += c print(cmd) os.system(cmd)
[ "numpy.random.randint", "os.system", "argparse.ArgumentParser" ]
[((593, 618), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (616, 618), False, 'import argparse\n'), ((1176, 1208), 'numpy.random.randint', 'np.random.randint', (['(0)', '(1000000000)'], {}), '(0, 1000000000)\n', (1193, 1208), True, 'import numpy as np\n'), ((2396, 2410), 'os.system', 'os.system', (['cmd'], {}), '(cmd)\n', (2405, 2410), False, 'import os\n')]
import numpy as np import cv2 import matplotlib.pyplot as plt from PIL import Image, ImageDraw # https://stackoverflow.com/questions/52540037/create-image-using-matplotlib-imshow-meshgrid-and-custom-colors def flow_to_rgb(flows): """ Convert a flow to a rgb value Args: flows: (N, 3) vector flow Returns: (N, 3) RGB values normalized between 0 and 1 """ # https://stackoverflow.com/questions/28898346/visualize-optical-flow-with-color-model # Use Hue, Saturation, Value colour model hsv = np.zeros((flows.shape[0], 1, 3), dtype=np.uint8) hsv[..., 1] = 255 mag, ang = cv2.cartToPolar(flows[..., 0], flows[..., 1]) hsv[..., 0] = ang * 180 / np.pi / 2 hsv[..., 2] = cv2.normalize(mag, None, 0, 255, cv2.NORM_MINMAX) rgb = cv2.cvtColor(hsv, cv2.COLOR_HSV2RGB) rgb = rgb[:, 0, :] / 255. # Normalize to 1 rgb[rgb < 0.2] = 0.2 # Just for visualize not moving points return rgb def colour_wheel(samples=1024): xx, yy = np.meshgrid( np.linspace(-1, 1, samples), np.linspace(-1, 1, samples)) flows = np.vstack([yy.ravel(), xx.ravel()]).T rgb_flows = flow_to_rgb(flows) rgb_flows = np.reshape(rgb_flows, (samples, samples, 3)) res = np.zeros((xx.shape[0], xx.shape[1], 3)) for i in range(xx.shape[0]): print(i) for j in range(xx.shape[1]): res[i, j, :] = rgb_flows[i, j] plt.figure(dpi=100) plt.imshow(res) plt.show() colour_wheel()
[ "cv2.cartToPolar", "matplotlib.pyplot.show", "cv2.cvtColor", "matplotlib.pyplot.imshow", "numpy.zeros", "matplotlib.pyplot.figure", "numpy.reshape", "numpy.linspace", "cv2.normalize" ]
[((533, 581), 'numpy.zeros', 'np.zeros', (['(flows.shape[0], 1, 3)'], {'dtype': 'np.uint8'}), '((flows.shape[0], 1, 3), dtype=np.uint8)\n', (541, 581), True, 'import numpy as np\n'), ((620, 665), 'cv2.cartToPolar', 'cv2.cartToPolar', (['flows[..., 0]', 'flows[..., 1]'], {}), '(flows[..., 0], flows[..., 1])\n', (635, 665), False, 'import cv2\n'), ((724, 773), 'cv2.normalize', 'cv2.normalize', (['mag', 'None', '(0)', '(255)', 'cv2.NORM_MINMAX'], {}), '(mag, None, 0, 255, cv2.NORM_MINMAX)\n', (737, 773), False, 'import cv2\n'), ((784, 820), 'cv2.cvtColor', 'cv2.cvtColor', (['hsv', 'cv2.COLOR_HSV2RGB'], {}), '(hsv, cv2.COLOR_HSV2RGB)\n', (796, 820), False, 'import cv2\n'), ((1181, 1225), 'numpy.reshape', 'np.reshape', (['rgb_flows', '(samples, samples, 3)'], {}), '(rgb_flows, (samples, samples, 3))\n', (1191, 1225), True, 'import numpy as np\n'), ((1237, 1276), 'numpy.zeros', 'np.zeros', (['(xx.shape[0], xx.shape[1], 3)'], {}), '((xx.shape[0], xx.shape[1], 3))\n', (1245, 1276), True, 'import numpy as np\n'), ((1412, 1431), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'dpi': '(100)'}), '(dpi=100)\n', (1422, 1431), True, 'import matplotlib.pyplot as plt\n'), ((1436, 1451), 'matplotlib.pyplot.imshow', 'plt.imshow', (['res'], {}), '(res)\n', (1446, 1451), True, 'import matplotlib.pyplot as plt\n'), ((1456, 1466), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1464, 1466), True, 'import matplotlib.pyplot as plt\n'), ((1021, 1048), 'numpy.linspace', 'np.linspace', (['(-1)', '(1)', 'samples'], {}), '(-1, 1, samples)\n', (1032, 1048), True, 'import numpy as np\n'), ((1050, 1077), 'numpy.linspace', 'np.linspace', (['(-1)', '(1)', 'samples'], {}), '(-1, 1, samples)\n', (1061, 1077), True, 'import numpy as np\n')]
from __future__ import division import os.path import numpy as np import scipy.stats import matplotlib matplotlib.use('Agg') matplotlib.rc('font',family='serif') import matplotlib.pyplot as plt from covar import cov_shrink_ss, cov_shrink_rblw DIRNAME = os.path.dirname(os.path.realpath(__file__)) def test_1(): random = np.random.RandomState(0) p = 100 sigma = scipy.stats.wishart(scale=np.eye(p), seed=random).rvs() Ns = [int(x) for x in [p/10, p/2, 2*p, 10*p]] x = np.arange(p) plt.figure(figsize=(8,8)) for i, N in enumerate(Ns): X = random.multivariate_normal(mean=np.zeros(p), cov=sigma, size=N) S1 = np.cov(X.T) S2 = cov_shrink_ss(X)[0] S3 = cov_shrink_rblw(np.cov(X.T), len(X))[0] plt.subplot(3,2,i+1) plt.title('p/n = %.1f' % (p/N)) plt.plot(x, sorted(np.linalg.eigvalsh(S2), reverse=True), 'b', lw=2, label='cov_shrink_ss') plt.plot(x, sorted(np.linalg.eigvalsh(S3), reverse=True), 'g', alpha=0.7, lw=2, label='cov_shrink_rblw') plt.plot(x, sorted(np.linalg.eigvalsh(sigma), reverse=True), 'k--', lw=2, label='true') plt.plot(x, sorted(np.linalg.eigvalsh(S1), reverse=True), 'r--', lw=2, label='sample covariance') if i == 1: plt.legend(fontsize=10) # plt.ylim(max(plt.ylim()[0], 1e-4), plt.ylim()[1]) plt.figtext(.05, .05, """Ordered eigenvalues of the sample covariance matrix (red), cov_shrink_ss()-estimated covariance matrix (blue), cov_shrink_rblw()-estimated covariance matrix (green), and true eigenvalues (dashed black). The data generated by sampling from a p-variate normal distribution for p=100 and various ratios of p/n. Note that for the larger value of p/n, the cov_shrink_rblw() estimator is identical to the sample covariance matrix.""") # plt.yscale('log') plt.ylabel('Eigenvalue') plt.tight_layout() plt.savefig('%s/test_2.png' % DIRNAME, dpi=300)
[ "matplotlib.pyplot.title", "matplotlib.pyplot.subplot", "matplotlib.rc", "numpy.eye", "matplotlib.pyplot.legend", "numpy.zeros", "numpy.random.RandomState", "matplotlib.pyplot.figtext", "numpy.linalg.eigvalsh", "matplotlib.pyplot.figure", "matplotlib.use", "numpy.arange", "covar.cov_shrink_s...
[((103, 124), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (117, 124), False, 'import matplotlib\n'), ((125, 162), 'matplotlib.rc', 'matplotlib.rc', (['"""font"""'], {'family': '"""serif"""'}), "('font', family='serif')\n", (138, 162), False, 'import matplotlib\n'), ((327, 351), 'numpy.random.RandomState', 'np.random.RandomState', (['(0)'], {}), '(0)\n', (348, 351), True, 'import numpy as np\n'), ((490, 502), 'numpy.arange', 'np.arange', (['p'], {}), '(p)\n', (499, 502), True, 'import numpy as np\n'), ((508, 534), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(8, 8)'}), '(figsize=(8, 8))\n', (518, 534), True, 'import matplotlib.pyplot as plt\n'), ((1887, 1905), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (1903, 1905), True, 'import matplotlib.pyplot as plt\n'), ((1910, 1957), 'matplotlib.pyplot.savefig', 'plt.savefig', (["('%s/test_2.png' % DIRNAME)"], {'dpi': '(300)'}), "('%s/test_2.png' % DIRNAME, dpi=300)\n", (1921, 1957), True, 'import matplotlib.pyplot as plt\n'), ((655, 666), 'numpy.cov', 'np.cov', (['X.T'], {}), '(X.T)\n', (661, 666), True, 'import numpy as np\n'), ((762, 786), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(3)', '(2)', '(i + 1)'], {}), '(3, 2, i + 1)\n', (773, 786), True, 'import matplotlib.pyplot as plt\n'), ((791, 824), 'matplotlib.pyplot.title', 'plt.title', (["('p/n = %.1f' % (p / N))"], {}), "('p/n = %.1f' % (p / N))\n", (800, 824), True, 'import matplotlib.pyplot as plt\n'), ((1365, 1830), 'matplotlib.pyplot.figtext', 'plt.figtext', (['(0.05)', '(0.05)', '"""Ordered eigenvalues of the sample covariance matrix (red),\ncov_shrink_ss()-estimated covariance matrix (blue),\ncov_shrink_rblw()-estimated covariance matrix (green), and\ntrue eigenvalues (dashed black). The data generated by sampling\nfrom a p-variate normal distribution for p=100 and various\nratios of p/n. Note that for the larger value of p/n, the\ncov_shrink_rblw() estimator is identical to the sample\ncovariance matrix."""'], {}), '(0.05, 0.05,\n """Ordered eigenvalues of the sample covariance matrix (red),\ncov_shrink_ss()-estimated covariance matrix (blue),\ncov_shrink_rblw()-estimated covariance matrix (green), and\ntrue eigenvalues (dashed black). The data generated by sampling\nfrom a p-variate normal distribution for p=100 and various\nratios of p/n. Note that for the larger value of p/n, the\ncov_shrink_rblw() estimator is identical to the sample\ncovariance matrix."""\n )\n', (1376, 1830), True, 'import matplotlib.pyplot as plt\n'), ((1857, 1881), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Eigenvalue"""'], {}), "('Eigenvalue')\n", (1867, 1881), True, 'import matplotlib.pyplot as plt\n'), ((680, 696), 'covar.cov_shrink_ss', 'cov_shrink_ss', (['X'], {}), '(X)\n', (693, 696), False, 'from covar import cov_shrink_ss, cov_shrink_rblw\n'), ((1272, 1295), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'fontsize': '(10)'}), '(fontsize=10)\n', (1282, 1295), True, 'import matplotlib.pyplot as plt\n'), ((610, 621), 'numpy.zeros', 'np.zeros', (['p'], {}), '(p)\n', (618, 621), True, 'import numpy as np\n'), ((729, 740), 'numpy.cov', 'np.cov', (['X.T'], {}), '(X.T)\n', (735, 740), True, 'import numpy as np\n'), ((851, 873), 'numpy.linalg.eigvalsh', 'np.linalg.eigvalsh', (['S2'], {}), '(S2)\n', (869, 873), True, 'import numpy as np\n'), ((952, 974), 'numpy.linalg.eigvalsh', 'np.linalg.eigvalsh', (['S3'], {}), '(S3)\n', (970, 974), True, 'import numpy as np\n'), ((1065, 1090), 'numpy.linalg.eigvalsh', 'np.linalg.eigvalsh', (['sigma'], {}), '(sigma)\n', (1083, 1090), True, 'import numpy as np\n'), ((1161, 1183), 'numpy.linalg.eigvalsh', 'np.linalg.eigvalsh', (['S1'], {}), '(S1)\n', (1179, 1183), True, 'import numpy as np\n'), ((402, 411), 'numpy.eye', 'np.eye', (['p'], {}), '(p)\n', (408, 411), True, 'import numpy as np\n')]
""" Training with OCCD and testing with CCD. Email: <EMAIL> Dtd: 2 - August - 2020 Parameters ---------- classification_type : string DESCRIPTION - classification_type == "binary_class" loads binary classification artificial data. classification_type == "multi_class" loads multiclass artificial data epsilon : scalar, float DESCRIPTION - A value in the range 0 and 0.3. for eg. epsilon = 0.1835 initial_neural_activity : scalar, float DESCRIPTION - The chaotic neurons has an initial neural activity. Initial neural activity is a value in the range 0 and 1. discrimination_threshold : scalar, float DESCRIPTION - The chaotic neurons has a discrimination threhold. discrimination threshold is a value in the range 0 and 1. folder_name : string DESCRIPTION - the name of the folder to store results. For eg., if folder_name = "hnb", then this function will create two folder "hnb-svm" and "hnb-neurochaos" to save the classification report. target_names : array, 1D, string DESCRIPTION - if there are two classes, then target_names = ['class-0', class-1] Note- At the present version of the code, the results for binary classification and five class classification will be saved. Returns : None ------- Computes the accuracy_neurochaos, fscore_neurochaos """ import os import numpy as np from sklearn.metrics import f1_score, accuracy_score from sklearn.svm import LinearSVC from sklearn.metrics import confusion_matrix as cm from sklearn.metrics import classification_report import ChaosFEX.feature_extractor as CFX from load_data_synthetic import get_data classification_type_test = "concentric_circle" classification_type_train = "concentric_circle_noise" epsilon = 0.18 initial_neural_activity = 0.34 discrimination_threshold = 0.499 folder_name = "occd-train_ccd-test" target_names = ['class-0', 'class-1'] path = os.getcwd() result_path_neurochaos = path + '/NEUROCHAOS-NOISE-RESULTS/' + classification_type_test + '/' + folder_name +'-neurochaos/' # Creating Folder to save the results try: os.makedirs(result_path_neurochaos) except OSError: print("Creation of the result directory %s failed" % result_path_neurochaos) else: print("Successfully created the result directory %s" % result_path_neurochaos) ## TEST DATA ccd_train_data, ccd_train_label, ccd_test_data, ccd_test_label = get_data(classification_type_test) ## TRAIN DATA occd_train_data, occd_train_label, occd_test_data, occd_test_label = get_data(classification_type_train) num_classes = len(np.unique(ccd_test_label)) # Number of classes print("**** Genome data details ******") for class_label in range(np.max(ccd_train_label) + 1): print("Total Data instance in Class -", class_label, " = ", ccd_train_label.tolist().count([class_label])) print(" train data = ", (occd_train_data.shape[0])) print("test data = ", (ccd_train_data.shape[0])) print("initial neural activity = ", initial_neural_activity, "discrimination threshold = ", discrimination_threshold, "epsilon = ", epsilon) # Extracting Neurochaos features from the data neurochaos_train_data_features = CFX.transform(occd_train_data, initial_neural_activity, 20000, epsilon, discrimination_threshold) neurochaos_val_data_features = CFX.transform(ccd_train_data, initial_neural_activity, 20000, epsilon, discrimination_threshold) # Start of Neurochaos classifier neurochaos_classifier = LinearSVC(random_state=0, tol=1e-5, dual=False) neurochaos_classifier.fit(neurochaos_train_data_features, occd_train_label[:, 0]) predicted_neurochaos_val_label = neurochaos_classifier.predict(neurochaos_val_data_features) acc_neurochaos = accuracy_score(ccd_train_label, predicted_neurochaos_val_label)*100 f1score_neurochaos = f1_score(ccd_train_label, predicted_neurochaos_val_label, average="macro") report_neurochaos = classification_report(ccd_train_label, predicted_neurochaos_val_label, target_names=target_names) # Saving the classification report to csv file for neurochaos classifier. print(report_neurochaos) #classification_report_csv_(report_neurochaos, num_classes).to_csv(result_path_neurochaos+'neurochaos_report_'+ str(iterations) +'.csv', index=False) confusion_matrix_neurochaos = cm(ccd_train_label, predicted_neurochaos_val_label) print("Confusion matrix for Neurochaos\n", confusion_matrix_neurochaos) # End of ChaosFEX. np.save(result_path_neurochaos + 'initial_neural_activity.npy', initial_neural_activity) np.save(result_path_neurochaos + 'discrimination_threshold.npy', discrimination_threshold) np.save(result_path_neurochaos + 'EPS.npy', epsilon) np.save(result_path_neurochaos + 'f1score.npy', f1score_neurochaos)
[ "numpy.save", "os.makedirs", "os.getcwd", "sklearn.metrics.accuracy_score", "sklearn.metrics.classification_report", "sklearn.metrics.f1_score", "numpy.max", "sklearn.svm.LinearSVC", "sklearn.metrics.confusion_matrix", "ChaosFEX.feature_extractor.transform", "numpy.unique", "load_data_syntheti...
[((1934, 1945), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (1943, 1945), False, 'import os\n'), ((2434, 2468), 'load_data_synthetic.get_data', 'get_data', (['classification_type_test'], {}), '(classification_type_test)\n', (2442, 2468), False, 'from load_data_synthetic import get_data\n'), ((2554, 2589), 'load_data_synthetic.get_data', 'get_data', (['classification_type_train'], {}), '(classification_type_train)\n', (2562, 2589), False, 'from load_data_synthetic import get_data\n'), ((3214, 3315), 'ChaosFEX.feature_extractor.transform', 'CFX.transform', (['occd_train_data', 'initial_neural_activity', '(20000)', 'epsilon', 'discrimination_threshold'], {}), '(occd_train_data, initial_neural_activity, 20000, epsilon,\n discrimination_threshold)\n', (3227, 3315), True, 'import ChaosFEX.feature_extractor as CFX\n'), ((3344, 3444), 'ChaosFEX.feature_extractor.transform', 'CFX.transform', (['ccd_train_data', 'initial_neural_activity', '(20000)', 'epsilon', 'discrimination_threshold'], {}), '(ccd_train_data, initial_neural_activity, 20000, epsilon,\n discrimination_threshold)\n', (3357, 3444), True, 'import ChaosFEX.feature_extractor as CFX\n'), ((3502, 3550), 'sklearn.svm.LinearSVC', 'LinearSVC', ([], {'random_state': '(0)', 'tol': '(1e-05)', 'dual': '(False)'}), '(random_state=0, tol=1e-05, dual=False)\n', (3511, 3550), False, 'from sklearn.svm import LinearSVC\n'), ((3839, 3913), 'sklearn.metrics.f1_score', 'f1_score', (['ccd_train_label', 'predicted_neurochaos_val_label'], {'average': '"""macro"""'}), "(ccd_train_label, predicted_neurochaos_val_label, average='macro')\n", (3847, 3913), False, 'from sklearn.metrics import f1_score, accuracy_score\n'), ((3935, 4036), 'sklearn.metrics.classification_report', 'classification_report', (['ccd_train_label', 'predicted_neurochaos_val_label'], {'target_names': 'target_names'}), '(ccd_train_label, predicted_neurochaos_val_label,\n target_names=target_names)\n', (3956, 4036), False, 'from sklearn.metrics import classification_report\n'), ((4324, 4375), 'sklearn.metrics.confusion_matrix', 'cm', (['ccd_train_label', 'predicted_neurochaos_val_label'], {}), '(ccd_train_label, predicted_neurochaos_val_label)\n', (4326, 4375), True, 'from sklearn.metrics import confusion_matrix as cm\n'), ((4474, 4566), 'numpy.save', 'np.save', (["(result_path_neurochaos + 'initial_neural_activity.npy')", 'initial_neural_activity'], {}), "(result_path_neurochaos + 'initial_neural_activity.npy',\n initial_neural_activity)\n", (4481, 4566), True, 'import numpy as np\n'), ((4564, 4658), 'numpy.save', 'np.save', (["(result_path_neurochaos + 'discrimination_threshold.npy')", 'discrimination_threshold'], {}), "(result_path_neurochaos + 'discrimination_threshold.npy',\n discrimination_threshold)\n", (4571, 4658), True, 'import numpy as np\n'), ((4656, 4708), 'numpy.save', 'np.save', (["(result_path_neurochaos + 'EPS.npy')", 'epsilon'], {}), "(result_path_neurochaos + 'EPS.npy', epsilon)\n", (4663, 4708), True, 'import numpy as np\n'), ((4710, 4777), 'numpy.save', 'np.save', (["(result_path_neurochaos + 'f1score.npy')", 'f1score_neurochaos'], {}), "(result_path_neurochaos + 'f1score.npy', f1score_neurochaos)\n", (4717, 4777), True, 'import numpy as np\n'), ((2126, 2161), 'os.makedirs', 'os.makedirs', (['result_path_neurochaos'], {}), '(result_path_neurochaos)\n', (2137, 2161), False, 'import os\n'), ((2611, 2636), 'numpy.unique', 'np.unique', (['ccd_test_label'], {}), '(ccd_test_label)\n', (2620, 2636), True, 'import numpy as np\n'), ((3749, 3812), 'sklearn.metrics.accuracy_score', 'accuracy_score', (['ccd_train_label', 'predicted_neurochaos_val_label'], {}), '(ccd_train_label, predicted_neurochaos_val_label)\n', (3763, 3812), False, 'from sklearn.metrics import f1_score, accuracy_score\n'), ((2728, 2751), 'numpy.max', 'np.max', (['ccd_train_label'], {}), '(ccd_train_label)\n', (2734, 2751), True, 'import numpy as np\n')]
# Copyright 2020 Huawei Technologies Co., Ltd # # 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. # ============================================================================ """ Data operations, will be used in run_pretrain.py """ import os import math import numpy as np import mindspore.common.dtype as mstype import mindspore.dataset as ds import mindspore.dataset.transforms.c_transforms as C from mindspore import log as logger class BucketDatasetGenerator: """ Provide data distribution of different gears for the bert network. Args: dataset (Dataset): The training dataset. batch_size (Int): The training batchsize. bucket_list (List): List of different sentence lengths,such as [128, 256, 512]. Default: None. """ def __init__(self, dataset, batch_size, bucket_list=None): self.dataset = dataset self.batch_size = batch_size self.bucket_list = bucket_list self.data_bucket = {bucket: [] for bucket in bucket_list} bucket_size = len(bucket_list) self.random_list = np.random.binomial(n=(bucket_size - 1), p=0.5, size=self.__len__()) self.random_list = (self.random_list + 2) % bucket_size self.random_list = [bucket_list[i] for i in self.random_list] self.iter = 0 def __next__(self): for item in self.iterator: for seq_length in self.bucket_list: if np.sum(item[1]) <= seq_length: self.data_bucket[seq_length].append(item) break for key in self.data_bucket.keys(): data = self.data_bucket[key] if len(data) >= self.batch_size and self.random_list[self.iter] == key: self.data_bucket[key] = self.data_bucket[key][self.batch_size:] arr = data[0] for i in range(1, self.batch_size): current_data = data[i] for j in range(len(current_data)): arr[j] = np.concatenate((arr[j], current_data[j])) res = () for label in arr: newlabel = np.reshape(label, (self.batch_size, -1)) res += (newlabel,) res += (np.array(key, np.int32),) self.iter += 1 return res raise StopIteration def __iter__(self): self.iterator = self.dataset.create_tuple_iterator(output_numpy=True) return self def __len__(self): return (self.dataset.get_dataset_size() // self.batch_size) - 1 def create_bert_dataset(device_num=1, rank=0, do_shuffle="true", data_dir=None, schema_dir=None, batch_size=32, bucket_list=None): """create train dataset""" # apply repeat operations files = os.listdir(data_dir) data_files = [] for file_name in files: if "tfrecord" in file_name: data_files.append(os.path.join(data_dir, file_name)) data_set = ds.TFRecordDataset(data_files, schema_dir if schema_dir != "" else None, columns_list=["input_ids", "input_mask", "segment_ids", "next_sentence_labels", "masked_lm_positions", "masked_lm_ids", "masked_lm_weights"], shuffle=ds.Shuffle.FILES if do_shuffle == "true" else False, num_shards=device_num, shard_id=rank, shard_equal_rows=True) if bucket_list: bucket_dataset = BucketDatasetGenerator(data_set, batch_size, bucket_list=bucket_list) data_set = ds.GeneratorDataset(bucket_dataset, column_names=["input_ids", "input_mask", "segment_ids", "next_sentence_labels", "masked_lm_positions", "masked_lm_ids", "masked_lm_weights", "sentence_flag"], shuffle=False) else: data_set = data_set.batch(batch_size, drop_remainder=True) ori_dataset_size = data_set.get_dataset_size() print('origin dataset size: ', ori_dataset_size) type_cast_op = C.TypeCast(mstype.int32) data_set = data_set.map(operations=type_cast_op, input_columns="masked_lm_ids") data_set = data_set.map(operations=type_cast_op, input_columns="masked_lm_positions") data_set = data_set.map(operations=type_cast_op, input_columns="next_sentence_labels") data_set = data_set.map(operations=type_cast_op, input_columns="segment_ids") data_set = data_set.map(operations=type_cast_op, input_columns="input_mask") data_set = data_set.map(operations=type_cast_op, input_columns="input_ids") # apply batch operations logger.info("data size: {}".format(data_set.get_dataset_size())) logger.info("repeat count: {}".format(data_set.get_repeat_count())) return data_set def create_ner_dataset(batch_size=1, repeat_count=1, assessment_method="accuracy", data_file_path=None, dataset_format="mindrecord", schema_file_path=None, do_shuffle=True, drop_remainder=True): """create finetune or evaluation dataset""" type_cast_op = C.TypeCast(mstype.int32) if dataset_format == "mindrecord": dataset = ds.MindDataset([data_file_path], columns_list=["input_ids", "input_mask", "segment_ids", "label_ids"], shuffle=do_shuffle) else: dataset = ds.TFRecordDataset([data_file_path], schema_file_path if schema_file_path != "" else None, columns_list=["input_ids", "input_mask", "segment_ids", "label_ids"], shuffle=do_shuffle) if assessment_method == "Spearman_correlation": type_cast_op_float = C.TypeCast(mstype.float32) dataset = dataset.map(operations=type_cast_op_float, input_columns="label_ids") else: dataset = dataset.map(operations=type_cast_op, input_columns="label_ids") dataset = dataset.map(operations=type_cast_op, input_columns="segment_ids") dataset = dataset.map(operations=type_cast_op, input_columns="input_mask") dataset = dataset.map(operations=type_cast_op, input_columns="input_ids") dataset = dataset.repeat(repeat_count) # apply batch operations dataset = dataset.batch(batch_size, drop_remainder=drop_remainder) return dataset def create_classification_dataset(batch_size=1, repeat_count=1, assessment_method="accuracy", data_file_path=None, schema_file_path=None, do_shuffle=True): """create finetune or evaluation dataset""" type_cast_op = C.TypeCast(mstype.int32) data_set = ds.TFRecordDataset([data_file_path], schema_file_path if schema_file_path != "" else None, columns_list=["input_ids", "input_mask", "segment_ids", "label_ids"], shuffle=do_shuffle) if assessment_method == "Spearman_correlation": type_cast_op_float = C.TypeCast(mstype.float32) data_set = data_set.map(operations=type_cast_op_float, input_columns="label_ids") else: data_set = data_set.map(operations=type_cast_op, input_columns="label_ids") data_set = data_set.map(operations=type_cast_op, input_columns="segment_ids") data_set = data_set.map(operations=type_cast_op, input_columns="input_mask") data_set = data_set.map(operations=type_cast_op, input_columns="input_ids") data_set = data_set.repeat(repeat_count) # apply batch operations data_set = data_set.batch(batch_size, drop_remainder=True) return data_set def generator_squad(data_features): for feature in data_features: yield (feature.input_ids, feature.input_mask, feature.segment_ids, feature.unique_id) def create_squad_dataset(batch_size=1, repeat_count=1, data_file_path=None, schema_file_path=None, is_training=True, do_shuffle=True): """create finetune or evaluation dataset""" type_cast_op = C.TypeCast(mstype.int32) if is_training: data_set = ds.TFRecordDataset([data_file_path], schema_file_path if schema_file_path != "" else None, columns_list=["input_ids", "input_mask", "segment_ids", "start_positions", "end_positions", "unique_ids", "is_impossible"], shuffle=do_shuffle) data_set = data_set.map(operations=type_cast_op, input_columns="start_positions") data_set = data_set.map(operations=type_cast_op, input_columns="end_positions") else: data_set = ds.GeneratorDataset(generator_squad(data_file_path), shuffle=do_shuffle, column_names=["input_ids", "input_mask", "segment_ids", "unique_ids"]) data_set = data_set.map(operations=type_cast_op, input_columns="segment_ids") data_set = data_set.map(operations=type_cast_op, input_columns="input_mask") data_set = data_set.map(operations=type_cast_op, input_columns="input_ids") data_set = data_set.map(operations=type_cast_op, input_columns="unique_ids") data_set = data_set.repeat(repeat_count) # apply batch operations data_set = data_set.batch(batch_size, drop_remainder=True) return data_set def create_eval_dataset(batchsize=32, device_num=1, rank=0, data_dir=None, schema_dir=None): """create evaluation dataset""" data_files = [] if os.path.isdir(data_dir): files = os.listdir(data_dir) for file_name in files: if "tfrecord" in file_name: data_files.append(os.path.join(data_dir, file_name)) else: data_files.append(data_dir) data_set = ds.TFRecordDataset(data_files, schema_dir if schema_dir != "" else None, columns_list=["input_ids", "input_mask", "segment_ids", "next_sentence_labels", "masked_lm_positions", "masked_lm_ids", "masked_lm_weights"], shard_equal_rows=True) ori_dataset_size = data_set.get_dataset_size() print("origin eval size: ", ori_dataset_size) dtypes = data_set.output_types() shapes = data_set.output_shapes() output_batches = math.ceil(ori_dataset_size / device_num / batchsize) padded_num = output_batches * device_num * batchsize - ori_dataset_size print("padded num: ", padded_num) if padded_num > 0: item = {"input_ids": np.zeros(shapes[0], dtypes[0]), "input_mask": np.zeros(shapes[1], dtypes[1]), "segment_ids": np.zeros(shapes[2], dtypes[2]), "next_sentence_labels": np.zeros(shapes[3], dtypes[3]), "masked_lm_positions": np.zeros(shapes[4], dtypes[4]), "masked_lm_ids": np.zeros(shapes[5], dtypes[5]), "masked_lm_weights": np.zeros(shapes[6], dtypes[6])} padded_samples = [item for x in range(padded_num)] padded_ds = ds.PaddedDataset(padded_samples) eval_ds = data_set + padded_ds sampler = ds.DistributedSampler(num_shards=device_num, shard_id=rank, shuffle=False) eval_ds.use_sampler(sampler) else: eval_ds = ds.TFRecordDataset(data_files, schema_dir if schema_dir != "" else None, columns_list=["input_ids", "input_mask", "segment_ids", "next_sentence_labels", "masked_lm_positions", "masked_lm_ids", "masked_lm_weights"], num_shards=device_num, shard_id=rank, shard_equal_rows=True) type_cast_op = C.TypeCast(mstype.int32) eval_ds = eval_ds.map(input_columns="masked_lm_ids", operations=type_cast_op) eval_ds = eval_ds.map(input_columns="masked_lm_positions", operations=type_cast_op) eval_ds = eval_ds.map(input_columns="next_sentence_labels", operations=type_cast_op) eval_ds = eval_ds.map(input_columns="segment_ids", operations=type_cast_op) eval_ds = eval_ds.map(input_columns="input_mask", operations=type_cast_op) eval_ds = eval_ds.map(input_columns="input_ids", operations=type_cast_op) eval_ds = eval_ds.batch(batchsize, drop_remainder=True) print("eval data size: {}".format(eval_ds.get_dataset_size())) print("eval repeat count: {}".format(eval_ds.get_repeat_count())) return eval_ds
[ "mindspore.dataset.PaddedDataset", "numpy.sum", "math.ceil", "os.path.isdir", "mindspore.dataset.transforms.c_transforms.TypeCast", "mindspore.dataset.MindDataset", "numpy.zeros", "mindspore.dataset.GeneratorDataset", "numpy.array", "numpy.reshape", "mindspore.dataset.TFRecordDataset", "mindsp...
[((3353, 3373), 'os.listdir', 'os.listdir', (['data_dir'], {}), '(data_dir)\n', (3363, 3373), False, 'import os\n'), ((3538, 3890), 'mindspore.dataset.TFRecordDataset', 'ds.TFRecordDataset', (['data_files', "(schema_dir if schema_dir != '' else None)"], {'columns_list': "['input_ids', 'input_mask', 'segment_ids', 'next_sentence_labels',\n 'masked_lm_positions', 'masked_lm_ids', 'masked_lm_weights']", 'shuffle': "(ds.Shuffle.FILES if do_shuffle == 'true' else False)", 'num_shards': 'device_num', 'shard_id': 'rank', 'shard_equal_rows': '(True)'}), "(data_files, schema_dir if schema_dir != '' else None,\n columns_list=['input_ids', 'input_mask', 'segment_ids',\n 'next_sentence_labels', 'masked_lm_positions', 'masked_lm_ids',\n 'masked_lm_weights'], shuffle=ds.Shuffle.FILES if do_shuffle == 'true' else\n False, num_shards=device_num, shard_id=rank, shard_equal_rows=True)\n", (3556, 3890), True, 'import mindspore.dataset as ds\n'), ((4753, 4777), 'mindspore.dataset.transforms.c_transforms.TypeCast', 'C.TypeCast', (['mstype.int32'], {}), '(mstype.int32)\n', (4763, 4777), True, 'import mindspore.dataset.transforms.c_transforms as C\n'), ((5763, 5787), 'mindspore.dataset.transforms.c_transforms.TypeCast', 'C.TypeCast', (['mstype.int32'], {}), '(mstype.int32)\n', (5773, 5787), True, 'import mindspore.dataset.transforms.c_transforms as C\n'), ((7263, 7287), 'mindspore.dataset.transforms.c_transforms.TypeCast', 'C.TypeCast', (['mstype.int32'], {}), '(mstype.int32)\n', (7273, 7287), True, 'import mindspore.dataset.transforms.c_transforms as C\n'), ((7303, 7491), 'mindspore.dataset.TFRecordDataset', 'ds.TFRecordDataset', (['[data_file_path]', "(schema_file_path if schema_file_path != '' else None)"], {'columns_list': "['input_ids', 'input_mask', 'segment_ids', 'label_ids']", 'shuffle': 'do_shuffle'}), "([data_file_path], schema_file_path if schema_file_path !=\n '' else None, columns_list=['input_ids', 'input_mask', 'segment_ids',\n 'label_ids'], shuffle=do_shuffle)\n", (7321, 7491), True, 'import mindspore.dataset as ds\n'), ((8639, 8663), 'mindspore.dataset.transforms.c_transforms.TypeCast', 'C.TypeCast', (['mstype.int32'], {}), '(mstype.int32)\n', (8649, 8663), True, 'import mindspore.dataset.transforms.c_transforms as C\n'), ((10095, 10118), 'os.path.isdir', 'os.path.isdir', (['data_dir'], {}), '(data_dir)\n', (10108, 10118), False, 'import os\n'), ((10359, 10608), 'mindspore.dataset.TFRecordDataset', 'ds.TFRecordDataset', (['data_files', "(schema_dir if schema_dir != '' else None)"], {'columns_list': "['input_ids', 'input_mask', 'segment_ids', 'next_sentence_labels',\n 'masked_lm_positions', 'masked_lm_ids', 'masked_lm_weights']", 'shard_equal_rows': '(True)'}), "(data_files, schema_dir if schema_dir != '' else None,\n columns_list=['input_ids', 'input_mask', 'segment_ids',\n 'next_sentence_labels', 'masked_lm_positions', 'masked_lm_ids',\n 'masked_lm_weights'], shard_equal_rows=True)\n", (10377, 10608), True, 'import mindspore.dataset as ds\n'), ((10910, 10962), 'math.ceil', 'math.ceil', (['(ori_dataset_size / device_num / batchsize)'], {}), '(ori_dataset_size / device_num / batchsize)\n', (10919, 10962), False, 'import math\n'), ((12293, 12317), 'mindspore.dataset.transforms.c_transforms.TypeCast', 'C.TypeCast', (['mstype.int32'], {}), '(mstype.int32)\n', (12303, 12317), True, 'import mindspore.dataset.transforms.c_transforms as C\n'), ((4159, 4376), 'mindspore.dataset.GeneratorDataset', 'ds.GeneratorDataset', (['bucket_dataset'], {'column_names': "['input_ids', 'input_mask', 'segment_ids', 'next_sentence_labels',\n 'masked_lm_positions', 'masked_lm_ids', 'masked_lm_weights',\n 'sentence_flag']", 'shuffle': '(False)'}), "(bucket_dataset, column_names=['input_ids', 'input_mask',\n 'segment_ids', 'next_sentence_labels', 'masked_lm_positions',\n 'masked_lm_ids', 'masked_lm_weights', 'sentence_flag'], shuffle=False)\n", (4178, 4376), True, 'import mindspore.dataset as ds\n'), ((5845, 5971), 'mindspore.dataset.MindDataset', 'ds.MindDataset', (['[data_file_path]'], {'columns_list': "['input_ids', 'input_mask', 'segment_ids', 'label_ids']", 'shuffle': 'do_shuffle'}), "([data_file_path], columns_list=['input_ids', 'input_mask',\n 'segment_ids', 'label_ids'], shuffle=do_shuffle)\n", (5859, 5971), True, 'import mindspore.dataset as ds\n'), ((6062, 6250), 'mindspore.dataset.TFRecordDataset', 'ds.TFRecordDataset', (['[data_file_path]', "(schema_file_path if schema_file_path != '' else None)"], {'columns_list': "['input_ids', 'input_mask', 'segment_ids', 'label_ids']", 'shuffle': 'do_shuffle'}), "([data_file_path], schema_file_path if schema_file_path !=\n '' else None, columns_list=['input_ids', 'input_mask', 'segment_ids',\n 'label_ids'], shuffle=do_shuffle)\n", (6080, 6250), True, 'import mindspore.dataset as ds\n'), ((6398, 6424), 'mindspore.dataset.transforms.c_transforms.TypeCast', 'C.TypeCast', (['mstype.float32'], {}), '(mstype.float32)\n', (6408, 6424), True, 'import mindspore.dataset.transforms.c_transforms as C\n'), ((7633, 7659), 'mindspore.dataset.transforms.c_transforms.TypeCast', 'C.TypeCast', (['mstype.float32'], {}), '(mstype.float32)\n', (7643, 7659), True, 'import mindspore.dataset.transforms.c_transforms as C\n'), ((8703, 8949), 'mindspore.dataset.TFRecordDataset', 'ds.TFRecordDataset', (['[data_file_path]', "(schema_file_path if schema_file_path != '' else None)"], {'columns_list': "['input_ids', 'input_mask', 'segment_ids', 'start_positions',\n 'end_positions', 'unique_ids', 'is_impossible']", 'shuffle': 'do_shuffle'}), "([data_file_path], schema_file_path if schema_file_path !=\n '' else None, columns_list=['input_ids', 'input_mask', 'segment_ids',\n 'start_positions', 'end_positions', 'unique_ids', 'is_impossible'],\n shuffle=do_shuffle)\n", (8721, 8949), True, 'import mindspore.dataset as ds\n'), ((10136, 10156), 'os.listdir', 'os.listdir', (['data_dir'], {}), '(data_dir)\n', (10146, 10156), False, 'import os\n'), ((11642, 11674), 'mindspore.dataset.PaddedDataset', 'ds.PaddedDataset', (['padded_samples'], {}), '(padded_samples)\n', (11658, 11674), True, 'import mindspore.dataset as ds\n'), ((11732, 11806), 'mindspore.dataset.DistributedSampler', 'ds.DistributedSampler', ([], {'num_shards': 'device_num', 'shard_id': 'rank', 'shuffle': '(False)'}), '(num_shards=device_num, shard_id=rank, shuffle=False)\n', (11753, 11806), True, 'import mindspore.dataset as ds\n'), ((11872, 12163), 'mindspore.dataset.TFRecordDataset', 'ds.TFRecordDataset', (['data_files', "(schema_dir if schema_dir != '' else None)"], {'columns_list': "['input_ids', 'input_mask', 'segment_ids', 'next_sentence_labels',\n 'masked_lm_positions', 'masked_lm_ids', 'masked_lm_weights']", 'num_shards': 'device_num', 'shard_id': 'rank', 'shard_equal_rows': '(True)'}), "(data_files, schema_dir if schema_dir != '' else None,\n columns_list=['input_ids', 'input_mask', 'segment_ids',\n 'next_sentence_labels', 'masked_lm_positions', 'masked_lm_ids',\n 'masked_lm_weights'], num_shards=device_num, shard_id=rank,\n shard_equal_rows=True)\n", (11890, 12163), True, 'import mindspore.dataset as ds\n'), ((11129, 11159), 'numpy.zeros', 'np.zeros', (['shapes[0]', 'dtypes[0]'], {}), '(shapes[0], dtypes[0])\n', (11137, 11159), True, 'import numpy as np\n'), ((11191, 11221), 'numpy.zeros', 'np.zeros', (['shapes[1]', 'dtypes[1]'], {}), '(shapes[1], dtypes[1])\n', (11199, 11221), True, 'import numpy as np\n'), ((11254, 11284), 'numpy.zeros', 'np.zeros', (['shapes[2]', 'dtypes[2]'], {}), '(shapes[2], dtypes[2])\n', (11262, 11284), True, 'import numpy as np\n'), ((11326, 11356), 'numpy.zeros', 'np.zeros', (['shapes[3]', 'dtypes[3]'], {}), '(shapes[3], dtypes[3])\n', (11334, 11356), True, 'import numpy as np\n'), ((11397, 11427), 'numpy.zeros', 'np.zeros', (['shapes[4]', 'dtypes[4]'], {}), '(shapes[4], dtypes[4])\n', (11405, 11427), True, 'import numpy as np\n'), ((11462, 11492), 'numpy.zeros', 'np.zeros', (['shapes[5]', 'dtypes[5]'], {}), '(shapes[5], dtypes[5])\n', (11470, 11492), True, 'import numpy as np\n'), ((11531, 11561), 'numpy.zeros', 'np.zeros', (['shapes[6]', 'dtypes[6]'], {}), '(shapes[6], dtypes[6])\n', (11539, 11561), True, 'import numpy as np\n'), ((3488, 3521), 'os.path.join', 'os.path.join', (['data_dir', 'file_name'], {}), '(data_dir, file_name)\n', (3500, 3521), False, 'import os\n'), ((1911, 1926), 'numpy.sum', 'np.sum', (['item[1]'], {}), '(item[1])\n', (1917, 1926), True, 'import numpy as np\n'), ((10263, 10296), 'os.path.join', 'os.path.join', (['data_dir', 'file_name'], {}), '(data_dir, file_name)\n', (10275, 10296), False, 'import os\n'), ((2672, 2712), 'numpy.reshape', 'np.reshape', (['label', '(self.batch_size, -1)'], {}), '(label, (self.batch_size, -1))\n', (2682, 2712), True, 'import numpy as np\n'), ((2784, 2807), 'numpy.array', 'np.array', (['key', 'np.int32'], {}), '(key, np.int32)\n', (2792, 2807), True, 'import numpy as np\n'), ((2528, 2569), 'numpy.concatenate', 'np.concatenate', (['(arr[j], current_data[j])'], {}), '((arr[j], current_data[j]))\n', (2542, 2569), True, 'import numpy as np\n')]
from astropy.io import fits import numpy as np from . import wcs #import wcs class FitsImage(wcs.WCS): def __init__(self,*args,extension=0): self.img=None self.hdr=None if len(args) !=0: if isinstance(args[0],str): filename=args[0] with fits.open(filename) as hdul: self.loadHDU(hdul[extension]) def loadHDU(self,hdu): self.img=hdu.data self.hdr=hdu.header wcs.WCS.__init__(self,self.hdr) @property def data(self): return self.img @property def header(self): return self.hdr def __str__(self): return "fits image: {}x{} pix2\n".format(self.naxis[0],self.naxis[1]) def __contains__(self,key): return key in self.hdr def __eq__(self,val): if isinstance(val,(int,float)): return self.img==val def __setitem__(self,key,value): self.hdr[key]=value def __getitem__(self,key): return self.hdr[key] def pixelValue(self,x,y): return self.dat[y,x] def extract(self,x0,x1,y0,y1,filename=None): # update x1+=1 y1+=1 # trim to be in the range x0=np.clip(x0,0,self.naxis[0]) x1=np.clip(x1,0,self.naxis[0]) y0=np.clip(y0,0,self.naxis[1]) y1=np.clip(y1,0,self.naxis[1]) # copy over the data and the header img=self.img[y0:y1,x0:x1] hdr=self.hdr.copy() # update the new header keywords hdr['NAXIS1']=x1-x0 hdr['NAXIS2']=y1-y0 hdr['CRPIX1']-=x0 hdr['CRPIX2']-=y0 hdr['LTV1']=-x0 hdr['LTV2']=-y0 # create the new data to return new=fits.HDUList() ext=fits.PrimaryHDU(img) ext.header=hdr new.append(ext) # write file to disk? if filename is not None: new.writeto(filename,overwrite=True) # create output in same datatype out=FitsImage() out.loadHDU(new[0]) return out def writeto(self,filename,overwrite=True): self.hdu.writeto(filename,overwrite=overwrite) if __name__=='__main__': filename='/Users/rryan/figs_gn1_wfc3_ir_f160w_030mas_drz_patch_v1ns.fits' a=FitsImage(filename) b=a.extract(50,100,70,90) print(b)
[ "astropy.io.fits.HDUList", "astropy.io.fits.PrimaryHDU", "astropy.io.fits.open", "numpy.clip" ]
[((1319, 1348), 'numpy.clip', 'np.clip', (['x0', '(0)', 'self.naxis[0]'], {}), '(x0, 0, self.naxis[0])\n', (1326, 1348), True, 'import numpy as np\n'), ((1358, 1387), 'numpy.clip', 'np.clip', (['x1', '(0)', 'self.naxis[0]'], {}), '(x1, 0, self.naxis[0])\n', (1365, 1387), True, 'import numpy as np\n'), ((1397, 1426), 'numpy.clip', 'np.clip', (['y0', '(0)', 'self.naxis[1]'], {}), '(y0, 0, self.naxis[1])\n', (1404, 1426), True, 'import numpy as np\n'), ((1436, 1465), 'numpy.clip', 'np.clip', (['y1', '(0)', 'self.naxis[1]'], {}), '(y1, 0, self.naxis[1])\n', (1443, 1465), True, 'import numpy as np\n'), ((1822, 1836), 'astropy.io.fits.HDUList', 'fits.HDUList', ([], {}), '()\n', (1834, 1836), False, 'from astropy.io import fits\n'), ((1849, 1869), 'astropy.io.fits.PrimaryHDU', 'fits.PrimaryHDU', (['img'], {}), '(img)\n', (1864, 1869), False, 'from astropy.io import fits\n'), ((312, 331), 'astropy.io.fits.open', 'fits.open', (['filename'], {}), '(filename)\n', (321, 331), False, 'from astropy.io import fits\n')]
import numpy as np import scipy.stats as stats from pyDOE import lhs class GaussianInputs: 'A class for Gaussian inputs' def __init__(self, mean, cov, domain, dim): self.mean = mean self.cov = cov self.domain = domain self.dim = dim def sampling(self, num, lh=True, criterion=None): if lh: samples = lhs(self.dim, num, criterion=criterion) samples = self.rescale_samples(samples, self.domain) else: samples = np.random.multivariate_normal(self.mean, self.cov, num) return samples def pdf(self, x): return stats.multivariate_normal(self.mean, self.cov).pdf(x) @staticmethod def rescale_samples(x, domain): """Rescale samples from [0,1]^d to actual domain.""" for i in range(x.shape[1]): bd = domain[i] x[:,i] = x[:,i]*(bd[1]-bd[0]) + bd[0] return x
[ "pyDOE.lhs", "numpy.random.multivariate_normal", "scipy.stats.multivariate_normal" ]
[((367, 406), 'pyDOE.lhs', 'lhs', (['self.dim', 'num'], {'criterion': 'criterion'}), '(self.dim, num, criterion=criterion)\n', (370, 406), False, 'from pyDOE import lhs\n'), ((509, 564), 'numpy.random.multivariate_normal', 'np.random.multivariate_normal', (['self.mean', 'self.cov', 'num'], {}), '(self.mean, self.cov, num)\n', (538, 564), True, 'import numpy as np\n'), ((625, 671), 'scipy.stats.multivariate_normal', 'stats.multivariate_normal', (['self.mean', 'self.cov'], {}), '(self.mean, self.cov)\n', (650, 671), True, 'import scipy.stats as stats\n')]
import numpy data=numpy.loadtxt(fname='../data/inflammation-01.csv', delimiter=',') from matplotlib import pyplot as plt figure = plt.figure(figsize=(7.0, 3.0)) figure.add_axes([0,0,1,1]) figure.axes[0].imshow(data) figure.savefig('image.png') range_over_days = plt.figure(figsize=(7.0, 3.0)) subplot_average=range_over_days.add_subplot(1, 2, 1) subplot_average.set_ylabel('min') subplot_average.plot(data.min(0)) subplot_max=range_over_days.add_subplot(1, 2, 2) subplot_max.set_ylabel('max') subplot_max.plot(data.max(0)) range_over_days.tight_layout() range_over_days.savefig('dayrange.png')
[ "matplotlib.pyplot.figure", "numpy.loadtxt" ]
[((19, 84), 'numpy.loadtxt', 'numpy.loadtxt', ([], {'fname': '"""../data/inflammation-01.csv"""', 'delimiter': '""","""'}), "(fname='../data/inflammation-01.csv', delimiter=',')\n", (32, 84), False, 'import numpy\n'), ((140, 170), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(7.0, 3.0)'}), '(figsize=(7.0, 3.0))\n', (150, 170), True, 'from matplotlib import pyplot as plt\n'), ((273, 303), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(7.0, 3.0)'}), '(figsize=(7.0, 3.0))\n', (283, 303), True, 'from matplotlib import pyplot as plt\n')]
from __future__ import print_function from random import shuffle import keras # Biblioteca para deep learning - Utilizando tensorflow como backend import random import glob import os import os.path import sys import numpy as np # Concatenação na variavel de sistema pythonPath para suportar a biblioteca pandas #sys.path.append("/usr/lib/python2.7/dist-packages") #import pandas as pd # # Definição dos recursos utilizados pelo keras from keras.preprocessing import sequence from keras.layers import Activation from keras.layers import Embedding from keras.layers import Conv1D, GlobalMaxPooling1D # As proximas 2 classes (Tokenizer e pad_sequences) permitem que um corpo de textos seja vetorizado substituindo # cada texto por uma sequencia de inteiros (representando o indice da palavra em um dicionario) from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import pad_sequences from keras.preprocessing.image import img_to_array from keras.utils import np_utils from keras.preprocessing import image from keras.applications.resnet50 import ResNet50 from keras.applications.imagenet_utils import preprocess_input from keras.callbacks import EarlyStopping, ModelCheckpoint from keras.models import Sequential,Model from keras.layers import Input,Flatten,Dense,Dropout,GlobalAveragePooling2D,Conv2D,MaxPooling2D from keras.utils.vis_utils import plot_model from keras.callbacks import Callback from sklearn.metrics import confusion_matrix, f1_score, precision_score, recall_score # Definição dos recursos utilizados pelo sklearn from sklearn.datasets import load_files from sklearn.preprocessing import LabelEncoder from sklearn.model_selection import StratifiedKFold from sklearn.metrics import confusion_matrix,accuracy_score from sklearn.preprocessing import LabelEncoder #from sklearn.cross_validation import KFold # Definiçao dos recursos do matplotlib - Utilizado para gerar gráficos #import matplotlib.pyplot as plt #import matplotlib.cm as colormap import timeit class RNC_vin: def __init__(self, max_features=100, embedding_dims=50, maxlen=50, filters=100, kernel_size=3, hidden_dims=250, output_dims=10, compile_loss='categorical_crossentropy'): self.max_features = max_features self.embedding_dims = embedding_dims self.maxlen = maxlen self.filters = filters self.kernel_size = kernel_size self.hidden_dims = hidden_dims self.output_dims = output_dims # model armazena o objeto referente a chamada Sequential() onde os parâmetros serão incluidos abaixo self.model = Sequential() # Adiciona uma camada de Embedding ao modelo de rede # max_features (input_dim) indica o tamanho do vocábulario # embedding_dims (output_dim) indica o tamanho do vetor espacial onde as palavras (numeros) serão armazenadas no embedding # input_length indica o tamanho maximo dos vetores que representam as frases (já tokenizadas) # Mais sobre Word Embedding: https://machinelearningmastery.com/use-word-embedding-layers-deep-learning-keras/ self.model.add(Embedding(max_features,embedding_dims,input_length=maxlen)) # Dropout é uma maneira de diminuir os erros durante a classificação # Basicamente, durante o treinamento, uma porcentagem dos neuronios são desligados aumentando a generalização da rede # forçando as camadas a aprender com diferentes neurônios # O parâmetro 0.2 é a fração que corresponde a quantidade de neurônios à desligar self.model.add(Dropout(0.2)) # Adiciona uma camada de convolução na rede neural # filters representa a quantidade de convuluções, ou seja, a quantidade de saidas da camada Conv1D # kernel_size indica o tamanho de uma convolução (no caso de 3 em 3 - janelinha de 3x3) # padding=valid > diz para não realizar padding # activation possui a intenção de não linearizar a rede. reLU = Rectified Linear Units # strides controla como o filtro realiza uma convolução, 1 indica que o filtro sempre anda de uma em uma posição # mais sobre: https://adeshpande3.github.io/A-Beginner%27s-Guide-To-Understanding-Convolutional-Neural-Networks-Part-2/ self.model.add(Conv1D(filters,kernel_size,padding='valid',activation='relu',strides=1)) # Serve para reduzir o tamanho da representação da saída da camada de convolução acima, diminuindo o numero de parâmetros # e poder computacional exigido, consequentemente controlando o overfitting não perdendo as caracteristicas adquiridas nas camadas passadas # Nesse caso, ela usa a omeração de MAX() mara reduzir o tamanho dos dados self.model.add(GlobalMaxPooling1D()) # Adiciona uma vanilla hidden layer - Vanilla indica que a camada é da forma mais simples, um padrão: # Dense aplica uma operação linear no vetor de entrada da camada # hidden_dims representa a dimensionalidade do array de saida self.model.add(Dense(hidden_dims)) #dropou igual ao explicado acima self.model.add(Dropout(0.2)) # Aplica uma função de ativação (no caso reLU) a uma saída self.model.add(Activation('relu')) # We project onto a single unit output layer, and squash it with a sigmoid: - Modificacao # Transforma todos os neuronios em apenas 1 - MOD Classificacoes nao binarias self.model.add(Dense(output_dims)) #era 10!!!! # A partir do neuronio anterior, a funcao sigmoid gera valores entre 0 e 1 # No caso, 0 representa 100% de certeza de ser negativo e 1 100% de certeza de ser Positivo self.model.add(Activation('sigmoid')) # Antes de treinar a rede, ela precisa ser compilada configurando o processo de aprendizado # STANCE - loss: Representa o objetivo no qual o modelo vai tentar minimizar binary_crossentropy é indicado para a classificação de 2 classes (positivo e negativo) # optimizer=adam é um algoritmo para atualizar os pesos da rede iterativamente baseado nos dados do treinamento # metrics para qualquer problema de classificação a métrica deve ser accuracy #self.model.compile(loss='binary_crossentropy',optimizer='rmsprop',metrics = ['accuracy']) self.model.compile(loss=compile_loss,optimizer='rmsprop',metrics = ['accuracy']) def fit(self, X_data, Y_data, batch_size=32, epochs=10, verbose=0, validation_data=None): if validation_data is not None: return self.model.fit(np.array(X_data), np.array(Y_data), batch_size=batch_size, epochs=epochs, validation_data=validation_data, verbose=verbose) else: return self.model.fit(np.array(X_data), np.array(Y_data), batch_size=batch_size, epochs=epochs, verbose=verbose) def predict(self, X_data, batch_size=32, verbose=0): return self.model.predict(X_data, batch_size=batch_size, verbose=verbose) np.random.seed(1)
[ "numpy.random.seed", "keras.layers.Activation", "keras.layers.Dropout", "keras.layers.Conv1D", "keras.layers.Dense", "numpy.array", "keras.layers.Embedding", "keras.models.Sequential", "keras.layers.GlobalMaxPooling1D" ]
[((6955, 6972), 'numpy.random.seed', 'np.random.seed', (['(1)'], {}), '(1)\n', (6969, 6972), True, 'import numpy as np\n'), ((2587, 2599), 'keras.models.Sequential', 'Sequential', ([], {}), '()\n', (2597, 2599), False, 'from keras.models import Sequential, Model\n'), ((3112, 3172), 'keras.layers.Embedding', 'Embedding', (['max_features', 'embedding_dims'], {'input_length': 'maxlen'}), '(max_features, embedding_dims, input_length=maxlen)\n', (3121, 3172), False, 'from keras.layers import Embedding\n'), ((3555, 3567), 'keras.layers.Dropout', 'Dropout', (['(0.2)'], {}), '(0.2)\n', (3562, 3567), False, 'from keras.layers import Input, Flatten, Dense, Dropout, GlobalAveragePooling2D, Conv2D, MaxPooling2D\n'), ((4255, 4330), 'keras.layers.Conv1D', 'Conv1D', (['filters', 'kernel_size'], {'padding': '"""valid"""', 'activation': '"""relu"""', 'strides': '(1)'}), "(filters, kernel_size, padding='valid', activation='relu', strides=1)\n", (4261, 4330), False, 'from keras.layers import Conv1D, GlobalMaxPooling1D\n'), ((4713, 4733), 'keras.layers.GlobalMaxPooling1D', 'GlobalMaxPooling1D', ([], {}), '()\n', (4731, 4733), False, 'from keras.layers import Conv1D, GlobalMaxPooling1D\n'), ((5013, 5031), 'keras.layers.Dense', 'Dense', (['hidden_dims'], {}), '(hidden_dims)\n', (5018, 5031), False, 'from keras.layers import Input, Flatten, Dense, Dropout, GlobalAveragePooling2D, Conv2D, MaxPooling2D\n'), ((5097, 5109), 'keras.layers.Dropout', 'Dropout', (['(0.2)'], {}), '(0.2)\n', (5104, 5109), False, 'from keras.layers import Input, Flatten, Dense, Dropout, GlobalAveragePooling2D, Conv2D, MaxPooling2D\n'), ((5201, 5219), 'keras.layers.Activation', 'Activation', (['"""relu"""'], {}), "('relu')\n", (5211, 5219), False, 'from keras.layers import Activation\n'), ((5429, 5447), 'keras.layers.Dense', 'Dense', (['output_dims'], {}), '(output_dims)\n', (5434, 5447), False, 'from keras.layers import Input, Flatten, Dense, Dropout, GlobalAveragePooling2D, Conv2D, MaxPooling2D\n'), ((5668, 5689), 'keras.layers.Activation', 'Activation', (['"""sigmoid"""'], {}), "('sigmoid')\n", (5678, 5689), False, 'from keras.layers import Activation\n'), ((6544, 6560), 'numpy.array', 'np.array', (['X_data'], {}), '(X_data)\n', (6552, 6560), True, 'import numpy as np\n'), ((6562, 6578), 'numpy.array', 'np.array', (['Y_data'], {}), '(Y_data)\n', (6570, 6578), True, 'import numpy as np\n'), ((6716, 6732), 'numpy.array', 'np.array', (['X_data'], {}), '(X_data)\n', (6724, 6732), True, 'import numpy as np\n'), ((6734, 6750), 'numpy.array', 'np.array', (['Y_data'], {}), '(Y_data)\n', (6742, 6750), True, 'import numpy as np\n')]
#! -*- coding:utf-8 -*- import os import re import gc import sys import json import codecs import random import warnings import numpy as np import pandas as pd from tqdm import tqdm from random import choice import tensorflow as tf import matplotlib.pyplot as plt from collections import Counter from sklearn.model_selection import KFold from sklearn.preprocessing import LabelEncoder from sklearn.metrics import f1_score, accuracy_score from sklearn.model_selection import StratifiedKFold from sklearn.model_selection import train_test_split import keras.backend as K from keras.layers import * from keras.callbacks import * from keras.models import Model from keras.optimizers import Adam from keras.initializers import glorot_uniform from keras_bert import load_trained_model_from_checkpoint, Tokenizer tqdm.pandas() seed = 2019 random.seed(seed) tf.set_random_seed(seed) np.random.seed(seed) warnings.filterwarnings('ignore') ################################################################ data_path = '../../dataSet/' train = pd.read_csv(data_path + 'Round2_train.csv', encoding='utf-8') train2= pd.read_csv(data_path + 'Train_Data.csv', encoding='utf-8') train=pd.concat([train, train2], axis=0, sort=True) test = pd.read_csv(data_path + 'round2_test.csv', encoding='utf-8') train = train[train['entity'].notnull()] test = test[test['entity'].notnull()] train=train.drop_duplicates(['title','text','entity','negative','key_entity']) # 去掉重复的data print(train.shape) ###(10526, 6) print(test.shape) ####((9997, 4) def get_or_content(y,z): s='' if str(y)!='nan': s+=y if str(z)!='nan': s+=z return s #获取title+text train['content']=list(map(lambda y,z: get_or_content(y,z),train['title'],train['text'])) test['content']=list(map(lambda y,z: get_or_content(y,z),test['title'],test['text'])) def entity_clear_row(entity,content): entities = entity.split(';') entities.sort(key=lambda x: len(x)) n = len(entities) tmp = entities.copy() for i in range(n): entity_tmp = entities[i] #长度小于等于1 if len(entity_tmp)<=1: tmp.remove(entity_tmp) continue if i + 1 >= n: break for entity_tmp2 in entities[i + 1:]: if entity_tmp2.find(entity_tmp) != -1 and ( entity_tmp2.find('?') != -1 or content.replace(entity_tmp2, '').find(entity_tmp) == -1): tmp.remove(entity_tmp) break return ';'.join(tmp) train['entity']=list(map(lambda entity,content:entity_clear_row(entity,content),train['entity'],train['content'])) test['entity']=list(map(lambda entity,content:entity_clear_row(entity,content),test['entity'],test['content'])) test['text'] = test.apply(lambda index: index.title if index.text is np.nan else index.text, axis=1) train = train[(train['entity'].notnull()) & (train['negative'] == 1)] ### emotion = pd.read_csv('../../Emotion_Model/submit/emotion_voting_three_models.csv', encoding='utf-8') emotion = emotion[emotion['negative'] == 1] test = emotion.merge(test, on='id', how='left') ################################################################ train_id_entity = train[['id', 'entity']] train_id_entity['entity'] = train_id_entity['entity'].apply(lambda index: index.split(';')) id, entity = [], [] for index in range(len(train_id_entity['entity'])): entity.extend(list(train_id_entity['entity'])[index]) id.extend([list(train_id_entity['id'])[index]] * len(list(train_id_entity['entity'])[index])) train_id_entity = pd.DataFrame({'id': id, 'entity_label': entity}) test_id_entity = test[['id', 'entity']] test_id_entity['entity'] = test_id_entity['entity'].apply(lambda index: index.split(';')) id, entity = [], [] for index in range(len(test_id_entity['entity'])): entity.extend(list(test_id_entity['entity'])[index]) id.extend([list(test_id_entity['id'])[index]] * len(list(test_id_entity['entity'])[index])) test_id_entity = pd.DataFrame({'id': id, 'entity_label': entity}) train = train.merge(train_id_entity, on='id', how='left') train['flag'] = train.apply(lambda index: 1 if index.key_entity.split(';').count(index.entity_label) >= 1 else 0, axis=1) test = test.merge(test_id_entity, on='id', how='left') ################################################################ print(train.shape) print(test.shape) def extract_feature(data): data['sub_word_num'] = data.apply(lambda index: index.entity.count(index.entity_label) - 1, axis=1) data['question_mark_num'] = data['entity_label'].apply(lambda index: index.count('?')) data['occur_in_title_num'] = data.apply(lambda index: 0 if index.title is np.nan else index.title.count(index.entity_label), axis=1) data['occur_in_text_num'] = data.apply(lambda index: 0 if index.text is np.nan else index.text.count(index.entity_label), axis=1) data['occur_in_partial_text_num'] = data.apply(lambda index: 0 if index.text is np.nan else index.text[:507].count(index.entity_label), axis=1) data['occur_in_entity'] = data.apply(lambda index: 0 if index.text is np.nan else index.entity.count(index.entity_label) - 1, axis=1) data['is_occur_in_article'] = data.apply(lambda index: 1 if (index.occur_in_title_num >= 1) | (index.occur_in_text_num >= 1) else 0, axis=1) return data train = extract_feature(train) test = extract_feature(test) print(train.columns) train['entity_len'] = train['entity_label'].progress_apply(lambda index: len(index)) test['entity_len'] = test['entity_label'].progress_apply(lambda index: len(index)) train[train['entity_len'] == 1].shape train = train[train['entity_len'] > 1] test[test['entity_len'] == 1].shape test = test[test['entity_len'] > 1] train_feature = train[['sub_word_num', 'question_mark_num', 'occur_in_title_num', 'occur_in_text_num', 'is_occur_in_article', 'occur_in_entity', 'occur_in_partial_text_num']] test_feature = test[['sub_word_num', 'question_mark_num', 'occur_in_title_num', 'occur_in_text_num', 'is_occur_in_article', 'occur_in_entity', 'occur_in_partial_text_num']] # Normalization from sklearn.preprocessing import MinMaxScaler scaler = MinMaxScaler() train_feature = scaler.fit_transform(train_feature) test_feature = scaler.fit_transform(test_feature) def get_other_content(x,y): entitys=x.split(";") if len(entitys)<=1: return np.nan l=[] for e in entitys: if e!=y: l.append(e) return ';'.join(l) train['other_entity']=list(map(lambda x,y :get_other_content(x,y),train['entity'],train['entity_label'])) test['other_entity']=list(map(lambda x,y :get_other_content(x,y),test['entity'],test['entity_label'])) def get_content(x,y): if str(y)=='nan': return x y=y.split(";") y = sorted(y, key=lambda i:len(i),reverse=True) for i in y: x = '其他实体'.join(x.split(i)) return x train['text']=list(map(lambda x,y: get_content(x,y), train['text'], train['other_entity'])) test['text']=list(map(lambda x,y: get_content(x,y), test['text'], test['other_entity'])) maxlen = 509 # 序列长度 # 模型下载链接 tensorflow版:https://github.com/ymcui/Chinese-BERT-wwm#%E4%B8%AD%E6%96%87%E6%A8%A1%E5%9E%8B%E4%B8%8B%E8%BD%BD bert_path = '../../PreTrainModel/chinese_roberta_wwm_large_ext_L-24_H-1024_A-16/' config_path = bert_path + 'bert_config.json' checkpoint_path = bert_path + 'bert_model.ckpt' dict_path = bert_path + 'vocab.txt' token_dict = {} with codecs.open(dict_path, 'r', 'utf8') as reader: for line in reader: token = line.strip() token_dict[token] = len(token_dict) # 给每个token 按序编号 class OurTokenizer(Tokenizer): def _tokenize(self, text): R = [] for c in text: if c in self._token_dict: R.append(c) elif self._is_space(c): R.append('[unused1]') # space类用未经训练的[unused1]表示 else: R.append('[UNK]') # 剩余的字符是[UNK] return R tokenizer = OurTokenizer(token_dict) def seq_padding(X, padding=0): L = [len(x) for x in X] ML = max(L) return np.array([np.concatenate([x, [padding] * (ML - len(x))]) if len(x) < ML else x for x in X]) class data_generator: def __init__(self, data, feature, batch_size=4, shuffle=True): self.data = data self.batch_size = batch_size self.shuffle = shuffle self.feature = feature self.steps = len(self.data) // self.batch_size if len(self.data) % self.batch_size != 0: self.steps += 1 def __len__(self): return self.steps def __iter__(self): while True: idxs = list(range(len(self.data))) if self.shuffle: np.random.shuffle(idxs) X1, X2, Y, Fea = [], [], [], [] for i in idxs: d = self.data[i] fea = self.feature[i] # add feature first_text = d[0] second_text = d[2][:maxlen - d[1]] x1, x2 = tokenizer.encode(first=first_text, second=second_text) # , max_len=512 y = d[3] Fea.append(fea) X1.append(x1) X2.append(x2) Y.append([y]) if len(X1) == self.batch_size or i == idxs[-1]: X1 = seq_padding(X1) X2 = seq_padding(X2, padding=1) Fea = seq_padding(Fea) Y = seq_padding(Y) yield [X1, X2, Fea], Y[:, 0, :] [X1, X2, Y, Fea] = [], [], [], [] from keras.metrics import top_k_categorical_accuracy from keras.metrics import categorical_accuracy def acc_top2(y_true, y_pred): return top_k_categorical_accuracy(y_true, y_pred, k=1) def f1_metric(y_true, y_pred): def recall(y_true, y_pred): true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1))) possible_positives = K.sum(K.round(K.clip(y_true, 0, 1))) recall = true_positives / (possible_positives + K.epsilon()) return recall def precision(y_true, y_pred): true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1))) predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1))) precision = true_positives / (predicted_positives + K.epsilon()) return precision precision = precision(y_true, y_pred) recall = recall(y_true, y_pred) return 2*((precision*recall)/(precision+recall+K.epsilon())) def build_bert(nclass): bert_model = load_trained_model_from_checkpoint(config_path, checkpoint_path, seq_len=None) for l in bert_model.layers: # print(l) l.trainable = True x1_in = Input(shape=(None,)) x2_in = Input(shape=(None,)) x3_in = Input(shape=(train_feature.shape[1],)) feature = Dense(64, activation='relu')(x3_in) x = bert_model([x1_in, x2_in]) x = Lambda(lambda x: x[:, 0])(x) x = concatenate([x, feature]) p = Dense(nclass, activation='softmax')(x) model = Model([x1_in, x2_in, x3_in], p) model.compile(loss='categorical_crossentropy', optimizer=Adam(1e-5), # lr: 5e-5 3e-5 2e-5 epoch: 3, 4 batch_size: 16, 32 metrics=['accuracy', f1_metric]) # categorical_accuracy print(model.summary()) return model ################################################################ from keras.utils import to_categorical DATA_LIST = [] for data_row in train.iloc[:].itertuples(): DATA_LIST.append((data_row.entity_label, data_row.entity_len, data_row.text, to_categorical(data_row.flag, 2))) DATA_LIST = np.array(DATA_LIST) DATA_LIST_TEST = [] for data_row in test.iloc[:].itertuples(): DATA_LIST_TEST.append((data_row.entity_label, data_row.entity_len, data_row.text, to_categorical(0, 2))) DATA_LIST_TEST = np.array(DATA_LIST_TEST) ################################################################ f1, acc = [], [] def run_cv(nfold, data, feature_train, data_label, data_test, feature_test): kf = StratifiedKFold(n_splits=nfold, shuffle=True, random_state=seed).split(data, train['flag']) train_model_pred = np.zeros((len(data), 2)) # 2 test_model_pred = np.zeros((len(data_test), 2)) # 2 for i, (train_fold, test_fold) in enumerate(kf): X_train, X_valid, = data[train_fold, :], data[test_fold, :] X_train_fea, X_valid_fea = feature_train[train_fold, :], feature_train[test_fold, :] model = build_bert(2) # 2 early_stopping = EarlyStopping(monitor='val_acc', patience=2) # val_acc plateau = ReduceLROnPlateau(monitor="val_acc", verbose=1, mode='max', factor=0.5, patience=1) checkpoint = ModelCheckpoint('./model/' + str(i) + '.hdf5', monitor='val_acc', verbose=2, save_best_only=True, mode='max',save_weights_only=True) train_D = data_generator(X_train, X_train_fea, shuffle=True) valid_D = data_generator(X_valid, X_valid_fea, shuffle=False) test_D = data_generator(data_test, feature_test, shuffle=False) model.fit_generator( train_D.__iter__(), steps_per_epoch=len(train_D), ## ?? ## epochs=10, validation_data=valid_D.__iter__(), validation_steps=len(valid_D), callbacks=[early_stopping, plateau, checkpoint], verbose=2 ) model.load_weights('./model/' + str(i) + '.hdf5') # return model val = model.predict_generator(valid_D.__iter__(), steps=len(valid_D),verbose=0) print(val) score = f1_score(train['flag'].values[test_fold], np.argmax(val, axis=1)) acc_score = accuracy_score(train['flag'].values[test_fold], np.argmax(val, axis=1)) global f1, acc f1.append(score) acc.append(acc_score) print('validate f1 score:', score) print('validate accuracy score:', acc_score) train_model_pred[test_fold, :] = val test_model_pred += model.predict_generator(test_D.__iter__(), steps=len(test_D),verbose=0) del model; gc.collect() K.clear_session() return train_model_pred, test_model_pred ################################################################ train_model_pred, test_model_pred = run_cv(10, DATA_LIST, train_feature, None, DATA_LIST_TEST, test_feature) print('validate aver f1 score:', np.average(f1)) print('validate aver accuracy score:', np.average(acc)) np.save('weights/bert_prob_train_binary_label_add_feature_extend_trainSet-PreProcess-roberta-large-wwm-ext.npy', train_model_pred) np.save('weights/bert_prob_test_binary_label_add_feature_extend_trainSet-PreProcess-roberta-large-wwm-ext.npy', test_model_pred) ################################################################ ################################################################ def return_list(group): return ';'.join(list(group)) sub = test.copy() sub['label'] = [np.argmax(index) for index in test_model_pred] test['prob'] = [index[1] for index in test_model_pred] sub = sub[sub['label'] == 1] key_entity = sub.groupby(['id'], as_index=False)['entity_label'].agg({'key_entity': return_list}) sub_id = set(test['id']) - set(key_entity['id']) sub_test = test[test['id'].isin(sub_id)] sub_test = sub_test.sort_values(by=['id', 'prob'], ascending=False).drop_duplicates(['id'], keep='first') sub_test['key_entity'] = sub_test['entity_label'] key_entity = pd.concat([key_entity, sub_test[['id', 'key_entity']]], axis=0, ignore_index=True) test_2 = pd.read_csv(data_path + 'round2_test.csv', encoding='utf-8') submit = test_2[['id']] submit = submit.merge(key_entity, on='id', how='left') submit['negative'] = submit['key_entity'].apply(lambda index: 0 if index is np.nan else 1) submit = submit[['id', 'negative', 'key_entity']] submit.to_csv('submit/entity_roberta-large-wwm-ext.csv', encoding='utf-8', index=None) print(submit[submit['key_entity'].notnull()].shape)
[ "numpy.random.seed", "numpy.argmax", "pandas.read_csv", "keras.backend.epsilon", "sklearn.preprocessing.MinMaxScaler", "tqdm.tqdm.pandas", "keras.models.Model", "gc.collect", "pandas.DataFrame", "codecs.open", "keras_bert.load_trained_model_from_checkpoint", "tensorflow.set_random_seed", "ra...
[((809, 822), 'tqdm.tqdm.pandas', 'tqdm.pandas', ([], {}), '()\n', (820, 822), False, 'from tqdm import tqdm\n'), ((835, 852), 'random.seed', 'random.seed', (['seed'], {}), '(seed)\n', (846, 852), False, 'import random\n'), ((853, 877), 'tensorflow.set_random_seed', 'tf.set_random_seed', (['seed'], {}), '(seed)\n', (871, 877), True, 'import tensorflow as tf\n'), ((878, 898), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (892, 898), True, 'import numpy as np\n'), ((899, 932), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (922, 932), False, 'import warnings\n'), ((1039, 1100), 'pandas.read_csv', 'pd.read_csv', (["(data_path + 'Round2_train.csv')"], {'encoding': '"""utf-8"""'}), "(data_path + 'Round2_train.csv', encoding='utf-8')\n", (1050, 1100), True, 'import pandas as pd\n'), ((1109, 1168), 'pandas.read_csv', 'pd.read_csv', (["(data_path + 'Train_Data.csv')"], {'encoding': '"""utf-8"""'}), "(data_path + 'Train_Data.csv', encoding='utf-8')\n", (1120, 1168), True, 'import pandas as pd\n'), ((1175, 1220), 'pandas.concat', 'pd.concat', (['[train, train2]'], {'axis': '(0)', 'sort': '(True)'}), '([train, train2], axis=0, sort=True)\n', (1184, 1220), True, 'import pandas as pd\n'), ((1228, 1288), 'pandas.read_csv', 'pd.read_csv', (["(data_path + 'round2_test.csv')"], {'encoding': '"""utf-8"""'}), "(data_path + 'round2_test.csv', encoding='utf-8')\n", (1239, 1288), True, 'import pandas as pd\n'), ((2916, 3011), 'pandas.read_csv', 'pd.read_csv', (['"""../../Emotion_Model/submit/emotion_voting_three_models.csv"""'], {'encoding': '"""utf-8"""'}), "('../../Emotion_Model/submit/emotion_voting_three_models.csv',\n encoding='utf-8')\n", (2927, 3011), True, 'import pandas as pd\n'), ((3549, 3597), 'pandas.DataFrame', 'pd.DataFrame', (["{'id': id, 'entity_label': entity}"], {}), "({'id': id, 'entity_label': entity})\n", (3561, 3597), True, 'import pandas as pd\n'), ((3972, 4020), 'pandas.DataFrame', 'pd.DataFrame', (["{'id': id, 'entity_label': entity}"], {}), "({'id': id, 'entity_label': entity})\n", (3984, 4020), True, 'import pandas as pd\n'), ((6126, 6140), 'sklearn.preprocessing.MinMaxScaler', 'MinMaxScaler', ([], {}), '()\n', (6138, 6140), False, 'from sklearn.preprocessing import MinMaxScaler\n'), ((11638, 11657), 'numpy.array', 'np.array', (['DATA_LIST'], {}), '(DATA_LIST)\n', (11646, 11657), True, 'import numpy as np\n'), ((11848, 11872), 'numpy.array', 'np.array', (['DATA_LIST_TEST'], {}), '(DATA_LIST_TEST)\n', (11856, 11872), True, 'import numpy as np\n'), ((14543, 14683), 'numpy.save', 'np.save', (['"""weights/bert_prob_train_binary_label_add_feature_extend_trainSet-PreProcess-roberta-large-wwm-ext.npy"""', 'train_model_pred'], {}), "(\n 'weights/bert_prob_train_binary_label_add_feature_extend_trainSet-PreProcess-roberta-large-wwm-ext.npy'\n , train_model_pred)\n", (14550, 14683), True, 'import numpy as np\n'), ((14674, 14812), 'numpy.save', 'np.save', (['"""weights/bert_prob_test_binary_label_add_feature_extend_trainSet-PreProcess-roberta-large-wwm-ext.npy"""', 'test_model_pred'], {}), "(\n 'weights/bert_prob_test_binary_label_add_feature_extend_trainSet-PreProcess-roberta-large-wwm-ext.npy'\n , test_model_pred)\n", (14681, 14812), True, 'import numpy as np\n'), ((15517, 15603), 'pandas.concat', 'pd.concat', (["[key_entity, sub_test[['id', 'key_entity']]]"], {'axis': '(0)', 'ignore_index': '(True)'}), "([key_entity, sub_test[['id', 'key_entity']]], axis=0,\n ignore_index=True)\n", (15526, 15603), True, 'import pandas as pd\n'), ((15610, 15670), 'pandas.read_csv', 'pd.read_csv', (["(data_path + 'round2_test.csv')"], {'encoding': '"""utf-8"""'}), "(data_path + 'round2_test.csv', encoding='utf-8')\n", (15621, 15670), True, 'import pandas as pd\n'), ((7408, 7443), 'codecs.open', 'codecs.open', (['dict_path', '"""r"""', '"""utf8"""'], {}), "(dict_path, 'r', 'utf8')\n", (7419, 7443), False, 'import codecs\n'), ((9695, 9742), 'keras.metrics.top_k_categorical_accuracy', 'top_k_categorical_accuracy', (['y_true', 'y_pred'], {'k': '(1)'}), '(y_true, y_pred, k=1)\n', (9721, 9742), False, 'from keras.metrics import top_k_categorical_accuracy\n'), ((10514, 10592), 'keras_bert.load_trained_model_from_checkpoint', 'load_trained_model_from_checkpoint', (['config_path', 'checkpoint_path'], {'seq_len': 'None'}), '(config_path, checkpoint_path, seq_len=None)\n', (10548, 10592), False, 'from keras_bert import load_trained_model_from_checkpoint, Tokenizer\n'), ((11016, 11047), 'keras.models.Model', 'Model', (['[x1_in, x2_in, x3_in]', 'p'], {}), '([x1_in, x2_in, x3_in], p)\n', (11021, 11047), False, 'from keras.models import Model\n'), ((14471, 14485), 'numpy.average', 'np.average', (['f1'], {}), '(f1)\n', (14481, 14485), True, 'import numpy as np\n'), ((14526, 14541), 'numpy.average', 'np.average', (['acc'], {}), '(acc)\n', (14536, 14541), True, 'import numpy as np\n'), ((15027, 15043), 'numpy.argmax', 'np.argmax', (['index'], {}), '(index)\n', (15036, 15043), True, 'import numpy as np\n'), ((14178, 14190), 'gc.collect', 'gc.collect', ([], {}), '()\n', (14188, 14190), False, 'import gc\n'), ((14199, 14216), 'keras.backend.clear_session', 'K.clear_session', ([], {}), '()\n', (14214, 14216), True, 'import keras.backend as K\n'), ((11128, 11139), 'keras.optimizers.Adam', 'Adam', (['(1e-05)'], {}), '(1e-05)\n', (11132, 11139), False, 'from keras.optimizers import Adam\n'), ((11591, 11623), 'keras.utils.to_categorical', 'to_categorical', (['data_row.flag', '(2)'], {}), '(data_row.flag, 2)\n', (11605, 11623), False, 'from keras.utils import to_categorical\n'), ((11808, 11828), 'keras.utils.to_categorical', 'to_categorical', (['(0)', '(2)'], {}), '(0, 2)\n', (11822, 11828), False, 'from keras.utils import to_categorical\n'), ((12042, 12106), 'sklearn.model_selection.StratifiedKFold', 'StratifiedKFold', ([], {'n_splits': 'nfold', 'shuffle': '(True)', 'random_state': 'seed'}), '(n_splits=nfold, shuffle=True, random_state=seed)\n', (12057, 12106), False, 'from sklearn.model_selection import StratifiedKFold\n'), ((13723, 13745), 'numpy.argmax', 'np.argmax', (['val'], {'axis': '(1)'}), '(val, axis=1)\n', (13732, 13745), True, 'import numpy as np\n'), ((13815, 13837), 'numpy.argmax', 'np.argmax', (['val'], {'axis': '(1)'}), '(val, axis=1)\n', (13824, 13837), True, 'import numpy as np\n'), ((8682, 8705), 'numpy.random.shuffle', 'np.random.shuffle', (['idxs'], {}), '(idxs)\n', (8699, 8705), True, 'import numpy as np\n'), ((9847, 9876), 'keras.backend.clip', 'K.clip', (['(y_true * y_pred)', '(0)', '(1)'], {}), '(y_true * y_pred, 0, 1)\n', (9853, 9876), True, 'import keras.backend as K\n'), ((9922, 9942), 'keras.backend.clip', 'K.clip', (['y_true', '(0)', '(1)'], {}), '(y_true, 0, 1)\n', (9928, 9942), True, 'import keras.backend as K\n'), ((10001, 10012), 'keras.backend.epsilon', 'K.epsilon', ([], {}), '()\n', (10010, 10012), True, 'import keras.backend as K\n'), ((10111, 10140), 'keras.backend.clip', 'K.clip', (['(y_true * y_pred)', '(0)', '(1)'], {}), '(y_true * y_pred, 0, 1)\n', (10117, 10140), True, 'import keras.backend as K\n'), ((10187, 10207), 'keras.backend.clip', 'K.clip', (['y_pred', '(0)', '(1)'], {}), '(y_pred, 0, 1)\n', (10193, 10207), True, 'import keras.backend as K\n'), ((10270, 10281), 'keras.backend.epsilon', 'K.epsilon', ([], {}), '()\n', (10279, 10281), True, 'import keras.backend as K\n'), ((10437, 10448), 'keras.backend.epsilon', 'K.epsilon', ([], {}), '()\n', (10446, 10448), True, 'import keras.backend as K\n')]
# this code is made and distributed by RedScorpion # need help? contact me on discord RedScorpion#5785 # for visual toturial, open this link on your browser # https://www.youtube.com/watch?v=g7m6EBFWzKM # for documentation, open this link on your browser # https://github.com/redscorpionx/wolves/ import pyautogui as gui import win32api as win import keyboard import win32con import numpy import time time.sleep(5) # given x and y are the mouse coordinates, this sends a left click def click(x, y): win.SetCursorPos((x, y)) win.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0) time.sleep(0.01) win.mouse_event(win32con.MOUSEEVENTF_LEFTUP, 0, 0) # finds the watch video button, clicks if it is there def find_button(): coords = (mom, dad) for m in range(1000): if gui.pixel(coords[0], coords[1])[0] == 255: click(coords[0], coords[1]) break else: coords = (coords[0], coords[1] - 5) def rich_overnight(): find_button() time.sleep(numpy.random.randint(40, 43)) click(me, you) # clicks the back button time.sleep(numpy.random.randint(5, 7)) find_button() time.sleep(numpy.random.randint(16, 17)) while True: rich_overnight()
[ "win32api.SetCursorPos", "time.sleep", "numpy.random.randint", "pyautogui.pixel", "win32api.mouse_event" ]
[((418, 431), 'time.sleep', 'time.sleep', (['(5)'], {}), '(5)\n', (428, 431), False, 'import time\n'), ((527, 551), 'win32api.SetCursorPos', 'win.SetCursorPos', (['(x, y)'], {}), '((x, y))\n', (543, 551), True, 'import win32api as win\n'), ((557, 609), 'win32api.mouse_event', 'win.mouse_event', (['win32con.MOUSEEVENTF_LEFTDOWN', '(0)', '(0)'], {}), '(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0)\n', (572, 609), True, 'import win32api as win\n'), ((615, 631), 'time.sleep', 'time.sleep', (['(0.01)'], {}), '(0.01)\n', (625, 631), False, 'import time\n'), ((637, 687), 'win32api.mouse_event', 'win.mouse_event', (['win32con.MOUSEEVENTF_LEFTUP', '(0)', '(0)'], {}), '(win32con.MOUSEEVENTF_LEFTUP, 0, 0)\n', (652, 687), True, 'import win32api as win\n'), ((1060, 1088), 'numpy.random.randint', 'numpy.random.randint', (['(40)', '(43)'], {}), '(40, 43)\n', (1080, 1088), False, 'import numpy\n'), ((1151, 1177), 'numpy.random.randint', 'numpy.random.randint', (['(5)', '(7)'], {}), '(5, 7)\n', (1171, 1177), False, 'import numpy\n'), ((1214, 1242), 'numpy.random.randint', 'numpy.random.randint', (['(16)', '(17)'], {}), '(16, 17)\n', (1234, 1242), False, 'import numpy\n'), ((831, 862), 'pyautogui.pixel', 'gui.pixel', (['coords[0]', 'coords[1]'], {}), '(coords[0], coords[1])\n', (840, 862), True, 'import pyautogui as gui\n')]
import torch import torch.nn as nn import torch.optim as optim from torch.optim import lr_scheduler import torchvision from torchvision import transforms from torch.utils.data import DataLoader from torch.autograd import Variable import torch.utils.data as data_utils import numpy as np import matplotlib.pyplot as plt from wavelets_pytorch_2.alltorch.wavelets import Morlet, Ricker, DOG, Paul from wavelets_pytorch_2.alltorch.transform import WaveletTransformTorch #WaveletTransform, from tqdm import tqdm import argparse import moment import os import sys #from loader import CustomDataset,Rescale,ToTensor from unet_network import UNet #ResUnet #RefineNet2 #IncUNet # UNetResAdd_2 #UNetResMul ResUNet# #Unet UNetRes def visual(label_g):#,cwt): fps = 150 dt = 1.0/fps dt1 = 1.0/fps dj = 0.125 unbias = False batch_size = 32 #wavelet = Morlet(w0=2) wavelet = Paul(m=8) x = np.linspace(0, 1, num=150) dt = 1 scales = np.load('./wavelet_dataset/scales.npy') print(label_g.shape) scales_label_torch = torch.from_numpy(scales).type(torch.FloatTensor) power_label_torch = torch.from_numpy(label_g.data.cpu().numpy()).type(torch.FloatTensor) # print(power_label_torch.size(),cwt.size()) wa_label_torch = WaveletTransformTorch(dt, dj, wavelet, unbias=unbias, cuda=True) label_recon = wa_label_torch.reconstruction(power_label_torch,scales_label_torch,cwt_n=power_label_torch[0]) return label_recon if __name__ == "__main__": ''' parser = argparse.ArgumentParser('Tool to perform segmentation with input and mask images') parser.add_argument( '--img_dir', required = True, type = str, help = 'Provide the path which contains image files' ) parser.add_argument( '--mask_dir', required = True, type = str, help = 'Provide the path which contains mask files' ) ''' # parser.add_argument( # '--batch_size', # default = 1, # type = int # ) # parser.add_argument( # '--no_epoch', # default = 25, # type = int # ) #img_dir = 'A/train' #mask_dir = 'B/train' #device = torch.device("cuda:0") #torch.cuda.set_device(0) BATCH_SIZE = 1 EPOCH = 70 #C,H,W = 3,256,256 C,H,W = 2,47,150 C_depth = 2 # learn_rate = 0.001 # pretrained = True # start_time = moment.now().strftime('%Y-%m-%d_%H-%M-%S') # log_file = './logfiles/' + start_time + '.txt' # log_data = open(log_file,'w+') # model_path = './models/' + start_time + '/' # os.mkdir(model_path) # Exp_name = 'ECG segmentation' #'DristiData_Disc_NoDepth_RefineNet2_1' #'OrigaData_Disc_NoDepth_RefineNet2_1' #'OrigaData_Disc_NoDepth_RefineNet2_1' #'OrigaData_Disc_NoDepth_IncRefineNet2_1' # SETTINGS = 'Epoch %d, LR %f, BATCH_SIZE %d \n'%(EPOCH,learn_rate,BATCH_SIZE) # log_data.write(SETTINGS) # if (pretrained == True): model = UNet(in_shape=(C,H,W),num_classes=2) # model = model.load_state_dict(torch.load('./models/2018-07-05_14-26-27/Epoch17.pt')) model = torch.load('./models/2018-07-06_14-01-30/Epoch30.pt') # else: # model = UNet(in_shape=(C,H,W),num_classes=2) #--------- load pretrained model if necessary # model.load_state_dict(torch.load('./Checkpoints/RimoneCkpt/RimOneData_Disc_NoDepth_RefineNet2_1_200_epch.pth')) #model = model.to(device) model = model.cuda() # train_dat = torch.load('wavelet_dataset/train_dat_cwt.pt') test_dat = torch.load('wavelet_dataset/test_dat_cwt.pt') #transformed_dataset_train = CustomDataset(img_dir=img_dir,mask_dir=mask_dir,transform=transforms.Compose([Rescale(256), ToTensor()])) test_x = test_dat[:,:2]#torch.stack([train_dat[:,0],train_dat[:,1]],1)#train_dat[:,:1] test_y = test_dat[:,2:] #cwt_n = #torch.load('wavelet_dataset/train_cwt.pt') # print("Test X:", test_x.shape) # print("Test Y:", test_y.shape) test_set = data_utils.TensorDataset(test_x, test_y) testLoader = DataLoader(test_set, batch_size=BATCH_SIZE, shuffle=True, num_workers=4) # momentum parameter for Adam momentum = 0.9 # weight decay weightDecay = 0.005 # optimizer = optim.SGD(model.parameters(), lr = learn_rate,momentum = momentum) # exp_lr_scheduler = lr_scheduler.StepLR(optimizer,step_size=7,gamma=0.1) # criterion = nn.L1Loss() # criterion = nn.CrossEntropyLoss() # criterion = nn.NLLLoss2d() num_epochs = 70 y_train = {} for epoch in tqdm(range(num_epochs)): # print ('Epoch {}/{}'.format(epoch,num_epochs-1)) # print ('-'*10) model.train() running_loss = 0.0 step = 0 for data,label in testLoader: step+=1 inputs = data labels = label # print(inputs.shape) # print(labels.shape) #.squeeze(1) #cwt = data[:,1] # if (type(criterion)==type(nn.MSELoss()) or type(criterion)==type(nn.L1Loss())): labels = labels.type(torch.FloatTensor) # else: # labels = labels.type(torch.LongTensor) # inputs = inputs.to(device)#Variable(inputs.cuda()) # labels = labels.to(device)#Variable(labels.cuda()) inputs,labels = Variable(inputs.cuda()), Variable(labels.cuda()) outputs = model(inputs)#.squeeze(1) lab = outputs ecg_orig = visual(inputs[0]) label_new = visual(lab[0])#,inputs) label_orig = visual(labels[0])#[0],cw) # print('Label_new:',label_new.shape) # print('Label_orig:',label_orig.shape) fig, ax = plt.subplots(3, 1, figsize=(12,6)) ax = ax.flatten() ax[0].plot(ecg_orig) ax[0].set_title(r'ECG') ax[0].set_xlabel('Samples') ax[1].plot(label_orig) ax[1].set_title(r'Label source') ax[1].set_xlabel('Samples') ax[2].plot(label_new) ax[2].set_title(r'Label U-net') plt.tight_layout() plt.show() ax[2].set_xlabel('Samples') # print('Data:', inputs.size()) # print('Inputs:', inputs.size()) # print('Labels:', labels.size()) # print('cwt:', cwt.size()) # print('Output:', outputs.size()) # break #loss = criterion(outputs,labels) # print('Image:', inputs.size()) # print('Labels:', labels.size()) #optimizer.zero_grad() # with torch.set_grad_enable(True): #print(lo) #loss.backward() #optimizer.step() # if step % 10 == 0: # #print(outputs.data.cpu().numpy().shape) # y_train['pred'] = np.argmax(outputs.data.cpu().numpy().T,axis=1) # y_train['true'] = labels.data.cpu().numpy() # # print (y_train['true'].shape) # # print (y_train['pred'].shape) # y_train['inp'] = inputs.data.cpu().numpy().T #print(labels[0].size())#,labels.size()) #.squeeze(0) #cw = cwt[0].squeeze(0) # print(lab.shape) # print(labels[0].shape)#,labels[0].shape) # label_new = visual(lab)#,inputs) # label_orig = visual(labels[0])#[0],cw) # print('Label_new:',label_new.shape) # print('Label_orig:',label_orig.shape) # update = 'Epoch: ', epoch, '| step : %d' %step, ' | train loss : %.6f' % loss.data[0] # , '| test accuracy: %.4f' % acc # update_str = [str(i) for i in update] # update_str = ''.join(update_str) # print (update_str) # if (epoch>30 and pretrained ): # plt.plot(label_new) # plt.show() # log_data.write(update_str + '\n') # print ("Saving the model" ) # torch.save(model,model_path+'Epoch'+str(epoch)+'.pt')
[ "matplotlib.pyplot.tight_layout", "numpy.load", "matplotlib.pyplot.show", "wavelets_pytorch_2.alltorch.wavelets.Paul", "torch.utils.data.DataLoader", "torch.load", "unet_network.UNet", "torch.utils.data.TensorDataset", "numpy.linspace", "matplotlib.pyplot.subplots", "wavelets_pytorch_2.alltorch....
[((902, 911), 'wavelets_pytorch_2.alltorch.wavelets.Paul', 'Paul', ([], {'m': '(8)'}), '(m=8)\n', (906, 911), False, 'from wavelets_pytorch_2.alltorch.wavelets import Morlet, Ricker, DOG, Paul\n'), ((920, 946), 'numpy.linspace', 'np.linspace', (['(0)', '(1)'], {'num': '(150)'}), '(0, 1, num=150)\n', (931, 946), True, 'import numpy as np\n'), ((971, 1010), 'numpy.load', 'np.load', (['"""./wavelet_dataset/scales.npy"""'], {}), "('./wavelet_dataset/scales.npy')\n", (978, 1010), True, 'import numpy as np\n'), ((1273, 1337), 'wavelets_pytorch_2.alltorch.transform.WaveletTransformTorch', 'WaveletTransformTorch', (['dt', 'dj', 'wavelet'], {'unbias': 'unbias', 'cuda': '(True)'}), '(dt, dj, wavelet, unbias=unbias, cuda=True)\n', (1294, 1337), False, 'from wavelets_pytorch_2.alltorch.transform import WaveletTransformTorch\n'), ((2997, 3036), 'unet_network.UNet', 'UNet', ([], {'in_shape': '(C, H, W)', 'num_classes': '(2)'}), '(in_shape=(C, H, W), num_classes=2)\n', (3001, 3036), False, 'from unet_network import UNet\n'), ((3137, 3190), 'torch.load', 'torch.load', (['"""./models/2018-07-06_14-01-30/Epoch30.pt"""'], {}), "('./models/2018-07-06_14-01-30/Epoch30.pt')\n", (3147, 3190), False, 'import torch\n'), ((3565, 3610), 'torch.load', 'torch.load', (['"""wavelet_dataset/test_dat_cwt.pt"""'], {}), "('wavelet_dataset/test_dat_cwt.pt')\n", (3575, 3610), False, 'import torch\n'), ((4027, 4067), 'torch.utils.data.TensorDataset', 'data_utils.TensorDataset', (['test_x', 'test_y'], {}), '(test_x, test_y)\n', (4051, 4067), True, 'import torch.utils.data as data_utils\n'), ((4090, 4162), 'torch.utils.data.DataLoader', 'DataLoader', (['test_set'], {'batch_size': 'BATCH_SIZE', 'shuffle': '(True)', 'num_workers': '(4)'}), '(test_set, batch_size=BATCH_SIZE, shuffle=True, num_workers=4)\n', (4100, 4162), False, 'from torch.utils.data import DataLoader\n'), ((1061, 1085), 'torch.from_numpy', 'torch.from_numpy', (['scales'], {}), '(scales)\n', (1077, 1085), False, 'import torch\n'), ((5786, 5821), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(3)', '(1)'], {'figsize': '(12, 6)'}), '(3, 1, figsize=(12, 6))\n', (5798, 5821), True, 'import matplotlib.pyplot as plt\n'), ((6170, 6188), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (6186, 6188), True, 'import matplotlib.pyplot as plt\n'), ((6201, 6211), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (6209, 6211), True, 'import matplotlib.pyplot as plt\n')]
# Copyright 2021 Huawei Technologies Co., Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import numpy as np import argparse def read_class_names(class_file_name): ''' loads class name from a file ''' names = {} with open(class_file_name, 'r') as data: for id, name in enumerate(data): names[id] = name.strip('\n') return names def _iou(box1, box2): """ Computes Intersection over Union value for 2 bounding boxes :param box1: array of 4 values (top left and bottom right coords): [x0, y0, x1, x2] :param box2: same as box1 :return: IoU """ b1_x0, b1_y0, b1_x1, b1_y1 = box1 b2_x0, b2_y0, b2_x1, b2_y1 = box2 int_x0 = max(b1_x0, b2_x0) int_y0 = max(b1_y0, b2_y0) int_x1 = min(b1_x1, b2_x1) int_y1 = min(b1_y1, b2_y1) int_area = max(int_x1 - int_x0, 0) * max(int_y1 - int_y0, 0) b1_area = (b1_x1 - b1_x0) * (b1_y1 - b1_y0) b2_area = (b2_x1 - b2_x0) * (b2_y1 - b2_y0) # we add small epsilon of 1e-05 to avoid division by 0 iou = int_area / (b1_area + b2_area - int_area + 1e-05) return iou def non_max_suppression(predictions_with_boxes, confidence_threshold, iou_threshold=0.4): """ Applies Non-max suppression to prediction boxes. :param predictions_with_boxes: 3D numpy array, first 4 values in 3rd dimension are bbox attrs, 5th is confidence :param confidence_threshold: deciding if prediction is valid :param iou_threshold: deciding if two boxes overlap :return: dict: class -> [(box, score)] """ conf_mask = np.expand_dims( (predictions_with_boxes[:, :, 4] > confidence_threshold), -1) predictions = predictions_with_boxes * conf_mask result = {} for image_pred in predictions: shape = image_pred.shape # non_zero_idxs = np.nonzero(image_pred) temp = image_pred sum_t = np.sum(temp, axis=1) non_zero_idxs = (sum_t != 0) image_pred = image_pred[non_zero_idxs] image_pred = image_pred.reshape(-1, shape[-1]) bbox_attrs = image_pred[:, :5] classes = image_pred[:, 5:] classes = np.argmax(classes, axis=-1) unique_classes = list(set(classes.reshape(-1))) for cls in unique_classes: cls_mask = classes == cls cls_boxes = bbox_attrs[np.nonzero(cls_mask)] cls_boxes = cls_boxes[cls_boxes[:, -1].argsort()[::-1]] cls_scores = cls_boxes[:, -1] cls_boxes = cls_boxes[:, :-1] while len(cls_boxes) > 0: box = cls_boxes[0] score = cls_scores[0] if cls not in result: result[cls] = [] result[cls].append((box, score)) cls_boxes = cls_boxes[1:] cls_scores = cls_scores[1:] ious = np.array([_iou(box, x) for x in cls_boxes]) iou_mask = ious < iou_threshold cls_boxes = cls_boxes[np.nonzero(iou_mask)] cls_scores = cls_scores[np.nonzero(iou_mask)] return result def parse_line(line): '''解析输入的confg文件,文件每一行是序号 文件名 宽 高''' temp = line.split(" ") index = temp[1].split("/")[-1].split(".")[0] # 放置高宽(不是宽高) return index, (int(temp[3]), int(temp[2])) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("--bin_data_path", default="./JPEGImages/") parser.add_argument("--test_annotation", default="input/benchmark_input.txt") parser.add_argument("--det_results_path", default="input/detection-results/") parser.add_argument("--coco_class_names", default="./coco.names") parser.add_argument("--voc_class_names", default="./voc.names") parser.add_argument("--net_input_size", default=416) parser.add_argument("--net_out_num", default=1) flags = parser.parse_args() # 根据标注文件生成字典,用于查询分辨率 # 加载输入图片的宽高信息 img_size_dict = dict() with open(flags.test_annotation)as f: for line in f.readlines(): temp = parse_line(line) img_size_dict[temp[0]] = temp[1] # 加载coco和voc的index->类别的映射关系 coco_class_map = read_class_names(flags.coco_class_names) voc_class_map = read_class_names(flags.voc_class_names) coco_set = set(coco_class_map.values()) voc_set = set(voc_class_map.values()) # 读取bin文件用于生成预测结果 bin_path = flags.bin_data_path net_input_size = flags.net_input_size det_results_path = flags.det_results_path os.makedirs(det_results_path, exist_ok=True) total_img = set([name.split("_")[0] for name in os.listdir(bin_path) if "bin" in name]) for bin_file in sorted(total_img): path_base = os.path.join(bin_path, bin_file) # 加载检测的所有输出tensor res_buff = [] for num in range(flags.net_out_num): print(path_base + "_" + str(num + 1) + ".bin") if os.path.exists(path_base + "_" + str(num + 1) + ".bin"): buf = np.fromfile(path_base + "_" + str(num + 1) + ".bin", dtype="float32") res_buff.append(buf) else: print("[ERROR] file not exist", path_base + "_" + str(num + 1) + ".bin") res_tensor = np.concatenate(res_buff, axis=0) # resize成1*?*85维度,1置信+4box+80类 pred_bbox = res_tensor.reshape([1, -1, 85]) img_index_str = bin_file.split("_")[0] bboxes = [] if img_index_str in img_size_dict: bboxes = non_max_suppression(pred_bbox, 0.5, 0.4) else: print("[ERROR] input with no width height") det_results_str = "" # YOLO输出是COCO类别,包含了VOC的20类,将VOC20类写入预测结果,用于map评估 current_img_size = img_size_dict[img_index_str] for class_ind in bboxes: class_name = coco_class_map[class_ind] score = bboxes[class_ind][0][1] bbox = bboxes[class_ind][0][0] if class_name in voc_set: # 对每个维度的坐标进行缩放,从输入尺寸,缩放到原尺寸 hscale = current_img_size[0] / float(flags.net_input_size) wscale = current_img_size[1] / float(flags.net_input_size) det_results_str += "{} {} {} {} {} {}\n".format( class_name, str(score), str(bbox[0] * wscale), str(bbox[1] * hscale), str(bbox[2] * wscale), str(bbox[3] * hscale)) det_results_file = os.path.join( det_results_path, img_index_str + ".txt") with open(det_results_file, "w") as detf: detf.write(det_results_str)
[ "numpy.sum", "os.makedirs", "argparse.ArgumentParser", "numpy.argmax", "numpy.expand_dims", "numpy.nonzero", "os.path.join", "os.listdir", "numpy.concatenate" ]
[((2116, 2190), 'numpy.expand_dims', 'np.expand_dims', (['(predictions_with_boxes[:, :, 4] > confidence_threshold)', '(-1)'], {}), '(predictions_with_boxes[:, :, 4] > confidence_threshold, -1)\n', (2130, 2190), True, 'import numpy as np\n'), ((3878, 3903), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (3901, 3903), False, 'import argparse\n'), ((5084, 5128), 'os.makedirs', 'os.makedirs', (['det_results_path'], {'exist_ok': '(True)'}), '(det_results_path, exist_ok=True)\n', (5095, 5128), False, 'import os\n'), ((2431, 2451), 'numpy.sum', 'np.sum', (['temp'], {'axis': '(1)'}), '(temp, axis=1)\n', (2437, 2451), True, 'import numpy as np\n'), ((2686, 2713), 'numpy.argmax', 'np.argmax', (['classes'], {'axis': '(-1)'}), '(classes, axis=-1)\n', (2695, 2713), True, 'import numpy as np\n'), ((5301, 5333), 'os.path.join', 'os.path.join', (['bin_path', 'bin_file'], {}), '(bin_path, bin_file)\n', (5313, 5333), False, 'import os\n'), ((5871, 5903), 'numpy.concatenate', 'np.concatenate', (['res_buff'], {'axis': '(0)'}), '(res_buff, axis=0)\n', (5885, 5903), True, 'import numpy as np\n'), ((7053, 7107), 'os.path.join', 'os.path.join', (['det_results_path', "(img_index_str + '.txt')"], {}), "(det_results_path, img_index_str + '.txt')\n", (7065, 7107), False, 'import os\n'), ((2880, 2900), 'numpy.nonzero', 'np.nonzero', (['cls_mask'], {}), '(cls_mask)\n', (2890, 2900), True, 'import numpy as np\n'), ((5202, 5222), 'os.listdir', 'os.listdir', (['bin_path'], {}), '(bin_path)\n', (5212, 5222), False, 'import os\n'), ((3529, 3549), 'numpy.nonzero', 'np.nonzero', (['iou_mask'], {}), '(iou_mask)\n', (3539, 3549), True, 'import numpy as np\n'), ((3591, 3611), 'numpy.nonzero', 'np.nonzero', (['iou_mask'], {}), '(iou_mask)\n', (3601, 3611), True, 'import numpy as np\n')]
import numpy as np from keras.utils import np_utils import time from datetime import timedelta from sklearn.naive_bayes import GaussianNB from sklearn.externals import joblib from sklearn.metrics import confusion_matrix from sklearn.metrics import classification_report import argparse import math import dataset_traditional as dataset def build_dataset(data_directory, img_width): X, y, tags = dataset.dataset(data_directory, int(img_width)) nb_classes = len(tags) feature = X label = np_utils.to_categorical(y, nb_classes) return feature, label, nb_classes def naivebayes_classifier(features, target): clf = GaussianNB() clf.fit(features, target) return clf def main(): start_time = time.monotonic() parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('-i', '--input', help='an input directory of dataset', required=True) parser.add_argument('-d', '--dimension', help='a image dimension', type=int, default=50) parser.add_argument('-o', '--output', help='a result file', type=str, default="output_result_nb.txt") args = parser.parse_args() data_directory = args.input print("loading dataset") X_train, Y_train, nb_classes = build_dataset( "{}/train".format(data_directory), args.dimension) X_test, Y_test, nb_classes = build_dataset( "{}/test".format(data_directory), args.dimension) print("number of classes : {}".format(nb_classes)) # new_shape = (X_train.shape[0] * X_train.shape[1], X_train[2] - 1) # X_trains = X_train[:, :, :3].reshape(new_shape) # print("shape {}".format(X_trains.shape)) trained_model = naivebayes_classifier(X_train, Y_train) # Save Model or creates a HDF5 file # joblib.dump(trained_model, 'knn_model_{}.pkl'.format( # data_directory.replace("/", "_"))) predicted = trained_model.predict(X_test) y_pred = np.argmax(predicted, axis=1) Y_test = np.argmax(Y_test, axis=1) cm = confusion_matrix(Y_test, y_pred) report = classification_report(Y_test, y_pred) tn = cm[0][0] fn = cm[1][0] tp = cm[1][1] fp = cm[0][1] if tp == 0: tp = 1 if tn == 0: tn = 1 if fp == 0: fp = 1 if fn == 0: fn = 1 TPR = float(tp)/(float(tp)+float(fn)) FPR = float(fp)/(float(fp)+float(tn)) accuracy = round((float(tp) + float(tn))/(float(tp) + float(fp) + float(fn) + float(tn)), 3) specitivity = round(float(tn)/(float(tn) + float(fp)), 3) sensitivity = round(float(tp)/(float(tp) + float(fn)), 3) mcc = round((float(tp)*float(tn) - float(fp)*float(fn))/math.sqrt( (float(tp)+float(fp)) * (float(tp)+float(fn)) * (float(tn)+float(fp)) * (float(tn)+float(fn)) ), 3) f_output = open(args.output, 'a') f_output.write('=======\n') f_output.write('knn_model_{}\n'.format( data_directory.replace("/", "_"))) f_output.write('TN: {}\n'.format(tn)) f_output.write('FN: {}\n'.format(fn)) f_output.write('TP: {}\n'.format(tp)) f_output.write('FP: {}\n'.format(fp)) f_output.write('TPR: {}\n'.format(TPR)) f_output.write('FPR: {}\n'.format(FPR)) f_output.write('accuracy: {}\n'.format(accuracy)) f_output.write('specitivity: {}\n'.format(specitivity)) f_output.write("sensitivity : {}\n".format(sensitivity)) f_output.write("mcc : {}\n".format(mcc)) f_output.write("{}".format(report)) f_output.write('=======\n') f_output.close() end_time = time.monotonic() print("Duration : {}".format(timedelta(seconds=end_time - start_time))) if __name__ == "__main__": main()
[ "sklearn.naive_bayes.GaussianNB", "argparse.ArgumentParser", "numpy.argmax", "sklearn.metrics.classification_report", "keras.utils.np_utils.to_categorical", "time.monotonic", "datetime.timedelta", "sklearn.metrics.confusion_matrix" ]
[((505, 543), 'keras.utils.np_utils.to_categorical', 'np_utils.to_categorical', (['y', 'nb_classes'], {}), '(y, nb_classes)\n', (528, 543), False, 'from keras.utils import np_utils\n'), ((639, 651), 'sklearn.naive_bayes.GaussianNB', 'GaussianNB', ([], {}), '()\n', (649, 651), False, 'from sklearn.naive_bayes import GaussianNB\n'), ((728, 744), 'time.monotonic', 'time.monotonic', ([], {}), '()\n', (742, 744), False, 'import time\n'), ((758, 837), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'formatter_class': 'argparse.ArgumentDefaultsHelpFormatter'}), '(formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n', (781, 837), False, 'import argparse\n'), ((2011, 2039), 'numpy.argmax', 'np.argmax', (['predicted'], {'axis': '(1)'}), '(predicted, axis=1)\n', (2020, 2039), True, 'import numpy as np\n'), ((2053, 2078), 'numpy.argmax', 'np.argmax', (['Y_test'], {'axis': '(1)'}), '(Y_test, axis=1)\n', (2062, 2078), True, 'import numpy as np\n'), ((2088, 2120), 'sklearn.metrics.confusion_matrix', 'confusion_matrix', (['Y_test', 'y_pred'], {}), '(Y_test, y_pred)\n', (2104, 2120), False, 'from sklearn.metrics import confusion_matrix\n'), ((2134, 2171), 'sklearn.metrics.classification_report', 'classification_report', (['Y_test', 'y_pred'], {}), '(Y_test, y_pred)\n', (2155, 2171), False, 'from sklearn.metrics import classification_report\n'), ((3668, 3684), 'time.monotonic', 'time.monotonic', ([], {}), '()\n', (3682, 3684), False, 'import time\n'), ((3718, 3758), 'datetime.timedelta', 'timedelta', ([], {'seconds': '(end_time - start_time)'}), '(seconds=end_time - start_time)\n', (3727, 3758), False, 'from datetime import timedelta\n')]
#-*- coding:utf-8 -*- import os import numpy as np from scipy.spatial import distance from variables import POS_TAGS, APPS from variables import DUPLICATES_CLUSTER_PATH, DUPLICATES_CLUSTER_IMG_PATH from util_db import select_cluster_combine_tag from util_db import select_cluster_id_txt, select_cluster_id_img from util_db import select_cluster_txt_tag, select_cluster_img_tag from util_db import insert_top_txt_into_sql, insert_top_img_into_sql from util_hist import read_hist_img, get_img_pos from util_hist import preprocess_line from util_pagerank import graphMove, firstPr, pageRank # --------------------------------------------------------------------------------------- # Description : Function to sort the sentences/screenshots within each supplementary and save them to database # --------------------------------------------------------------------------------------- def distance_sentence_jaccard(sentence_a,sentence_b): inter = 0 union = 0 for word_a in sentence_a: if word_a in sentence_b: inter = inter + 1 union = len(sentence_a) + len(sentence_b) - inter return 1 - (inter*1.0)/(union*1.0) def distance_img(app,img_name_a,img_name_b): hist_img = read_hist_img(app) index_a = get_img_pos(img_name_a) index_b = get_img_pos(img_name_b) img_a = hist_img[index_a] img_b = hist_img[index_b] dis = distance.euclidean(img_a, img_b) return dis def processing(sentence_list): line_list = [] for line in sentence_list: if line == '': break line = preprocess_line(line) words = [x.split('_') for x in line.split(' ')] line_list.append(words) return line_list def calculate_txt_pr_matrix(diff_sentence_list): pr_matrix = [] for sentence_a in diff_sentence_list: weight_list = [] for sentence_b in diff_sentence_list: distance = distance_sentence_jaccard(sentence_a, sentence_b) weight = 1 - distance weight_list.append(weight) distance = 0 weight = 0 pr_matrix.append(weight_list) return pr_matrix def calculate_img_pr_matrix(app,diff_img_list): pr_matrix = [] for img_a in diff_img_list: weight_list = [] for img_b in diff_img_list: distance = distance_img(app, img_a, img_b) weight = 1 - distance weight_list.append(weight) distance = 0 weight = 0 pr_matrix.append(weight_list) return pr_matrix def get_txt_pagerank(diff_sentence_list): pr_matrix = calculate_txt_pr_matrix(diff_sentence_list) a_matrix = np.array(pr_matrix) M = graphMove(a_matrix) pr = firstPr(M) p = 0.8 re = pageRank(p,M,pr) return re def get_img_pagerank(diff_img_list): pr_matrix = calculate_img_pr_matrix(app, diff_img_list) a_matrix = np.array(pr_matrix) M = graphMove(a_matrix) pr = firstPr(M) p = 0.8 re = pageRank(p,M,pr) return re def calculate_cluster_txt_pr(app): for group_id in sorted(os.listdir('/'.join([DUPLICATES_CLUSTER_PATH, app]))): cluster_combine_tags = select_cluster_combine_tag(group_id, app) for cluster_combine_tag in cluster_combine_tags: cluster_ids = select_cluster_id_txt(cluster_combine_tag[0], group_id, app) for cluster_id_ in cluster_ids: cluster_id = cluster_id_[0] if cluster_id != None: # contain textual candidate cluster cluster_txt = select_cluster_txt_tag(cluster_id, group_id, app) diff_sentence_list = [] report_id_list = [] diff_sentence_index_list = [] for cluster_info in cluster_txt: diff_sentence_list.append(cluster_info[0]) report_id_list.append(cluster_info[1]) diff_sentence_index_list.append(cluster_info[2]) if len(diff_sentence_list) > 1: diff_sentence_list_process = processing(diff_sentence_list) pr = get_txt_pagerank(diff_sentence_list_process) pr_dict = {} flag1 = 0 for tmp in pr: pr_dict[str(flag1)] = tmp[0] flag1 = flag1 + 1 top_n = 0 for key,value in sorted(pr_dict.items(), key=lambda d:d[1], reverse = True): txts = (str(top_n), diff_sentence_list[int(key)], report_id_list[int(key)], diff_sentence_index_list[int(key)]) insert_top_txt_into_sql(app, group_id, cluster_combine_tag[0], txts) top_n = top_n + 1 if len(diff_sentence_list) == 1: # there is only one sentence txts = ('0', diff_sentence_list[0], report_id_list[0], diff_sentence_index_list[0]) insert_top_txt_into_sql(app, group_id, cluster_combine_tag[0], txts) def calculate_cluster_img_pr(app): for group_id in sorted(os.listdir('/'.join([DUPLICATES_CLUSTER_IMG_PATH, app]))): cluster_combine_tags = select_cluster_combine_tag(group_id, app) for cluster_combine_tag in cluster_combine_tags: cluster_ids = select_cluster_id_img(cluster_combine_tag[0], group_id,app) for cluster_id_ in cluster_ids: cluster_id = cluster_id_[0] if cluster_id != None: # contain image candidate cluster cluster_img = select_cluster_img_tag(cluster_id, group_id, app) diff_img_list = [] report_id_list = [] for cluster_info in cluster_img: diff_img_list.append(cluster_info[0]) report_id_list.append(cluster_info[1]) if len(diff_img_list) > 1: pr = get_img_pagerank(diff_img_list) pr_dict = {} flag1 = 0 for tmp in pr: pr_dict[str(flag1)] = tmp[0] flag1 = flag1 + 1 top_n = 0 for key,value in sorted(pr_dict.iteritems(), key=lambda d:d[1], reverse = True): imgs = [] imgs = (str(top_n), diff_img_list[int(key)], report_id_list[int(key)]) insert_top_img_into_sql(app,group_id,cluster_combine_tag[0],imgs) top_n = top_n + 1 if len(diff_img_list) == 1: # there is only one image imgs = ('0', diff_img_list[0], report_id_list[0]) insert_top_img_into_sql(app,group_id,cluster_combine_tag[0],imgs) for app in APPS: calculate_cluster_txt_pr(app) #calculate_cluster_img_pr(app)
[ "util_db.select_cluster_combine_tag", "util_pagerank.pageRank", "scipy.spatial.distance.euclidean", "util_hist.preprocess_line", "util_db.select_cluster_id_txt", "util_pagerank.graphMove", "util_pagerank.firstPr", "util_hist.read_hist_img", "numpy.array", "util_db.select_cluster_txt_tag", "util_...
[((1182, 1200), 'util_hist.read_hist_img', 'read_hist_img', (['app'], {}), '(app)\n', (1195, 1200), False, 'from util_hist import read_hist_img, get_img_pos\n'), ((1213, 1236), 'util_hist.get_img_pos', 'get_img_pos', (['img_name_a'], {}), '(img_name_a)\n', (1224, 1236), False, 'from util_hist import read_hist_img, get_img_pos\n'), ((1248, 1271), 'util_hist.get_img_pos', 'get_img_pos', (['img_name_b'], {}), '(img_name_b)\n', (1259, 1271), False, 'from util_hist import read_hist_img, get_img_pos\n'), ((1335, 1367), 'scipy.spatial.distance.euclidean', 'distance.euclidean', (['img_a', 'img_b'], {}), '(img_a, img_b)\n', (1353, 1367), False, 'from scipy.spatial import distance\n'), ((2415, 2434), 'numpy.array', 'np.array', (['pr_matrix'], {}), '(pr_matrix)\n', (2423, 2434), True, 'import numpy as np\n'), ((2440, 2459), 'util_pagerank.graphMove', 'graphMove', (['a_matrix'], {}), '(a_matrix)\n', (2449, 2459), False, 'from util_pagerank import graphMove, firstPr, pageRank\n'), ((2466, 2476), 'util_pagerank.firstPr', 'firstPr', (['M'], {}), '(M)\n', (2473, 2476), False, 'from util_pagerank import graphMove, firstPr, pageRank\n'), ((2496, 2514), 'util_pagerank.pageRank', 'pageRank', (['p', 'M', 'pr'], {}), '(p, M, pr)\n', (2504, 2514), False, 'from util_pagerank import graphMove, firstPr, pageRank\n'), ((2632, 2651), 'numpy.array', 'np.array', (['pr_matrix'], {}), '(pr_matrix)\n', (2640, 2651), True, 'import numpy as np\n'), ((2657, 2676), 'util_pagerank.graphMove', 'graphMove', (['a_matrix'], {}), '(a_matrix)\n', (2666, 2676), False, 'from util_pagerank import graphMove, firstPr, pageRank\n'), ((2683, 2693), 'util_pagerank.firstPr', 'firstPr', (['M'], {}), '(M)\n', (2690, 2693), False, 'from util_pagerank import graphMove, firstPr, pageRank\n'), ((2713, 2731), 'util_pagerank.pageRank', 'pageRank', (['p', 'M', 'pr'], {}), '(p, M, pr)\n', (2721, 2731), False, 'from util_pagerank import graphMove, firstPr, pageRank\n'), ((1491, 1512), 'util_hist.preprocess_line', 'preprocess_line', (['line'], {}), '(line)\n', (1506, 1512), False, 'from util_hist import preprocess_line\n'), ((2889, 2930), 'util_db.select_cluster_combine_tag', 'select_cluster_combine_tag', (['group_id', 'app'], {}), '(group_id, app)\n', (2915, 2930), False, 'from util_db import select_cluster_combine_tag\n'), ((4506, 4547), 'util_db.select_cluster_combine_tag', 'select_cluster_combine_tag', (['group_id', 'app'], {}), '(group_id, app)\n', (4532, 4547), False, 'from util_db import select_cluster_combine_tag\n'), ((2999, 3059), 'util_db.select_cluster_id_txt', 'select_cluster_id_txt', (['cluster_combine_tag[0]', 'group_id', 'app'], {}), '(cluster_combine_tag[0], group_id, app)\n', (3020, 3059), False, 'from util_db import select_cluster_id_txt, select_cluster_id_img\n'), ((4616, 4676), 'util_db.select_cluster_id_img', 'select_cluster_id_img', (['cluster_combine_tag[0]', 'group_id', 'app'], {}), '(cluster_combine_tag[0], group_id, app)\n', (4637, 4676), False, 'from util_db import select_cluster_id_txt, select_cluster_id_img\n'), ((3209, 3258), 'util_db.select_cluster_txt_tag', 'select_cluster_txt_tag', (['cluster_id', 'group_id', 'app'], {}), '(cluster_id, group_id, app)\n', (3231, 3258), False, 'from util_db import select_cluster_txt_tag, select_cluster_img_tag\n'), ((4823, 4872), 'util_db.select_cluster_img_tag', 'select_cluster_img_tag', (['cluster_id', 'group_id', 'app'], {}), '(cluster_id, group_id, app)\n', (4845, 4872), False, 'from util_db import select_cluster_txt_tag, select_cluster_img_tag\n'), ((4293, 4361), 'util_db.insert_top_txt_into_sql', 'insert_top_txt_into_sql', (['app', 'group_id', 'cluster_combine_tag[0]', 'txts'], {}), '(app, group_id, cluster_combine_tag[0], txts)\n', (4316, 4361), False, 'from util_db import insert_top_txt_into_sql, insert_top_img_into_sql\n'), ((5658, 5726), 'util_db.insert_top_img_into_sql', 'insert_top_img_into_sql', (['app', 'group_id', 'cluster_combine_tag[0]', 'imgs'], {}), '(app, group_id, cluster_combine_tag[0], imgs)\n', (5681, 5726), False, 'from util_db import insert_top_txt_into_sql, insert_top_img_into_sql\n'), ((4036, 4104), 'util_db.insert_top_txt_into_sql', 'insert_top_txt_into_sql', (['app', 'group_id', 'cluster_combine_tag[0]', 'txts'], {}), '(app, group_id, cluster_combine_tag[0], txts)\n', (4059, 4104), False, 'from util_db import insert_top_txt_into_sql, insert_top_img_into_sql\n'), ((5446, 5514), 'util_db.insert_top_img_into_sql', 'insert_top_img_into_sql', (['app', 'group_id', 'cluster_combine_tag[0]', 'imgs'], {}), '(app, group_id, cluster_combine_tag[0], imgs)\n', (5469, 5514), False, 'from util_db import insert_top_txt_into_sql, insert_top_img_into_sql\n')]
import torch import numpy as np import yaml, pickle, os, math from random import shuffle #from Pattern_Generator import Pattern_Generate from Pattern_Generator import Pattern_Generate with open('Hyper_Parameter.yaml') as f: hp_Dict = yaml.load(f, Loader=yaml.Loader) class Train_Dataset(torch.utils.data.Dataset): def __init__(self): super(Train_Dataset, self).__init__() metadata_Dict = pickle.load(open( os.path.join(hp_Dict['Train']['Train_Pattern']['Path'], hp_Dict['Train']['Train_Pattern']['Metadata_File']).replace('\\', '/'), 'rb' )) self.file_List = [ x for x in metadata_Dict['File_List'] # if metadata_Dict['Mel_Length_Dict'][x] > hp_Dict['Train']['Train_Pattern']['Pattern_Length'] ] * hp_Dict['Train']['Train_Pattern']['Accumulated_Dataset_Epoch'] self.dataset_Dict = metadata_Dict['Dataset_Dict'] self.cache_Dict = {} def __getitem__(self, idx): if idx in self.cache_Dict.keys(): return self.cache_Dict[idx] file = self.file_List[idx] dataset = self.dataset_Dict[file] path = os.path.join(hp_Dict['Train']['Train_Pattern']['Path'], dataset, file).replace('\\', '/') pattern_Dict = pickle.load(open(path, 'rb')) pattern = pattern_Dict['Mel'], pattern_Dict['Pitch'] if hp_Dict['Train']['Use_Pattern_Cache']: self.cache_Dict[path] = pattern return pattern def __len__(self): return len(self.file_List) class Dev_Dataset(torch.utils.data.Dataset): def __init__(self): super(Dev_Dataset, self).__init__() metadata_Dict = pickle.load(open( os.path.join(hp_Dict['Train']['Eval_Pattern']['Path'], hp_Dict['Train']['Eval_Pattern']['Metadata_File']).replace('\\', '/'), 'rb' )) self.file_List = [ x for x in metadata_Dict['File_List'] ] self.dataset_Dict = metadata_Dict['Dataset_Dict'] self.cache_Dict = {} def __getitem__(self, idx): if idx in self.cache_Dict.keys(): return self.cache_Dict[idx] file = self.file_List[idx] dataset = self.dataset_Dict[file] path = os.path.join(hp_Dict['Train']['Eval_Pattern']['Path'], dataset, file).replace('\\', '/') pattern_Dict = pickle.load(open(path, 'rb')) pattern = pattern_Dict['Mel'], pattern_Dict['Pitch'] if hp_Dict['Train']['Use_Pattern_Cache']: self.cache_Dict[path] = pattern return pattern def __len__(self): return len(self.file_List) class Inference_Dataset(torch.utils.data.Dataset): def __init__(self, pattern_path= 'Wav_Path_for_Inference.txt'): super(Inference_Dataset, self).__init__() self.pattern_List = [ line.strip().split('\t') for line in open(pattern_path, 'r').readlines()[1:] ] self.cache_Dict = {} def __getitem__(self, idx): if idx in self.cache_Dict.keys(): return self.cache_Dict[idx] source_Label, source_Path, target_Label, target_Path = self.pattern_List[idx] _, source_Mel, source_Pitch = Pattern_Generate(source_Path, 15) _, target_Mel, _ = Pattern_Generate(target_Path, 15) pattern = source_Mel, target_Mel, source_Pitch, source_Label, target_Label if hp_Dict['Train']['Use_Pattern_Cache']: self.cache_Dict[idx] = pattern return pattern def __len__(self): return len(self.pattern_List) class Collater: def __call__(self, batch): mels, pitches = zip(*[ (mel, pitch) for mel, pitch in batch ]) mels = [ mel * np.random.uniform( low= hp_Dict['Train']['Train_Pattern']['Energy_Variance']['Min'], high= hp_Dict['Train']['Train_Pattern']['Energy_Variance']['Max'] ) for mel in mels ] stack_Size = np.random.randint( low= hp_Dict['Train']['Train_Pattern']['Mel_Length']['Min'], high= hp_Dict['Train']['Train_Pattern']['Mel_Length']['Max'] + 1 ) contents, pitches = Stack(mels, pitches, size= stack_Size) styles = Style_Stack(mels) contents = torch.FloatTensor(contents) # [Batch, Mel_dim, Time] styles = torch.FloatTensor(styles) # [Batch * Samples, Mel_dim, Time] pitches = torch.FloatTensor(pitches) # [Batch, Time] interpolation_Size = np.random.randint( low= int(stack_Size * hp_Dict['Train']['Train_Pattern']['Interpolation']['Min']), high= int(stack_Size * hp_Dict['Train']['Train_Pattern']['Interpolation']['Max']) ) interpolation_Size = int(np.ceil( interpolation_Size / hp_Dict['Content_Encoder']['Frequency'] )) * hp_Dict['Content_Encoder']['Frequency'] contents = torch.nn.functional.interpolate( input= contents, size= interpolation_Size, mode= 'linear', align_corners= True ) pitches = torch.nn.functional.interpolate( input= pitches.unsqueeze(1), size= interpolation_Size, mode= 'linear', align_corners= True ).squeeze(1) return contents, styles, pitches class Inference_Collater: def __call__(self, batch): source_Mels, target_Mels, source_Pitchs, source_Labels, target_Labels = zip(*[ (source_Mel, target_Mel, source_Pitch, source_Label, target_Label) for source_Mel, target_Mel, source_Pitch, source_Label, target_Label in batch ]) contents, pitches, lengths = Stack(source_Mels, source_Pitchs) content_Styles = Style_Stack(source_Mels) target_Styles = Style_Stack(target_Mels) contents = torch.FloatTensor(contents) # [Batch, Mel_dim, Time] content_Styles = torch.FloatTensor(content_Styles) # [Batch * Samples, Mel_dim, Time] target_Styles = torch.FloatTensor(target_Styles) # [Batch * Samples, Mel_dim, Time] pitches = torch.FloatTensor(pitches) # [Batch, Time] return contents, content_Styles, target_Styles, pitches, lengths, source_Labels, target_Labels def Stack(mels, pitches, size= None): if size is None: max_Length = max([mel.shape[0] for mel in mels]) max_Length = int(np.ceil( max_Length / hp_Dict['Content_Encoder']['Frequency'] )) * hp_Dict['Content_Encoder']['Frequency'] lengths = [mel.shape[0] for mel in mels] mels = np.stack([ np.pad(mel, [(0, max_Length - mel.shape[0]), (0, 0)], constant_values= -hp_Dict['Sound']['Max_Abs_Mel']) for mel in mels ], axis= 0) pitches = np.stack([ np.pad(pitch, (0, max_Length - pitch.shape[0]), constant_values= 0.0) for pitch in pitches ], axis= 0) return mels.transpose(0, 2, 1), pitches, lengths mel_List = [] pitch_List = [] for mel, pitch in zip(mels, pitches): if mel.shape[0] > size: offset = np.random.randint(0, mel.shape[0] - size) mel = mel[offset:offset + size] pitch = pitch[offset:offset + size] else: pad = size - mel.shape[0] mel = np.pad( mel, [[int(np.floor(pad / 2)), int(np.ceil(pad / 2))], [0, 0]], mode= 'reflect' ) pitch = np.pad( pitch, [int(np.floor(pad / 2)), int(np.ceil(pad / 2))], mode= 'reflect' ) mel_List.append(mel) pitch_List.append(pitch) return np.stack(mel_List, axis= 0).transpose(0, 2, 1), np.stack(pitch_List, axis= 0) def Style_Stack(mels): styles = [] for mel in mels: overlap_Length = hp_Dict['Style_Encoder']['Inference']['Overlap_Length'] slice_Length = hp_Dict['Style_Encoder']['Inference']['Slice_Length'] required_Length = hp_Dict['Style_Encoder']['Inference']['Samples'] * (slice_Length - overlap_Length) + overlap_Length if mel.shape[0] > required_Length: offset = np.random.randint(0, mel.shape[0] - required_Length) mel = mel[offset:offset + required_Length] else: pad = (required_Length - mel.shape[0]) / 2 mel = np.pad( mel, [[int(np.floor(pad)), int(np.ceil(pad))], [0, 0]], mode= 'reflect' ) mel = np.stack([ mel[index:index + slice_Length] for index in range(0, required_Length - overlap_Length, slice_Length - overlap_Length) ]) styles.append(mel) return np.vstack(styles).transpose(0, 2, 1) if __name__ == "__main__": # dataLoader = torch.utils.data.DataLoader( # dataset= Train_Dataset(), # shuffle= True, # collate_fn= Collater(), # batch_size= hp_Dict['Train']['Batch_Size'], # num_workers= hp_Dict['Train']['Num_Workers'], # pin_memory= True # ) # dataLoader = torch.utils.data.DataLoader( # dataset= Dev_Dataset(), # shuffle= True, # collate_fn= Collater(), # batch_size= hp_Dict['Train']['Batch_Size'], # num_workers= hp_Dict['Train']['Num_Workers'], # pin_memory= True # ) # import time # for x in dataLoader: # speakers, mels, pitches, factors = x # print(speakers.shape) # print(mels.shape) # print(pitches.shape) # print(factors) # time.sleep(2.0) dataLoader = torch.utils.data.DataLoader( dataset= Inference_Dataset(), shuffle= False, collate_fn= Inference_Collater(), batch_size= hp_Dict['Train']['Batch_Size'], num_workers= hp_Dict['Train']['Num_Workers'], pin_memory= True ) import time for x in dataLoader: speakers, rhymes, contents, pitches, factors, rhyme_Labels, content_Labels, pitch_Labels, lengths = x print(speakers.shape) print(rhymes.shape) print(contents.shape) print(pitches.shape) print(factors) print(rhyme_Labels) print(content_Labels) print(pitch_Labels) print(lengths) time.sleep(2.0)
[ "numpy.stack", "numpy.random.uniform", "yaml.load", "numpy.pad", "numpy.ceil", "numpy.floor", "torch.FloatTensor", "time.sleep", "numpy.random.randint", "Pattern_Generator.Pattern_Generate", "torch.nn.functional.interpolate", "os.path.join", "numpy.vstack" ]
[((239, 271), 'yaml.load', 'yaml.load', (['f'], {'Loader': 'yaml.Loader'}), '(f, Loader=yaml.Loader)\n', (248, 271), False, 'import yaml, pickle, os, math\n'), ((3251, 3284), 'Pattern_Generator.Pattern_Generate', 'Pattern_Generate', (['source_Path', '(15)'], {}), '(source_Path, 15)\n', (3267, 3284), False, 'from Pattern_Generator import Pattern_Generate\n'), ((3312, 3345), 'Pattern_Generator.Pattern_Generate', 'Pattern_Generate', (['target_Path', '(15)'], {}), '(target_Path, 15)\n', (3328, 3345), False, 'from Pattern_Generator import Pattern_Generate\n'), ((4087, 4234), 'numpy.random.randint', 'np.random.randint', ([], {'low': "hp_Dict['Train']['Train_Pattern']['Mel_Length']['Min']", 'high': "(hp_Dict['Train']['Train_Pattern']['Mel_Length']['Max'] + 1)"}), "(low=hp_Dict['Train']['Train_Pattern']['Mel_Length']['Min'\n ], high=hp_Dict['Train']['Train_Pattern']['Mel_Length']['Max'] + 1)\n", (4104, 4234), True, 'import numpy as np\n'), ((4392, 4419), 'torch.FloatTensor', 'torch.FloatTensor', (['contents'], {}), '(contents)\n', (4409, 4419), False, 'import torch\n'), ((4464, 4489), 'torch.FloatTensor', 'torch.FloatTensor', (['styles'], {}), '(styles)\n', (4481, 4489), False, 'import torch\n'), ((4544, 4570), 'torch.FloatTensor', 'torch.FloatTensor', (['pitches'], {}), '(pitches)\n', (4561, 4570), False, 'import torch\n'), ((5031, 5142), 'torch.nn.functional.interpolate', 'torch.nn.functional.interpolate', ([], {'input': 'contents', 'size': 'interpolation_Size', 'mode': '"""linear"""', 'align_corners': '(True)'}), "(input=contents, size=interpolation_Size,\n mode='linear', align_corners=True)\n", (5062, 5142), False, 'import torch\n'), ((5990, 6017), 'torch.FloatTensor', 'torch.FloatTensor', (['contents'], {}), '(contents)\n', (6007, 6017), False, 'import torch\n'), ((6070, 6103), 'torch.FloatTensor', 'torch.FloatTensor', (['content_Styles'], {}), '(content_Styles)\n', (6087, 6103), False, 'import torch\n'), ((6164, 6196), 'torch.FloatTensor', 'torch.FloatTensor', (['target_Styles'], {}), '(target_Styles)\n', (6181, 6196), False, 'import torch\n'), ((6251, 6277), 'torch.FloatTensor', 'torch.FloatTensor', (['pitches'], {}), '(pitches)\n', (6268, 6277), False, 'import torch\n'), ((7944, 7972), 'numpy.stack', 'np.stack', (['pitch_List'], {'axis': '(0)'}), '(pitch_List, axis=0)\n', (7952, 7972), True, 'import numpy as np\n'), ((10537, 10552), 'time.sleep', 'time.sleep', (['(2.0)'], {}), '(2.0)\n', (10547, 10552), False, 'import time\n'), ((7282, 7323), 'numpy.random.randint', 'np.random.randint', (['(0)', '(mel.shape[0] - size)'], {}), '(0, mel.shape[0] - size)\n', (7299, 7323), True, 'import numpy as np\n'), ((8384, 8436), 'numpy.random.randint', 'np.random.randint', (['(0)', '(mel.shape[0] - required_Length)'], {}), '(0, mel.shape[0] - required_Length)\n', (8401, 8436), True, 'import numpy as np\n'), ((8948, 8965), 'numpy.vstack', 'np.vstack', (['styles'], {}), '(styles)\n', (8957, 8965), True, 'import numpy as np\n'), ((1164, 1234), 'os.path.join', 'os.path.join', (["hp_Dict['Train']['Train_Pattern']['Path']", 'dataset', 'file'], {}), "(hp_Dict['Train']['Train_Pattern']['Path'], dataset, file)\n", (1176, 1234), False, 'import yaml, pickle, os, math\n'), ((2268, 2337), 'os.path.join', 'os.path.join', (["hp_Dict['Train']['Eval_Pattern']['Path']", 'dataset', 'file'], {}), "(hp_Dict['Train']['Eval_Pattern']['Path'], dataset, file)\n", (2280, 2337), False, 'import yaml, pickle, os, math\n'), ((3810, 3963), 'numpy.random.uniform', 'np.random.uniform', ([], {'low': "hp_Dict['Train']['Train_Pattern']['Energy_Variance']['Min']", 'high': "hp_Dict['Train']['Train_Pattern']['Energy_Variance']['Max']"}), "(low=hp_Dict['Train']['Train_Pattern']['Energy_Variance'][\n 'Min'], high=hp_Dict['Train']['Train_Pattern']['Energy_Variance']['Max'])\n", (3827, 3963), True, 'import numpy as np\n'), ((4873, 4942), 'numpy.ceil', 'np.ceil', (["(interpolation_Size / hp_Dict['Content_Encoder']['Frequency'])"], {}), "(interpolation_Size / hp_Dict['Content_Encoder']['Frequency'])\n", (4880, 4942), True, 'import numpy as np\n'), ((6543, 6604), 'numpy.ceil', 'np.ceil', (["(max_Length / hp_Dict['Content_Encoder']['Frequency'])"], {}), "(max_Length / hp_Dict['Content_Encoder']['Frequency'])\n", (6550, 6604), True, 'import numpy as np\n'), ((6762, 6870), 'numpy.pad', 'np.pad', (['mel', '[(0, max_Length - mel.shape[0]), (0, 0)]'], {'constant_values': "(-hp_Dict['Sound']['Max_Abs_Mel'])"}), "(mel, [(0, max_Length - mel.shape[0]), (0, 0)], constant_values=-\n hp_Dict['Sound']['Max_Abs_Mel'])\n", (6768, 6870), True, 'import numpy as np\n'), ((6960, 7028), 'numpy.pad', 'np.pad', (['pitch', '(0, max_Length - pitch.shape[0])'], {'constant_values': '(0.0)'}), '(pitch, (0, max_Length - pitch.shape[0]), constant_values=0.0)\n', (6966, 7028), True, 'import numpy as np\n'), ((7896, 7922), 'numpy.stack', 'np.stack', (['mel_List'], {'axis': '(0)'}), '(mel_List, axis=0)\n', (7904, 7922), True, 'import numpy as np\n'), ((445, 557), 'os.path.join', 'os.path.join', (["hp_Dict['Train']['Train_Pattern']['Path']", "hp_Dict['Train']['Train_Pattern']['Metadata_File']"], {}), "(hp_Dict['Train']['Train_Pattern']['Path'], hp_Dict['Train'][\n 'Train_Pattern']['Metadata_File'])\n", (457, 557), False, 'import yaml, pickle, os, math\n'), ((1723, 1833), 'os.path.join', 'os.path.join', (["hp_Dict['Train']['Eval_Pattern']['Path']", "hp_Dict['Train']['Eval_Pattern']['Metadata_File']"], {}), "(hp_Dict['Train']['Eval_Pattern']['Path'], hp_Dict['Train'][\n 'Eval_Pattern']['Metadata_File'])\n", (1735, 1833), False, 'import yaml, pickle, os, math\n'), ((7712, 7729), 'numpy.floor', 'np.floor', (['(pad / 2)'], {}), '(pad / 2)\n', (7720, 7729), True, 'import numpy as np\n'), ((7736, 7752), 'numpy.ceil', 'np.ceil', (['(pad / 2)'], {}), '(pad / 2)\n', (7743, 7752), True, 'import numpy as np\n'), ((7537, 7554), 'numpy.floor', 'np.floor', (['(pad / 2)'], {}), '(pad / 2)\n', (7545, 7554), True, 'import numpy as np\n'), ((7561, 7577), 'numpy.ceil', 'np.ceil', (['(pad / 2)'], {}), '(pad / 2)\n', (7568, 7577), True, 'import numpy as np\n'), ((8630, 8643), 'numpy.floor', 'np.floor', (['pad'], {}), '(pad)\n', (8638, 8643), True, 'import numpy as np\n'), ((8650, 8662), 'numpy.ceil', 'np.ceil', (['pad'], {}), '(pad)\n', (8657, 8662), True, 'import numpy as np\n')]
""" July 2021 <NAME>, <EMAIL> <NAME>, <EMAIL> 3D Shape Analysis Lab Department of Computer Science and Engineering Ulsan National Institute of Science and Technology """ import numpy as np from joblib import Parallel, delayed from scipy.spatial import cKDTree as KDTree from scipy.sparse import coo_matrix class TriangleSearch: def __init__(self, v, f): """ Fast closest triangle search. This module is particularly useful for spherical tessellation. The module only works on spherical tessellation. Parameters __________ v : 2D array, shape = [n_vertex, 3] 3D coordinates of the unit sphere. f : 2D array, shape = [n_face, 3] Triangles of the unit sphere. """ self.v = v self.f = f centroid = self.v[self.f[:, 0], :] + self.v[self.f[:, 1], :] + self.v[self.f[:, 2], :] centroid /= np.linalg.norm(centroid, axis=1, keepdims=True) self.MD = KDTree(centroid) a = self.v[self.f[:, 0], :] b = self.v[self.f[:, 1], :] c = self.v[self.f[:, 2], :] normal = np.cross(a - b, a - c) # Exception: when normal == [0, 0, 0] zero_normal = (normal == 0).all(axis=1) normal[zero_normal] = a[zero_normal] normal /= np.linalg.norm(normal, axis=1, keepdims=True) self.face_normal = normal self.r = np.multiply(self.v[self.f[:, 0], :], self.face_normal).sum(1) def barycentric(self, v, f, p): """ Barycentric coefficients of p inside triangles f. """ a = v[f[:, 0], :] b = v[f[:, 1], :] c = v[f[:, 2], :] n = np.cross(b - a, c - a) abc = np.linalg.norm(n, axis=1, keepdims=True) n /= abc u = (np.cross(b - p, c - p) * n).sum(-1, keepdims=True) / abc v = (np.cross(c - p, a - p) * n).sum(-1, keepdims=True) / abc w = 1 - u - v return np.hstack([u, v, w]) def query(self, query_v, tol=-1e-6): """ Find triangle that contains query_v and then compute their barycentric coefficients. """ q = query_v / np.linalg.norm(query_v, axis=1, keepdims=True) q_num = q.shape[0] qID = np.arange(q_num) which_tri = np.zeros(q_num, dtype=np.int) bary_list = np.zeros((q_num, 3)) k = 1 while qID.size > 0: query = q[qID, :] _, kk = self.MD.query(query, k) if k > 1: kk = kk[:, k - 1] # k-th closest triangle q_proj = np.multiply(query.transpose(1, 0), self.r[kk] / np.multiply(query, self.face_normal[kk]).sum(1)) q_proj = q_proj.transpose(1, 0) b = self.barycentric(self.v, self.f[kk], q_proj) valid = (b >= tol).sum(1) == 3 which_tri[qID[valid]] = kk[valid] bary_list[qID[valid]] = b[valid] qID = np.delete(qID, valid) k += 1 return which_tri, bary_list def vertex_area(v, f): """ Vertex-wise area. The area is approximated by a third of neighborhood triangle areas. Parameters __________ v : 2D array, shape = [n_vertex, 3] 3D coordinates of the unit sphere. f : 2D array, shape = [n_face, 3] Triangles of the unit sphere. Returns _______ area : 1D array, shape = [n_vertex] Area per vertex. """ u = v / np.linalg.norm(v, axis=1, keepdims=True) a = u[f[:, 0], :] b = u[f[:, 1], :] c = u[f[:, 2], :] normal = np.cross(a - b, a - c) area = np.linalg.norm(normal, axis=1, keepdims=True) area = coo_matrix( (np.repeat(area, 3), (np.repeat(np.arange(f.shape[0]), 3), f.flatten())), shape=(f.shape[0], v.shape[0]) ) area = np.squeeze(np.asarray(coo_matrix.sum(area, axis=0))) / 6 return area def legendre(n, x, tol, tstart): """ The Schmidt semi-normalized associated polynomials. Parameters __________ n : int degree of spherical harmonics. x : 1D array, shape = [n_vertex] List of cosine values. tol : float sqrt(tiny). tstart: float eps. Returns _______ Y : 2D array, shape = [n + 1, n_vertex] Schmidt semi-normalized associated polynomials. Notes _____ MATLAB: https://www.mathworks.com/help/matlab/ref/legendre.html """ Y = np.zeros(shape=(n + 1, len(x))) if n == 0: Y[0] = 1 elif n == 1: Y[0] = x Y[1] = np.sqrt(1.0 - x * x) else: factor = np.sqrt(1.0 - x * x) rootn = [np.sqrt(i) for i in range(2 * n + 1)] pole = np.where(factor == 0)[0] factor[pole] = 1 twocot = -2 * x / factor sn = np.power(-factor, n) Y[n, :] = np.sqrt(np.prod(1.0 - 1.0 / (2 * np.arange(1, n + 1)))) * sn Y[n - 1, :] = Y[n, :] * twocot * n / rootn[2 * n] for m in range(n - 2, -1, -1): Y[m] = (Y[m + 1] * twocot * (m + 1) - Y[m + 2] * rootn[n + m + 2] * rootn[n - m - 1]) / ( rootn[n + m + 1] * rootn[n - m] ) idx = np.where(np.absolute(sn) < tol)[0] v = 9.2 - np.log(tol) / (n * factor[idx]) w = 1 / np.log(v) m1 = 1 + n * factor[idx] * v * w * (1.0058 + w * (3.819 - w * 12.173)) m1 = np.minimum(n, np.floor(m1)).astype("int") Y[:, idx] = 0 m1_unique = np.unique(m1) for mm1 in m1_unique: k = np.where(m1 == mm1)[0] col = idx[k] Y[mm1 - 1, col[x[col] < 0]] = np.sign((n + 1) % 2 - 0.5) * tstart Y[mm1 - 1, col[x[col] >= 0]] = np.sign(mm1 % 2 - 0.5) * tstart for m in range(mm1 - 2, -1, -1): Y[m, col] = ( Y[m + 1, col] * twocot[col] * (m + 1) - Y[m + 2, col] * rootn[n + m + 2] * rootn[n - m - 1] ) / (rootn[n + m + 1] * rootn[n - m]) sumsq = tol + np.sum(Y[: mm1 - 2, col] * Y[: mm1 - 2, col], axis=0) Y[:mm1, col] /= np.sqrt(2 * sumsq - Y[0, col] * Y[0, col]) Y[1:, pole] = 0 Y[0, pole] = np.power(x[pole], n) Y[1:None] *= rootn[2] Y[1:None:2] *= -1 return Y def spharm_real(x, l, threads=None, lbase=0): """ A set of real spherical harmonic bases using the Schmidt semi-normalized associated polynomials. The spherical harmonics will be generated from lbase to l. Parameters __________ x : 2D array, shape = [n_vertex, 3] Array of 3D coordinates of the unit sphere. l : int Degree of spherical harmonics. lbase : int Base degree of spherical harmonics. threads : int Non-negative number of threads for parallel computing powered by joblib. Returns _______ Y : 2D array, shape = [(l - lbase + 1) ** 2, n_vertex] Real spherical harmonic bases. """ def cart2sph(x): azimuth = np.arctan2(x[:, 1], x[:, 0]) elevation = np.pi / 2 - np.arctan2(x[:, 2], np.sqrt(x[:, 0] ** 2 + x[:, 1] ** 2)) return azimuth, elevation def basis(Y, theta, lfrom, lto, lbase, c, s, tol, tstart): c2 = np.cos(-theta) for l in range(lfrom, lto, 1): center = (l + 1) * (l + 1) - l - 1 - lbase * lbase Y[center : center + l + 1] = legendre(l, c2, tol, tstart) * np.sqrt((2 * l + 1) / (4 * np.pi)) if lfrom == 0: lfrom = 1 for l in range(lfrom, lto, 1): center = (l + 1) * (l + 1) - l - 1 - lbase * lbase Y[center - 1 : center - l - 1 : -1] = Y[center + 1 : center + l + 1] * s[0:l] Y[center + 1 : center + l + 1] *= c[0:l] if lbase < 0: lbase = 0 phi, theta = cart2sph(x) size = (l + 1) * (l + 1) - lbase * lbase Y = np.zeros(shape=(size, len(x))) m = np.arange(1, l + 1) deg = m[:, None] * phi[None, :] c = np.cos(deg) s = np.sin(deg) tol = np.sqrt(np.finfo(x.dtype).tiny) tstart = np.finfo(x.dtype).eps if threads is not None and threads > 1: Parallel(n_jobs=threads, require="sharedmem")( delayed(basis)(Y, theta, n, n + 1, lbase, c, s, tol, tstart) for n in range(lbase, l + 1, 1) ) else: basis(Y, theta, lbase, l + 1, lbase, c, s, tol, tstart) return Y
[ "numpy.absolute", "scipy.sparse.coo_matrix.sum", "numpy.arctan2", "numpy.sum", "numpy.floor", "numpy.sin", "numpy.linalg.norm", "numpy.arange", "scipy.spatial.cKDTree", "numpy.unique", "numpy.multiply", "numpy.power", "numpy.finfo", "numpy.repeat", "numpy.cross", "numpy.hstack", "num...
[((3548, 3570), 'numpy.cross', 'np.cross', (['(a - b)', '(a - c)'], {}), '(a - b, a - c)\n', (3556, 3570), True, 'import numpy as np\n'), ((3582, 3627), 'numpy.linalg.norm', 'np.linalg.norm', (['normal'], {'axis': '(1)', 'keepdims': '(True)'}), '(normal, axis=1, keepdims=True)\n', (3596, 3627), True, 'import numpy as np\n'), ((7837, 7856), 'numpy.arange', 'np.arange', (['(1)', '(l + 1)'], {}), '(1, l + 1)\n', (7846, 7856), True, 'import numpy as np\n'), ((7901, 7912), 'numpy.cos', 'np.cos', (['deg'], {}), '(deg)\n', (7907, 7912), True, 'import numpy as np\n'), ((7921, 7932), 'numpy.sin', 'np.sin', (['deg'], {}), '(deg)\n', (7927, 7932), True, 'import numpy as np\n'), ((914, 961), 'numpy.linalg.norm', 'np.linalg.norm', (['centroid'], {'axis': '(1)', 'keepdims': '(True)'}), '(centroid, axis=1, keepdims=True)\n', (928, 961), True, 'import numpy as np\n'), ((981, 997), 'scipy.spatial.cKDTree', 'KDTree', (['centroid'], {}), '(centroid)\n', (987, 997), True, 'from scipy.spatial import cKDTree as KDTree\n'), ((1124, 1146), 'numpy.cross', 'np.cross', (['(a - b)', '(a - c)'], {}), '(a - b, a - c)\n', (1132, 1146), True, 'import numpy as np\n'), ((1304, 1349), 'numpy.linalg.norm', 'np.linalg.norm', (['normal'], {'axis': '(1)', 'keepdims': '(True)'}), '(normal, axis=1, keepdims=True)\n', (1318, 1349), True, 'import numpy as np\n'), ((1676, 1698), 'numpy.cross', 'np.cross', (['(b - a)', '(c - a)'], {}), '(b - a, c - a)\n', (1684, 1698), True, 'import numpy as np\n'), ((1713, 1753), 'numpy.linalg.norm', 'np.linalg.norm', (['n'], {'axis': '(1)', 'keepdims': '(True)'}), '(n, axis=1, keepdims=True)\n', (1727, 1753), True, 'import numpy as np\n'), ((1949, 1969), 'numpy.hstack', 'np.hstack', (['[u, v, w]'], {}), '([u, v, w])\n', (1958, 1969), True, 'import numpy as np\n'), ((2241, 2257), 'numpy.arange', 'np.arange', (['q_num'], {}), '(q_num)\n', (2250, 2257), True, 'import numpy as np\n'), ((2278, 2307), 'numpy.zeros', 'np.zeros', (['q_num'], {'dtype': 'np.int'}), '(q_num, dtype=np.int)\n', (2286, 2307), True, 'import numpy as np\n'), ((2328, 2348), 'numpy.zeros', 'np.zeros', (['(q_num, 3)'], {}), '((q_num, 3))\n', (2336, 2348), True, 'import numpy as np\n'), ((3427, 3467), 'numpy.linalg.norm', 'np.linalg.norm', (['v'], {'axis': '(1)', 'keepdims': '(True)'}), '(v, axis=1, keepdims=True)\n', (3441, 3467), True, 'import numpy as np\n'), ((6931, 6959), 'numpy.arctan2', 'np.arctan2', (['x[:, 1]', 'x[:, 0]'], {}), '(x[:, 1], x[:, 0])\n', (6941, 6959), True, 'import numpy as np\n'), ((7162, 7176), 'numpy.cos', 'np.cos', (['(-theta)'], {}), '(-theta)\n', (7168, 7176), True, 'import numpy as np\n'), ((7989, 8006), 'numpy.finfo', 'np.finfo', (['x.dtype'], {}), '(x.dtype)\n', (7997, 8006), True, 'import numpy as np\n'), ((2152, 2198), 'numpy.linalg.norm', 'np.linalg.norm', (['query_v'], {'axis': '(1)', 'keepdims': '(True)'}), '(query_v, axis=1, keepdims=True)\n', (2166, 2198), True, 'import numpy as np\n'), ((2924, 2945), 'numpy.delete', 'np.delete', (['qID', 'valid'], {}), '(qID, valid)\n', (2933, 2945), True, 'import numpy as np\n'), ((3660, 3678), 'numpy.repeat', 'np.repeat', (['area', '(3)'], {}), '(area, 3)\n', (3669, 3678), True, 'import numpy as np\n'), ((4516, 4536), 'numpy.sqrt', 'np.sqrt', (['(1.0 - x * x)'], {}), '(1.0 - x * x)\n', (4523, 4536), True, 'import numpy as np\n'), ((4564, 4584), 'numpy.sqrt', 'np.sqrt', (['(1.0 - x * x)'], {}), '(1.0 - x * x)\n', (4571, 4584), True, 'import numpy as np\n'), ((4751, 4771), 'numpy.power', 'np.power', (['(-factor)', 'n'], {}), '(-factor, n)\n', (4759, 4771), True, 'import numpy as np\n'), ((5416, 5429), 'numpy.unique', 'np.unique', (['m1'], {}), '(m1)\n', (5425, 5429), True, 'import numpy as np\n'), ((6116, 6136), 'numpy.power', 'np.power', (['x[pole]', 'n'], {}), '(x[pole], n)\n', (6124, 6136), True, 'import numpy as np\n'), ((7952, 7969), 'numpy.finfo', 'np.finfo', (['x.dtype'], {}), '(x.dtype)\n', (7960, 7969), True, 'import numpy as np\n'), ((8064, 8109), 'joblib.Parallel', 'Parallel', ([], {'n_jobs': 'threads', 'require': '"""sharedmem"""'}), "(n_jobs=threads, require='sharedmem')\n", (8072, 8109), False, 'from joblib import Parallel, delayed\n'), ((1403, 1457), 'numpy.multiply', 'np.multiply', (['self.v[self.f[:, 0], :]', 'self.face_normal'], {}), '(self.v[self.f[:, 0], :], self.face_normal)\n', (1414, 1457), True, 'import numpy as np\n'), ((3803, 3831), 'scipy.sparse.coo_matrix.sum', 'coo_matrix.sum', (['area'], {'axis': '(0)'}), '(area, axis=0)\n', (3817, 3831), False, 'from scipy.sparse import coo_matrix\n'), ((4602, 4612), 'numpy.sqrt', 'np.sqrt', (['i'], {}), '(i)\n', (4609, 4612), True, 'import numpy as np\n'), ((4655, 4676), 'numpy.where', 'np.where', (['(factor == 0)'], {}), '(factor == 0)\n', (4663, 4676), True, 'import numpy as np\n'), ((5229, 5238), 'numpy.log', 'np.log', (['v'], {}), '(v)\n', (5235, 5238), True, 'import numpy as np\n'), ((6027, 6069), 'numpy.sqrt', 'np.sqrt', (['(2 * sumsq - Y[0, col] * Y[0, col])'], {}), '(2 * sumsq - Y[0, col] * Y[0, col])\n', (6034, 6069), True, 'import numpy as np\n'), ((7012, 7048), 'numpy.sqrt', 'np.sqrt', (['(x[:, 0] ** 2 + x[:, 1] ** 2)'], {}), '(x[:, 0] ** 2 + x[:, 1] ** 2)\n', (7019, 7048), True, 'import numpy as np\n'), ((7351, 7385), 'numpy.sqrt', 'np.sqrt', (['((2 * l + 1) / (4 * np.pi))'], {}), '((2 * l + 1) / (4 * np.pi))\n', (7358, 7385), True, 'import numpy as np\n'), ((3691, 3712), 'numpy.arange', 'np.arange', (['f.shape[0]'], {}), '(f.shape[0])\n', (3700, 3712), True, 'import numpy as np\n'), ((5181, 5192), 'numpy.log', 'np.log', (['tol'], {}), '(tol)\n', (5187, 5192), True, 'import numpy as np\n'), ((5476, 5495), 'numpy.where', 'np.where', (['(m1 == mm1)'], {}), '(m1 == mm1)\n', (5484, 5495), True, 'import numpy as np\n'), ((5567, 5593), 'numpy.sign', 'np.sign', (['((n + 1) % 2 - 0.5)'], {}), '((n + 1) % 2 - 0.5)\n', (5574, 5593), True, 'import numpy as np\n'), ((5646, 5668), 'numpy.sign', 'np.sign', (['(mm1 % 2 - 0.5)'], {}), '(mm1 % 2 - 0.5)\n', (5653, 5668), True, 'import numpy as np\n'), ((5945, 5996), 'numpy.sum', 'np.sum', (['(Y[:mm1 - 2, col] * Y[:mm1 - 2, col])'], {'axis': '(0)'}), '(Y[:mm1 - 2, col] * Y[:mm1 - 2, col], axis=0)\n', (5951, 5996), True, 'import numpy as np\n'), ((8123, 8137), 'joblib.delayed', 'delayed', (['basis'], {}), '(basis)\n', (8130, 8137), False, 'from joblib import Parallel, delayed\n'), ((1784, 1806), 'numpy.cross', 'np.cross', (['(b - p)', '(c - p)'], {}), '(b - p, c - p)\n', (1792, 1806), True, 'import numpy as np\n'), ((1854, 1876), 'numpy.cross', 'np.cross', (['(c - p)', '(a - p)'], {}), '(c - p, a - p)\n', (1862, 1876), True, 'import numpy as np\n'), ((5137, 5152), 'numpy.absolute', 'np.absolute', (['sn'], {}), '(sn)\n', (5148, 5152), True, 'import numpy as np\n'), ((5345, 5357), 'numpy.floor', 'np.floor', (['m1'], {}), '(m1)\n', (5353, 5357), True, 'import numpy as np\n'), ((2618, 2658), 'numpy.multiply', 'np.multiply', (['query', 'self.face_normal[kk]'], {}), '(query, self.face_normal[kk])\n', (2629, 2658), True, 'import numpy as np\n'), ((4824, 4843), 'numpy.arange', 'np.arange', (['(1)', '(n + 1)'], {}), '(1, n + 1)\n', (4833, 4843), True, 'import numpy as np\n')]
#!/usr/bin/env python # -*- coding: utf-8 -*- # by TR """ stack and plot rfs by azimuth """ from sito import read, imaging from glob import glob import matplotlib.pyplot as plt from matplotlib import colors import numpy as np from matplotlib.colorbar import ColorbarBase path = '/home/richter/Results/IPOC/receiver/2012_mag5.5/' azi_path = path + '/azi_stack/' plotdir = azi_path + 'plots/' def getFig(num=0, ratio=1.5, margin=None, **kwargs): axes = [1. - 0.1 * num] + [0.1] * num if margin == None: margin = [1.7, 1.3, 1.1, 0.3] #left, rigth, bottom, top fig = imaging.getFigure(axes, width=15., margin=margin, ratio=ratio, fontsize=12, labelsize='small', **kwargs) return fig def cosmetic(station, fig): bins = np.arange(18) * 20 + 10 if station in ('PB01'): fig.axes[0].set_yticks(bins) fig.axes[0].set_yticks((), minor=True) fig.axes[0].set_yticklabels([str(bi) * ((i + 1) % 2) for i, bi in enumerate(bins)]) fig.axes[0].set_ylim((-20, 380)) def plot(station='*'): start = -5 end = 22 show = False for file_ in glob(azi_path + station + '_azi_stack.QHD'): ms = read(file_) station = ms[0].stats.station ratio = (len(ms) * 0.5 + 1.4 + 0.4 * 2.54) / 15 ratio = min(ratio, 2.) fig = getFig(ratio=ratio) alpha = None num_tr = np.sum(np.array(ms.getHI('count'))) if num_tr >= 100: alpha = ['count', 20, 0, 1., 0.] elif num_tr >= 50: alpha = ['count', 10, 0, 1., 0.] else: alpha = ['count', 5, 0, 1., 0.] plot = ms.plotRF(start, end, yaxis='azi', ylabel=u'azi (°)', show=show, fig=fig, scale=360 / len(ms), plotinfo=('sum',), plotinfowhere=('top',), alpha=alpha) if alpha is not None: #http://matplotlib.sourceforge.net/examples/api/colorbar_only.html ax2 = plot.fig.add_axes([0.94, 0.2, 0.01, 0.6]) norm = colors.Normalize(vmin=0, vmax=alpha[1]) ColorbarBase(ax2, cmap='Greys', norm=norm, extend='max') cosmetic(station, plot.fig) plot.fig.savefig(plotdir + 'rf_azistack_%s_Q.pdf' % station) plt.close(plot.fig) def calculate(station='*'): for file_ in glob(path + station + '_mout.QHD'): ms = read(file_).select(component='Q', expr='not st.mark') station = ms[0].stats.station if len(ms) >= 100: bins = np.arange(19) * 20 elif len(ms) >= 50: bins = np.arange(13) * 30 else: bins = np.arange(7) * 60 ms = ms.getBinnedStream(bins, header='azi') ms.write(azi_path + '%s_azi_stack' % station, 'Q') calculate() plot()
[ "matplotlib.colors.Normalize", "matplotlib.pyplot.close", "sito.imaging.getFigure", "numpy.arange", "glob.glob", "matplotlib.colorbar.ColorbarBase", "sito.read" ]
[((586, 695), 'sito.imaging.getFigure', 'imaging.getFigure', (['axes'], {'width': '(15.0)', 'margin': 'margin', 'ratio': 'ratio', 'fontsize': '(12)', 'labelsize': '"""small"""'}), "(axes, width=15.0, margin=margin, ratio=ratio, fontsize=12,\n labelsize='small', **kwargs)\n", (603, 695), False, 'from sito import read, imaging\n'), ((1163, 1206), 'glob.glob', 'glob', (["(azi_path + station + '_azi_stack.QHD')"], {}), "(azi_path + station + '_azi_stack.QHD')\n", (1167, 1206), False, 'from glob import glob\n'), ((2359, 2393), 'glob.glob', 'glob', (["(path + station + '_mout.QHD')"], {}), "(path + station + '_mout.QHD')\n", (2363, 2393), False, 'from glob import glob\n'), ((1221, 1232), 'sito.read', 'read', (['file_'], {}), '(file_)\n', (1225, 1232), False, 'from sito import read, imaging\n'), ((2293, 2312), 'matplotlib.pyplot.close', 'plt.close', (['plot.fig'], {}), '(plot.fig)\n', (2302, 2312), True, 'import matplotlib.pyplot as plt\n'), ((775, 788), 'numpy.arange', 'np.arange', (['(18)'], {}), '(18)\n', (784, 788), True, 'import numpy as np\n'), ((2071, 2110), 'matplotlib.colors.Normalize', 'colors.Normalize', ([], {'vmin': '(0)', 'vmax': 'alpha[1]'}), '(vmin=0, vmax=alpha[1])\n', (2087, 2110), False, 'from matplotlib import colors\n'), ((2123, 2179), 'matplotlib.colorbar.ColorbarBase', 'ColorbarBase', (['ax2'], {'cmap': '"""Greys"""', 'norm': 'norm', 'extend': '"""max"""'}), "(ax2, cmap='Greys', norm=norm, extend='max')\n", (2135, 2179), False, 'from matplotlib.colorbar import ColorbarBase\n'), ((2408, 2419), 'sito.read', 'read', (['file_'], {}), '(file_)\n', (2412, 2419), False, 'from sito import read, imaging\n'), ((2546, 2559), 'numpy.arange', 'np.arange', (['(19)'], {}), '(19)\n', (2555, 2559), True, 'import numpy as np\n'), ((2612, 2625), 'numpy.arange', 'np.arange', (['(13)'], {}), '(13)\n', (2621, 2625), True, 'import numpy as np\n'), ((2664, 2676), 'numpy.arange', 'np.arange', (['(7)'], {}), '(7)\n', (2673, 2676), True, 'import numpy as np\n')]
"""ODIN data live view adapter. This module implements an odin-control adapter capable of rendering odin-data live view images to users. Created on 8th October 2018 :author: <NAME>, STFC Application Engineering Gruop """ import logging import re from collections import OrderedDict import numpy as np import cv2 from tornado.escape import json_decode from odin_data.ipc_tornado_channel import IpcTornadoChannel from odin_data.ipc_channel import IpcChannelException from odin.adapters.adapter import ApiAdapter, ApiAdapterResponse, response_types from odin.adapters.parameter_tree import ParameterTree, ParameterTreeError ENDPOINTS_CONFIG_NAME = 'live_view_endpoints' COLORMAP_CONFIG_NAME = 'default_colormap' DEFAULT_ENDPOINT = 'tcp://127.0.0.1:5020' DEFAULT_COLORMAP = "Jet" class LiveViewAdapter(ApiAdapter): """Live view adapter class. This class implements the live view adapter for odin-control. """ def __init__(self, **kwargs): """ Initialise the adapter. Creates a LiveViewer Object that handles the major logic of the adapter. :param kwargs: Key Word arguments given from the configuration file, which is copied into the options dictionary. """ logging.debug("Live View Adapter init called") super(LiveViewAdapter, self).__init__(**kwargs) if self.options.get(ENDPOINTS_CONFIG_NAME, False): endpoints = [x.strip() for x in self.options.get(ENDPOINTS_CONFIG_NAME, "").split(',')] else: logging.debug("Setting default endpoint of '%s'", DEFAULT_ENDPOINT) endpoints = [DEFAULT_ENDPOINT] if self.options.get(COLORMAP_CONFIG_NAME, False): default_colormap = self.options.get(COLORMAP_CONFIG_NAME, "") else: default_colormap = "Jet" self.live_viewer = LiveViewer(endpoints, default_colormap) @response_types('application/json', 'image/*', default='application/json') def get(self, path, request): """ Handle a HTTP GET request from a client, passing this to the Live Viewer object. :param path: The path to the resource requested by the GET request :param request: Additional request parameters :return: The requested resource, or an error message and code if the request was invalid. """ try: response, content_type, status = self.live_viewer.get(path, request) except ParameterTreeError as param_error: response = {'response': 'LiveViewAdapter GET error: {}'.format(param_error)} content_type = 'application/json' status = 400 return ApiAdapterResponse(response, content_type=content_type, status_code=status) @response_types('application/json', default='application/json') def put(self, path, request): """ Handle a HTTP PUT request from a client, passing it to the Live Viewer Object. :param path: path to the resource :param request: request object containing data to PUT to the resource :return: the requested resource after changing, or an error message and code if invalid """ logging.debug("REQUEST: %s", request.body) try: data = json_decode(request.body) self.live_viewer.set(path, data) response, content_type, status = self.live_viewer.get(path) except ParameterTreeError as param_error: response = {'response': 'LiveViewAdapter PUT error: {}'.format(param_error)} content_type = 'application/json' status = 400 return ApiAdapterResponse(response, content_type=content_type, status_code=status) def cleanup(self): """Clean up the adapter on shutdown. Calls the Live View object's cleanup method.""" self.live_viewer.cleanup() class LiveViewer(object): """ Live viewer main class. This class handles the major logic of the adapter, including generation of the images from data. """ def __init__(self, endpoints, default_colormap): """ Initialise the LiveViewer object. This method creates the IPC channel used to receive images from odin-data and assigns a callback method that is called when data arrives at the channel. It also initialises the Parameter tree used for HTTP GET and SET requests. :param endpoints: the endpoint address that the IPC channel subscribes to. """ logging.debug("Initialising LiveViewer") self.img_data = np.arange(0, 1024, 1).reshape(32, 32) self.clip_min = None self.clip_max = None self.header = {} self.endpoints = endpoints self.ipc_channels = [] for endpoint in self.endpoints: try: tmp_channel = SubSocket(self, endpoint) self.ipc_channels.append(tmp_channel) logging.debug("Subscribed to endpoint: %s", tmp_channel.endpoint) except IpcChannelException as chan_error: logging.warning("Unable to subscribe to %s: %s", endpoint, chan_error) logging.debug("Connected to %d endpoints", len(self.ipc_channels)) if not self.ipc_channels: logging.warning( "Warning: No subscriptions made. Check the configuration file for valid endpoints") # Define a list of available cv2 colormaps self.cv2_colormaps = { "Autumn": cv2.COLORMAP_AUTUMN, "Bone": cv2.COLORMAP_BONE, "Jet": cv2.COLORMAP_JET, "Winter": cv2.COLORMAP_WINTER, "Rainbow": cv2.COLORMAP_RAINBOW, "Ocean": cv2.COLORMAP_OCEAN, "Summer": cv2.COLORMAP_SUMMER, "Spring": cv2.COLORMAP_SPRING, "Cool": cv2.COLORMAP_COOL, "HSV": cv2.COLORMAP_HSV, "Pink": cv2.COLORMAP_PINK, "Hot": cv2.COLORMAP_HOT, "Parula": cv2.COLORMAP_PARULA } # Build a sorted list of colormap options mapping readable name to lowercase option self.colormap_options = OrderedDict() for colormap_name in sorted(self.cv2_colormaps.keys()): self.colormap_options[colormap_name.lower()] = colormap_name # Set the selected colormap to the default if default_colormap.lower() in self.colormap_options: self.selected_colormap = default_colormap.lower() else: self.selected_colormap = "jet" self.rendered_image = self.render_image() self.param_tree = ParameterTree({ "name": "Live View Adapter", "endpoints": (self.get_channel_endpoints, None), "frame": (lambda: self.header, None), "colormap_options": self.colormap_options, "colormap_selected": (self.get_selected_colormap, self.set_selected_colormap), "data_min_max": (lambda: [int(self.img_data.min()), int(self.img_data.max())], None), "frame_counts": (self.get_channel_counts, self.set_channel_counts), "clip_range": (lambda: [self.clip_min, self.clip_max], self.set_clip) }) def get(self, path, _request=None): """ Handle a HTTP get request. Checks if the request is for the image or another resource, and responds accordingly. :param path: the URI path to the resource requested :param request: Additional request parameters. :return: the requested resource,or an error message and code, if the request is invalid. """ path_elems = re.split('[/?#]', path) if path_elems[0] == 'image': if self.img_data is not None: response = self.rendered_image content_type = 'image/png' status = 200 else: response = {"response": "LiveViewAdapter: No Image Available"} content_type = 'application/json' status = 400 else: response = self.param_tree.get(path) content_type = 'application/json' status = 200 return response, content_type, status def set(self, path, data): """ Handle a HTTP PUT i.e. set request. :param path: the URI path to the resource :param data: the data to PUT to the resource """ self.param_tree.set(path, data) def create_image_from_socket(self, msg): """ Create an image from data received on the socket. This callback function is called when data is ready on the IPC channel. It creates the image data array from the raw data sent by the Odin Data Plugin, reshaping it to a multi dimensional array matching the image dimensions. :param msg: a multipart message containing the image header, and raw image data. """ # Message should be a list from multi part message. # First part will be the json header from the live view, second part is the raw image data header = json_decode(msg[0]) # json_decode returns dictionary encoded in unicode. Convert to normal strings header = self.convert_to_string(header) logging.debug("Got image with header: %s", header) # create a np array of the image data, of type specified in the frame header img_data = np.fromstring(msg[1], dtype=np.dtype(header['dtype'])) self.img_data = img_data.reshape([int(header["shape"][0]), int(header["shape"][1])]) self.header = header self.rendered_image = self.render_image( self.selected_colormap, self.clip_min, self.clip_max) def render_image(self, colormap=None, clip_min=None, clip_max=None): """ Render an image from the image data, applying a colormap to the greyscale data. :param colormap: Desired image colormap. if None, uses the default colormap. :param clip_min: The minimum pixel value desired. If a pixel is lower than this value, it is set to this value. :param clip_max: The maximum pixel value desired. If a pixel is higher than this value, it is set to this value. :return: The rendered image binary data, encoded into a string so it can be returned by a GET request. """ if colormap is None: colormap = self.selected_colormap if clip_min is not None and clip_max is not None: if clip_min > clip_max: clip_min = None clip_max = None logging.warning("Clip minimum cannot be more than clip maximum") if clip_min is not None or clip_max is not None: img_clipped = np.clip(self.img_data, clip_min, clip_max) # clip image else: img_clipped = self.img_data # Scale to 0-255 for colormap img_scaled = self.scale_array(img_clipped, 0, 255).astype(dtype=np.uint8) # Apply colormap cv2_colormap = self.cv2_colormaps[self.colormap_options[colormap]] img_colormapped = cv2.applyColorMap(img_scaled, cv2_colormap) # Most time consuming step, depending on image size and the type of image img_encode = cv2.imencode( '.png', img_colormapped, params=[cv2.IMWRITE_PNG_COMPRESSION, 0])[1] return img_encode.tostring() @staticmethod def scale_array(src, tmin, tmax): """ Set the range of image data. The ratio between pixels should remain the same, but the total range should be rescaled to fit the desired minimum and maximum :param src: the source array to rescale :param tmin: the target minimum :param tmax: the target maximum :return: an array of the same dimensions as the source, but with the data rescaled. """ smin, smax = src.min(), src.max() downscaled = (src.astype(float) - smin) / (smax - smin) rescaled = (downscaled * (tmax - tmin) + tmin).astype(src.dtype) return rescaled def convert_to_string(self, obj): """ Convert all unicode parts of a dictionary or list to standard strings. This method may not handle special characters well! :param obj: the dictionary, list, or unicode string :return: the same data type as obj, but with unicode strings converted to python strings. """ if isinstance(obj, dict): return {self.convert_to_string(key): self.convert_to_string(value) for key, value in obj.items()} elif isinstance(obj, list): return [self.convert_to_string(element) for element in obj] elif isinstance(obj, unicode): return obj.encode('utf-8') return obj def cleanup(self): """Close the IPC channels ready for shutdown.""" for channel in self.ipc_channels: channel.cleanup() def get_selected_colormap(self): """ Get the default colormap for the adapter. :return: the default colormap for the adapter """ return self.selected_colormap def set_selected_colormap(self, colormap): """ Set the selected colormap for the adapter. :param colormap: colormap to select """ if colormap.lower() in self.colormap_options: self.selected_colormap = colormap.lower() def set_clip(self, clip_array): """ Set the image clipping, i.e. max and min values to render. :param clip_array: array of min and max values to clip """ if (clip_array[0] is None) or isinstance(clip_array[0], int): self.clip_min = clip_array[0] if (clip_array[1] is None) or isinstance(clip_array[1], int): self.clip_max = clip_array[1] def get_channel_endpoints(self): """ Get the list of endpoints this adapter is subscribed to. :return: a list of endpoints """ endpoints = [] for channel in self.ipc_channels: endpoints.append(channel.endpoint) return endpoints def get_channel_counts(self): """ Get a dict of the endpoints and the count of how many frames came from that endpoint. :return: A dict, with the endpoint as a key, and the number of images from that endpoint as the value """ counts = {} for channel in self.ipc_channels: counts[channel.endpoint] = channel.frame_count return counts def set_channel_counts(self, data): """ Set the channel frame counts. This method is used to reset the channel frame counts to known values. :param data: channel frame count data to set """ data = self.convert_to_string(data) logging.debug("Data Type: %s", type(data).__name__) for channel in self.ipc_channels: if channel.endpoint in data: logging.debug("Endpoint %s in request", channel.endpoint) channel.frame_count = data[channel.endpoint] class SubSocket(object): """ Subscriber Socket class. This class implements an IPC channel subcriber socker and sets up a callback function for receiving data from that socket that counts how many images it receives during its lifetime. """ def __init__(self, parent, endpoint): """ Initialise IPC channel as a subscriber, and register the callback. :param parent: the class that created this object, a LiveViewer, given so that this object can reference the method in the parent :param endpoint: the URI address of the socket to subscribe to """ self.parent = parent self.endpoint = endpoint self.frame_count = 0 self.channel = IpcTornadoChannel(IpcTornadoChannel.CHANNEL_TYPE_SUB, endpoint=endpoint) self.channel.subscribe() self.channel.connect() # register the get_image method to be called when the ZMQ socket receives a message self.channel.register_callback(self.callback) def callback(self, msg): """ Handle incoming data on the socket. This callback method is called whenever data arrives on the IPC channel socket. Increments the counter, then passes the message on to the image renderer of the parent. :param msg: the multipart message from the IPC channel """ self.frame_count += 1 self.parent.create_image_from_socket(msg) def cleanup(self): """Cleanup channel when the server is closed. Closes the IPC channel socket correctly.""" self.channel.close()
[ "logging.debug", "re.split", "logging.warning", "numpy.dtype", "tornado.escape.json_decode", "numpy.clip", "cv2.imencode", "numpy.arange", "cv2.applyColorMap", "odin.adapters.adapter.ApiAdapterResponse", "collections.OrderedDict", "odin_data.ipc_tornado_channel.IpcTornadoChannel", "odin.adap...
[((1897, 1970), 'odin.adapters.adapter.response_types', 'response_types', (['"""application/json"""', '"""image/*"""'], {'default': '"""application/json"""'}), "('application/json', 'image/*', default='application/json')\n", (1911, 1970), False, 'from odin.adapters.adapter import ApiAdapter, ApiAdapterResponse, response_types\n'), ((2748, 2810), 'odin.adapters.adapter.response_types', 'response_types', (['"""application/json"""'], {'default': '"""application/json"""'}), "('application/json', default='application/json')\n", (2762, 2810), False, 'from odin.adapters.adapter import ApiAdapter, ApiAdapterResponse, response_types\n'), ((1239, 1285), 'logging.debug', 'logging.debug', (['"""Live View Adapter init called"""'], {}), "('Live View Adapter init called')\n", (1252, 1285), False, 'import logging\n'), ((2666, 2741), 'odin.adapters.adapter.ApiAdapterResponse', 'ApiAdapterResponse', (['response'], {'content_type': 'content_type', 'status_code': 'status'}), '(response, content_type=content_type, status_code=status)\n', (2684, 2741), False, 'from odin.adapters.adapter import ApiAdapter, ApiAdapterResponse, response_types\n'), ((3181, 3223), 'logging.debug', 'logging.debug', (['"""REQUEST: %s"""', 'request.body'], {}), "('REQUEST: %s', request.body)\n", (3194, 3223), False, 'import logging\n'), ((3626, 3701), 'odin.adapters.adapter.ApiAdapterResponse', 'ApiAdapterResponse', (['response'], {'content_type': 'content_type', 'status_code': 'status'}), '(response, content_type=content_type, status_code=status)\n', (3644, 3701), False, 'from odin.adapters.adapter import ApiAdapter, ApiAdapterResponse, response_types\n'), ((4492, 4532), 'logging.debug', 'logging.debug', (['"""Initialising LiveViewer"""'], {}), "('Initialising LiveViewer')\n", (4505, 4532), False, 'import logging\n'), ((6121, 6134), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (6132, 6134), False, 'from collections import OrderedDict\n'), ((7596, 7619), 're.split', 're.split', (['"""[/?#]"""', 'path'], {}), "('[/?#]', path)\n", (7604, 7619), False, 'import re\n'), ((9063, 9082), 'tornado.escape.json_decode', 'json_decode', (['msg[0]'], {}), '(msg[0])\n', (9074, 9082), False, 'from tornado.escape import json_decode\n'), ((9227, 9277), 'logging.debug', 'logging.debug', (['"""Got image with header: %s"""', 'header'], {}), "('Got image with header: %s', header)\n", (9240, 9277), False, 'import logging\n'), ((11084, 11127), 'cv2.applyColorMap', 'cv2.applyColorMap', (['img_scaled', 'cv2_colormap'], {}), '(img_scaled, cv2_colormap)\n', (11101, 11127), False, 'import cv2\n'), ((15848, 15920), 'odin_data.ipc_tornado_channel.IpcTornadoChannel', 'IpcTornadoChannel', (['IpcTornadoChannel.CHANNEL_TYPE_SUB'], {'endpoint': 'endpoint'}), '(IpcTornadoChannel.CHANNEL_TYPE_SUB, endpoint=endpoint)\n', (15865, 15920), False, 'from odin_data.ipc_tornado_channel import IpcTornadoChannel\n'), ((1528, 1595), 'logging.debug', 'logging.debug', (['"""Setting default endpoint of \'%s\'"""', 'DEFAULT_ENDPOINT'], {}), '("Setting default endpoint of \'%s\'", DEFAULT_ENDPOINT)\n', (1541, 1595), False, 'import logging\n'), ((3256, 3281), 'tornado.escape.json_decode', 'json_decode', (['request.body'], {}), '(request.body)\n', (3267, 3281), False, 'from tornado.escape import json_decode\n'), ((5258, 5367), 'logging.warning', 'logging.warning', (['"""Warning: No subscriptions made. Check the configuration file for valid endpoints"""'], {}), "(\n 'Warning: No subscriptions made. Check the configuration file for valid endpoints'\n )\n", (5273, 5367), False, 'import logging\n'), ((10724, 10766), 'numpy.clip', 'np.clip', (['self.img_data', 'clip_min', 'clip_max'], {}), '(self.img_data, clip_min, clip_max)\n', (10731, 10766), True, 'import numpy as np\n'), ((11232, 11310), 'cv2.imencode', 'cv2.imencode', (['""".png"""', 'img_colormapped'], {'params': '[cv2.IMWRITE_PNG_COMPRESSION, 0]'}), "('.png', img_colormapped, params=[cv2.IMWRITE_PNG_COMPRESSION, 0])\n", (11244, 11310), False, 'import cv2\n'), ((4558, 4579), 'numpy.arange', 'np.arange', (['(0)', '(1024)', '(1)'], {}), '(0, 1024, 1)\n', (4567, 4579), True, 'import numpy as np\n'), ((4928, 4993), 'logging.debug', 'logging.debug', (['"""Subscribed to endpoint: %s"""', 'tmp_channel.endpoint'], {}), "('Subscribed to endpoint: %s', tmp_channel.endpoint)\n", (4941, 4993), False, 'import logging\n'), ((9411, 9436), 'numpy.dtype', 'np.dtype', (["header['dtype']"], {}), "(header['dtype'])\n", (9419, 9436), True, 'import numpy as np\n'), ((10575, 10639), 'logging.warning', 'logging.warning', (['"""Clip minimum cannot be more than clip maximum"""'], {}), "('Clip minimum cannot be more than clip maximum')\n", (10590, 10639), False, 'import logging\n'), ((14991, 15048), 'logging.debug', 'logging.debug', (['"""Endpoint %s in request"""', 'channel.endpoint'], {}), "('Endpoint %s in request', channel.endpoint)\n", (15004, 15048), False, 'import logging\n'), ((5064, 5134), 'logging.warning', 'logging.warning', (['"""Unable to subscribe to %s: %s"""', 'endpoint', 'chan_error'], {}), "('Unable to subscribe to %s: %s', endpoint, chan_error)\n", (5079, 5134), False, 'import logging\n')]
import argparse import os import pickle as pkl import numpy as np import torch from statsmodels.tsa.arima_process import ArmaProcess from attribution.mask_group import MaskGroup from attribution.perturbation import GaussianBlur from baselines.explainers import FO, FP, IG, SVS from utils.losses import mse explainers = ["dynamask", "fo", "fp", "ig", "shap"] def run_experiment( cv: int = 0, N_ex: int = 10, T: int = 50, N_features: int = 50, N_select: int = 5, save_dir: str = "experiments/results/rare_feature/", ): """Run experiment. Args: cv: Do the experiment with different cv to obtain error bars. N_ex: Number of time series to generate. T: Length of each time series. N_features: Number of features in each time series. N_select: Number of features that are truly salient. save_dir: Directory where the results should be saved. Returns: None """ # Create the saving directory if it does not exist if not os.path.exists(save_dir): os.makedirs(save_dir) # Initialize useful variables random_seed = cv device = torch.device("cuda" if torch.cuda.is_available() else "cpu") torch.manual_seed(random_seed) np.random.seed(random_seed) pert = GaussianBlur(device=device) # We use a Gaussian Blur perturbation operator # Generate the input data ar = np.array([2, 0.5, 0.2, 0.1]) # AR coefficients ma = np.array([2]) # MA coefficients data_arima = ArmaProcess(ar=ar, ma=ma).generate_sample(nsample=(N_ex, T, N_features), axis=1) X = torch.tensor(data_arima, device=device, dtype=torch.float32) # Initialize the saliency tensors true_saliency = torch.zeros(size=(N_ex, T, N_features), device=device, dtype=torch.int64) dynamask_saliency = torch.zeros(size=true_saliency.shape, device=device) fo_saliency = torch.zeros(size=true_saliency.shape, device=device) fp_saliency = torch.zeros(size=true_saliency.shape, device=device) ig_saliency = torch.zeros(size=true_saliency.shape, device=device) shap_saliency = torch.zeros(size=true_saliency.shape, device=device) for k in range(N_ex): # We compute the attribution for each individual time series print(f"Now working on example {k + 1}/{N_ex}.") # The truly salient features are selected randomly via a random permutation perm = torch.randperm(N_features, device=device) true_saliency[k, int(T / 4) : int(3 * T / 4), perm[:N_select]] = 1 x = X[k, :, :] # The white box only depends on the truly salient features def f(input): output = torch.zeros(input.shape, device=input.device) output[int(T / 4) : int(3 * T / 4), perm[:N_select]] = input[int(T / 4) : int(3 * T / 4), perm[:N_select]] output = (output ** 2).sum(dim=-1) return output # Dynamask attribution mask_group = MaskGroup(perturbation=pert, device=device, random_seed=random_seed, verbose=False) mask_group.fit( f=f, X=x, area_list=np.arange(0.001, 0.051, 0.001), loss_function=mse, n_epoch=1000, size_reg_factor_dilation=1000, size_reg_factor_init=1, learning_rate=1.0, ) mask = mask_group.get_best_mask() # The mask with the lowest error is selected dynamask_attr = mask.mask_tensor.clone().detach() dynamask_saliency[k, :, :] = dynamask_attr # Feature Occlusion attribution fo = FO(f=f) fo_attr = fo.attribute(x) fo_saliency[k, :, :] = fo_attr # Feature Permutation attribution fp = FP(f=f) fp_attr = fp.attribute(x) fp_saliency[k, :, :] = fp_attr # Integrated Gradient attribution ig = IG(f=f) ig_attr = ig.attribute(x) ig_saliency[k, :, :] = ig_attr # Sampling Shapley Value attribution shap = SVS(f=f) shap_attr = shap.attribute(x) shap_saliency[k, :, :] = shap_attr # Save everything in the directory with open(os.path.join(save_dir, f"true_saliency_{cv}.pkl"), "wb") as file: pkl.dump(true_saliency, file) with open(os.path.join(save_dir, f"dynamask_saliency_{cv}.pkl"), "wb") as file: pkl.dump(dynamask_saliency, file) with open(os.path.join(save_dir, f"fo_saliency_{cv}.pkl"), "wb") as file: pkl.dump(fo_saliency, file) with open(os.path.join(save_dir, f"fp_saliency_{cv}.pkl"), "wb") as file: pkl.dump(fp_saliency, file) with open(os.path.join(save_dir, f"ig_saliency_{cv}.pkl"), "wb") as file: pkl.dump(ig_saliency, file) with open(os.path.join(save_dir, f"shap_saliency_{cv}.pkl"), "wb") as file: pkl.dump(shap_saliency, file) if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--cv", default=0, type=int) args = parser.parse_args() run_experiment(cv=args.cv)
[ "pickle.dump", "numpy.random.seed", "argparse.ArgumentParser", "baselines.explainers.SVS", "numpy.arange", "os.path.join", "os.path.exists", "baselines.explainers.FO", "torch.zeros", "statsmodels.tsa.arima_process.ArmaProcess", "baselines.explainers.IG", "baselines.explainers.FP", "torch.man...
[((1213, 1243), 'torch.manual_seed', 'torch.manual_seed', (['random_seed'], {}), '(random_seed)\n', (1230, 1243), False, 'import torch\n'), ((1248, 1275), 'numpy.random.seed', 'np.random.seed', (['random_seed'], {}), '(random_seed)\n', (1262, 1275), True, 'import numpy as np\n'), ((1287, 1314), 'attribution.perturbation.GaussianBlur', 'GaussianBlur', ([], {'device': 'device'}), '(device=device)\n', (1299, 1314), False, 'from attribution.perturbation import GaussianBlur\n'), ((1403, 1431), 'numpy.array', 'np.array', (['[2, 0.5, 0.2, 0.1]'], {}), '([2, 0.5, 0.2, 0.1])\n', (1411, 1431), True, 'import numpy as np\n'), ((1460, 1473), 'numpy.array', 'np.array', (['[2]'], {}), '([2])\n', (1468, 1473), True, 'import numpy as np\n'), ((1599, 1659), 'torch.tensor', 'torch.tensor', (['data_arima'], {'device': 'device', 'dtype': 'torch.float32'}), '(data_arima, device=device, dtype=torch.float32)\n', (1611, 1659), False, 'import torch\n'), ((1719, 1792), 'torch.zeros', 'torch.zeros', ([], {'size': '(N_ex, T, N_features)', 'device': 'device', 'dtype': 'torch.int64'}), '(size=(N_ex, T, N_features), device=device, dtype=torch.int64)\n', (1730, 1792), False, 'import torch\n'), ((1817, 1869), 'torch.zeros', 'torch.zeros', ([], {'size': 'true_saliency.shape', 'device': 'device'}), '(size=true_saliency.shape, device=device)\n', (1828, 1869), False, 'import torch\n'), ((1888, 1940), 'torch.zeros', 'torch.zeros', ([], {'size': 'true_saliency.shape', 'device': 'device'}), '(size=true_saliency.shape, device=device)\n', (1899, 1940), False, 'import torch\n'), ((1959, 2011), 'torch.zeros', 'torch.zeros', ([], {'size': 'true_saliency.shape', 'device': 'device'}), '(size=true_saliency.shape, device=device)\n', (1970, 2011), False, 'import torch\n'), ((2030, 2082), 'torch.zeros', 'torch.zeros', ([], {'size': 'true_saliency.shape', 'device': 'device'}), '(size=true_saliency.shape, device=device)\n', (2041, 2082), False, 'import torch\n'), ((2103, 2155), 'torch.zeros', 'torch.zeros', ([], {'size': 'true_saliency.shape', 'device': 'device'}), '(size=true_saliency.shape, device=device)\n', (2114, 2155), False, 'import torch\n'), ((4859, 4884), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (4882, 4884), False, 'import argparse\n'), ((1023, 1047), 'os.path.exists', 'os.path.exists', (['save_dir'], {}), '(save_dir)\n', (1037, 1047), False, 'import os\n'), ((1057, 1078), 'os.makedirs', 'os.makedirs', (['save_dir'], {}), '(save_dir)\n', (1068, 1078), False, 'import os\n'), ((2401, 2442), 'torch.randperm', 'torch.randperm', (['N_features'], {'device': 'device'}), '(N_features, device=device)\n', (2415, 2442), False, 'import torch\n'), ((2943, 3030), 'attribution.mask_group.MaskGroup', 'MaskGroup', ([], {'perturbation': 'pert', 'device': 'device', 'random_seed': 'random_seed', 'verbose': '(False)'}), '(perturbation=pert, device=device, random_seed=random_seed,\n verbose=False)\n', (2952, 3030), False, 'from attribution.mask_group import MaskGroup\n'), ((3567, 3574), 'baselines.explainers.FO', 'FO', ([], {'f': 'f'}), '(f=f)\n', (3569, 3574), False, 'from baselines.explainers import FO, FP, IG, SVS\n'), ((3704, 3711), 'baselines.explainers.FP', 'FP', ([], {'f': 'f'}), '(f=f)\n', (3706, 3711), False, 'from baselines.explainers import FO, FP, IG, SVS\n'), ((3841, 3848), 'baselines.explainers.IG', 'IG', ([], {'f': 'f'}), '(f=f)\n', (3843, 3848), False, 'from baselines.explainers import FO, FP, IG, SVS\n'), ((3983, 3991), 'baselines.explainers.SVS', 'SVS', ([], {'f': 'f'}), '(f=f)\n', (3986, 3991), False, 'from baselines.explainers import FO, FP, IG, SVS\n'), ((4201, 4230), 'pickle.dump', 'pkl.dump', (['true_saliency', 'file'], {}), '(true_saliency, file)\n', (4209, 4230), True, 'import pickle as pkl\n'), ((4323, 4356), 'pickle.dump', 'pkl.dump', (['dynamask_saliency', 'file'], {}), '(dynamask_saliency, file)\n', (4331, 4356), True, 'import pickle as pkl\n'), ((4443, 4470), 'pickle.dump', 'pkl.dump', (['fo_saliency', 'file'], {}), '(fo_saliency, file)\n', (4451, 4470), True, 'import pickle as pkl\n'), ((4557, 4584), 'pickle.dump', 'pkl.dump', (['fp_saliency', 'file'], {}), '(fp_saliency, file)\n', (4565, 4584), True, 'import pickle as pkl\n'), ((4671, 4698), 'pickle.dump', 'pkl.dump', (['ig_saliency', 'file'], {}), '(ig_saliency, file)\n', (4679, 4698), True, 'import pickle as pkl\n'), ((4787, 4816), 'pickle.dump', 'pkl.dump', (['shap_saliency', 'file'], {}), '(shap_saliency, file)\n', (4795, 4816), True, 'import pickle as pkl\n'), ((1171, 1196), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (1194, 1196), False, 'import torch\n'), ((1510, 1535), 'statsmodels.tsa.arima_process.ArmaProcess', 'ArmaProcess', ([], {'ar': 'ar', 'ma': 'ma'}), '(ar=ar, ma=ma)\n', (1521, 1535), False, 'from statsmodels.tsa.arima_process import ArmaProcess\n'), ((2652, 2697), 'torch.zeros', 'torch.zeros', (['input.shape'], {'device': 'input.device'}), '(input.shape, device=input.device)\n', (2663, 2697), False, 'import torch\n'), ((4127, 4176), 'os.path.join', 'os.path.join', (['save_dir', 'f"""true_saliency_{cv}.pkl"""'], {}), "(save_dir, f'true_saliency_{cv}.pkl')\n", (4139, 4176), False, 'import os\n'), ((4245, 4298), 'os.path.join', 'os.path.join', (['save_dir', 'f"""dynamask_saliency_{cv}.pkl"""'], {}), "(save_dir, f'dynamask_saliency_{cv}.pkl')\n", (4257, 4298), False, 'import os\n'), ((4371, 4418), 'os.path.join', 'os.path.join', (['save_dir', 'f"""fo_saliency_{cv}.pkl"""'], {}), "(save_dir, f'fo_saliency_{cv}.pkl')\n", (4383, 4418), False, 'import os\n'), ((4485, 4532), 'os.path.join', 'os.path.join', (['save_dir', 'f"""fp_saliency_{cv}.pkl"""'], {}), "(save_dir, f'fp_saliency_{cv}.pkl')\n", (4497, 4532), False, 'import os\n'), ((4599, 4646), 'os.path.join', 'os.path.join', (['save_dir', 'f"""ig_saliency_{cv}.pkl"""'], {}), "(save_dir, f'ig_saliency_{cv}.pkl')\n", (4611, 4646), False, 'import os\n'), ((4713, 4762), 'os.path.join', 'os.path.join', (['save_dir', 'f"""shap_saliency_{cv}.pkl"""'], {}), "(save_dir, f'shap_saliency_{cv}.pkl')\n", (4725, 4762), False, 'import os\n'), ((3107, 3137), 'numpy.arange', 'np.arange', (['(0.001)', '(0.051)', '(0.001)'], {}), '(0.001, 0.051, 0.001)\n', (3116, 3137), True, 'import numpy as np\n')]
"""Evaluate multiple models in multiple experiments, or evaluate baseline on multiple datasets TODO: use hydra or another model to manage the experiments """ import os import sys import json import argparse import logging from glob import glob import time import string logging.basicConfig(format='%(asctime)s: %(levelname)s: %(message)s', level=logging.INFO) import numpy as np import pandas as pd import h5py import scipy import scipy.interpolate import scipy.stats import torch import dill import matplotlib.pyplot as plt import matplotlib.cm as cm import matplotlib.ticker as ticker import matplotlib.colors as colors import matplotlib.patheffects as pe import matplotlib.animation as animation from tqdm import tqdm from tabulate import tabulate import utility as util from helper import load_model, prediction_output_to_trajectories pd.set_option('io.hdf.default_format','table') ############################ # Bag-of-N (BoN) FDE metrics ############################ def compute_min_FDE(predict, future): return np.min(np.linalg.norm(predict[...,-1,:] - future[-1], axis=-1)) def compute_min_ADE(predict, future): mean_ades = np.mean(np.linalg.norm(predict - future, axis=-1), axis=-1) return np.min(mean_ades) def evaluate_scene_BoN(scene, ph, eval_stg, hyp, n_predictions=20, min_fde=True, min_ade=True): predictconfig = util.AttrDict(ph=ph, num_samples=n_predictions, z_mode=False, gmm_mode=False, full_dist=False, all_z_sep=False) max_hl = hyp['maximum_history_length'] with torch.no_grad(): predictions = eval_stg.predict(scene, np.arange(scene.timesteps), predictconfig.ph, num_samples=predictconfig.num_samples, min_future_timesteps=predictconfig.ph, z_mode=predictconfig.z_mode, gmm_mode=predictconfig.gmm_mode, full_dist=predictconfig.full_dist, all_z_sep=predictconfig.all_z_sep) prediction_dict, histories_dict, futures_dict = \ prediction_output_to_trajectories( predictions, dt=scene.dt, max_h=max_hl, ph=predictconfig.ph, map=None) batch_metrics = {'min_ade': list(), 'min_fde': list()} for t in prediction_dict.keys(): for node in prediction_dict[t].keys(): if min_ade: batch_metrics['min_ade'].append(compute_min_ADE(prediction_dict[t][node], futures_dict[t][node])) if min_fde: batch_metrics['min_fde'].append(compute_min_FDE(prediction_dict[t][node], futures_dict[t][node])) return batch_metrics def evaluate_BoN(env, ph, eval_stg, hyp, n_predictions=20, min_fde=True, min_ade=True): batch_metrics = {'min_ade': list(), 'min_fde': list()} prefix = f"Evaluate Bo{n_predictions} (ph = {ph}): " for scene in tqdm(env.scenes, desc=prefix, dynamic_ncols=True, leave=True): _batch_metrics = evaluate_scene_BoN(scene, ph, eval_stg, hyp, n_predictions=n_predictions, min_fde=min_fde, min_ade=min_ade) batch_metrics['min_ade'].extend(_batch_metrics['min_ade']) batch_metrics['min_fde'].extend(_batch_metrics['min_fde']) return batch_metrics ############### # Other metrics ############### def make_interpolate_map(scene): map = scene.map['VEHICLE'] obs_map = 1 - np.max(map.data[..., :, :, :], axis=-3) / 255 interp_obs_map = scipy.interpolate.RectBivariateSpline( range(obs_map.shape[0]), range(obs_map.shape[1]), obs_map, kx=1, ky=1) return interp_obs_map def compute_num_offroad_viols(interp_map, scene_map, predicted_trajs): """Count the number of predicted trajectories that go off the road. Note this does not count trajectories that go over road/lane dividers. Parameters ========== interp_map : scipy.interpolate.RectBivariateSpline Interpolation to get road obstacle indicator value from predicted points. scene_map : trajectron.environment.GeometricMap Map transform the predicted points to map coordinates. predicted_trajs : ndarray Predicted trajectories of shape (number of predictions, number of timesteps, 2). Returns ======= int A value between [0, number of predictions]. """ old_shape = predicted_trajs.shape pred_trajs_map = scene_map.to_map_points(predicted_trajs.reshape((-1, 2))) traj_values = interp_map(pred_trajs_map[:, 0], pred_trajs_map[:, 1], grid=False) # traj_values has shape (1, num_samples, ph). traj_values = traj_values.reshape((old_shape[0], old_shape[1], old_shape[2])) # num_viol_trajs is an integer in [0, num_samples]. return np.sum(traj_values.max(axis=2) > 0, dtype=float) def compute_kde_nll(predicted_trajs, gt_traj): kde_ll = 0. log_pdf_lower_bound = -20 num_timesteps = gt_traj.shape[0] num_batches = predicted_trajs.shape[0] for batch_num in range(num_batches): for timestep in range(num_timesteps): try: kde = scipy.stats.gaussian_kde(predicted_trajs[batch_num, :, timestep].T) pdf = kde.logpdf(gt_traj[timestep].T) pdf = np.clip(kde.logpdf(gt_traj[timestep].T), a_min=log_pdf_lower_bound, a_max=None)[0] kde_ll += pdf / (num_timesteps * num_batches) except np.linalg.LinAlgError: kde_ll = np.nan return -kde_ll def compute_ade(predicted_trajs, gt_traj): error = np.linalg.norm(predicted_trajs - gt_traj, axis=-1) ade = np.mean(error, axis=-1) return ade.flatten() def compute_fde(predicted_trajs, gt_traj): final_error = np.linalg.norm(predicted_trajs[:, :, -1] - gt_traj[-1], axis=-1) return final_error.flatten() ######################## # Most Likely Evaluation ######################## def evaluate_scene_most_likely(scene, ph, eval_stg, hyp, ade=True, fde=True): predictconfig = util.AttrDict(ph=ph, num_samples=1, z_mode=True, gmm_mode=True, full_dist=False, all_z_sep=False) max_hl = hyp['maximum_history_length'] with torch.no_grad(): predictions = eval_stg.predict(scene, np.arange(scene.timesteps), predictconfig.ph, num_samples=predictconfig.num_samples, min_future_timesteps=predictconfig.ph, z_mode=predictconfig.z_mode, gmm_mode=predictconfig.gmm_mode, full_dist=predictconfig.full_dist, all_z_sep=predictconfig.all_z_sep) prediction_dict, histories_dict, futures_dict = \ prediction_output_to_trajectories( predictions, dt=scene.dt, max_h=max_hl, ph=predictconfig.ph, map=None) batch_metrics = {'ade': list(), 'fde': list()} for t in prediction_dict.keys(): for node in prediction_dict[t].keys(): if ade: batch_metrics['ade'].extend( compute_ade(prediction_dict[t][node], futures_dict[t][node]) ) if fde: batch_metrics['fde'].extend( compute_fde(prediction_dict[t][node], futures_dict[t][node]) ) return batch_metrics def evaluate_most_likely(env, ph, eval_stg, hyp, ade=True, fde=True): batch_metrics = {'ade': list(), 'fde': list()} prefix = f"Evaluate Most Likely (ph = {ph}): " for scene in tqdm(env.scenes, desc=prefix, dynamic_ncols=True, leave=True): _batch_metrics = evaluate_scene_most_likely(scene, ph, eval_stg, hyp, ade=ade, fde=fde) batch_metrics['ade'].extend(_batch_metrics['ade']) batch_metrics['fde'].extend(_batch_metrics['fde']) return batch_metrics ################# # Full Evaluation ################# def evaluate_scene_full(scene, ph, eval_stg, hyp, ade=True, fde=True, kde=True, offroad_viols=True): num_samples = 2000 predictconfig = util.AttrDict(ph=ph, num_samples=num_samples, z_mode=False, gmm_mode=False, full_dist=False, all_z_sep=False) max_hl = hyp['maximum_history_length'] with torch.no_grad(): predictions = eval_stg.predict(scene, np.arange(scene.timesteps), predictconfig.ph, num_samples=predictconfig.num_samples, min_future_timesteps=predictconfig.ph, z_mode=predictconfig.z_mode, gmm_mode=predictconfig.gmm_mode, full_dist=predictconfig.full_dist, all_z_sep=predictconfig.all_z_sep) prediction_dict, histories_dict, futures_dict = \ prediction_output_to_trajectories( predictions, dt=scene.dt, max_h=max_hl, ph=predictconfig.ph, map=None) interp_map = make_interpolate_map(scene) map = scene.map['VEHICLE'] batch_metrics = {'ade': list(), 'fde': list(), 'kde': list(), 'offroad_viols': list()} for t in prediction_dict.keys(): for node in prediction_dict[t].keys(): if ade: batch_metrics['ade'].extend( compute_ade(prediction_dict[t][node], futures_dict[t][node]) ) if fde: batch_metrics['fde'].extend( compute_fde(prediction_dict[t][node], futures_dict[t][node]) ) if offroad_viols: batch_metrics['offroad_viols'].extend( [ compute_num_offroad_viols(interp_map, map, prediction_dict[t][node]) / float(num_samples) ]) if kde: batch_metrics['kde'].extend( [ compute_kde_nll(prediction_dict[t][node], futures_dict[t][node]) ]) return batch_metrics def evaluate_full(env, ph, eval_stg, hyp, ade=True, fde=True, kde=True, offroad_viols=True): batch_metrics = {'ade': list(), 'fde': list(), 'kde': list(), 'offroad_viols': list()} prefix = f"Evaluate Full (ph = {ph}): " for scene in tqdm(env.scenes, desc=prefix, dynamic_ncols=True, leave=True): _batch_metrics = evaluate_scene_full(scene, ph, eval_stg, hyp, ade=ade, fde=fde, kde=kde, offroad_viols=offroad_viols) batch_metrics['ade'].extend(_batch_metrics['ade']) batch_metrics['fde'].extend(_batch_metrics['fde']) batch_metrics['kde'].extend(_batch_metrics['kde']) batch_metrics['offroad_viols'].extend(_batch_metrics['offroad_viols']) return batch_metrics ########## # Datasets ########## dataset_dir = "../../.." dataset_1 = util.AttrDict( test_set_path=f"{ dataset_dir }/carla_v3-1_dataset/v3-1_split1_test.pkl", name='v3-1_split1_test', desc="CARLA synthesized dataset with heading fix, occlusion fix, and 32 timesteps.") dataset_2 = util.AttrDict( test_set_path=f"{ dataset_dir }/carla_v3-1-1_dataset/v3-1-1_split1_test.pkl", name='v3-1-1_split1_test', desc="CARLA synthesized dataset with heading fix, occlusion fix, and 32 timesteps.") dataset_3 = util.AttrDict( test_set_path=f"{ dataset_dir }/carla_v3-1-2_dataset/v3-1-2_split1_test.pkl", name='v3-1-2_split1_test', desc="CARLA synthesized dataset with heading fix, occlusion fix, and 32 timesteps.") DATASETS = [dataset_1, dataset_2, dataset_3] def load_dataset(dataset): logging.info(f"Loading dataset: {dataset.name}: {dataset.desc}") with open(dataset.test_set_path, 'rb') as f: eval_env = dill.load(f, encoding='latin1') return eval_env ############# # Experiments ############# """ The experiments to evaluate are: - 20210621 one model trained on NuScenes to use as baseline for other evaluation - 20210801 have models trained from v3-1-1 (train set has 200 scenes). Compare MapV2, MapV3. - 20210802 have models trained from v3-1-1. MapV5 squeezes map encoding to size 32 using FC. - 20210803 have models trained from v3-1-1. Compare map, mapV4. MapV4 with multi K values. MapV4 does not apply FC. May have size 100 or 150. - 20210804 have models trained from v3-1 (train set has 300 scenes). Compare map with mapV4. - 20210805 have models trained from v3-1 (train set has 300 scenes). MapV4 with multi K values. - 20210812 have models trained from v3-1-1 rebalanced. Models are trained 20 epochs. - 20210815 have models trained from v3-1-1 rebalanced. Models are trained 40 epochs. - 20210816 have models trained from v3-1-2 (train set has 600 scenes) rebalanced. """ model_dir = "models" baseline_model = util.AttrDict( path=f"{ model_dir }/20210621/models_19_Mar_2021_22_14_19_int_ee_me_ph8", desc="Base model +Dynamics Integration, Maps with K=25 latent values " "(on NuScenes dataset)") experiment_1 = util.AttrDict( models_dir=f"{ model_dir }/20210801", dataset=dataset_2, desc="20210801 have models trained from v3-1-1 (train set has 200 scenes). Compare MapV2, MapV3.") experiment_2 = util.AttrDict( models_dir=f"{ model_dir }/20210802", dataset=dataset_2, desc="20210802 have models trained from v3-1-1. MapV5 squeezes map encoding to size 32 using FC.") experiment_3 = util.AttrDict( models_dir=f"{ model_dir }/20210803", dataset=dataset_2, desc="20210803 have models trained from v3-1-1. Compare map, mapV4. MapV4 with multi K values. " "MapV4 does not apply FC. May have size 100 or 150.") experiment_4 = util.AttrDict( models_dir=f"{ model_dir }/20210804", dataset=dataset_1, desc="20210804 have models trained from v3-1 (train set has 300 scenes). Compare map with mapV4.") experiment_5 = util.AttrDict( models_dir=f"{ model_dir }/20210805", dataset=dataset_1, desc="20210805 have models trained from v3-1 (train set has 300 scenes). MapV4 with multi K values.") experiment_6 = util.AttrDict( models_dir=f"{ model_dir }/20210812", dataset=dataset_2, desc="20210812 have models trained from v3-1-1 rebalanced. Models are trained 20 epochs.") experiment_7 = util.AttrDict( models_dir=f"{ model_dir }/20210815", dataset=dataset_2, ts=40, desc="20210815 have models trained from v3-1-1 rebalanced. Models are trained 40 epochs.") experiment_8 = util.AttrDict( models_dir=f"{ model_dir }/20210816", dataset=dataset_3, desc="20210816 have models trained from v3-1-2 (train set has 600 scenes) rebalanced.") EXPERIMENTS = [experiment_1, experiment_2, experiment_3, experiment_4, experiment_5, experiment_6, experiment_7, experiment_8] def _load_model(model_path, eval_env, ts=20): eval_stg, hyp = load_model(model_path, eval_env, ts=ts)#, device='cuda') return eval_stg, hyp PREDICTION_HORIZONS = [2,4,6,8] def run_evaluate_experiments(config): if config.experiment_index is not None and config.experiment_index >= 1: experiments = [EXPERIMENTS[config.experiment_index - 1]] else: experiments = EXPERIMENTS ###################### # Evaluate experiments ###################### # results_filename = f"results_{time.strftime('%d_%b_%Y_%H_%M_%S', time.localtime())}.h5" logging.info("Evaluating each experiment") for experiment in experiments: results_key = experiment.models_dir.split('/')[-1] results_filename = f"results_{results_key}.h5" logging.info(f"Evaluating models in experiment: {experiment.desc}") logging.info(f"Writing to: {results_filename}") eval_env = load_dataset(experiment.dataset) # need hyper parameters to do this, but have to load models first has_computed_scene_graph = False for model_path in glob(f"{experiment.models_dir}/*"): model_key = '/'.join(model_path.split('/')[-2:]) ts = getattr(experiment, 'ts', 20) eval_stg, hyp = _load_model(model_path, eval_env, ts=ts) if not has_computed_scene_graph: prefix = f"Preparing Node Graph: " for scene in tqdm(eval_env.scenes, desc=prefix, dynamic_ncols=True, leave=True): scene.calculate_scene_graph(eval_env.attention_radius, hyp['edge_addition_filter'], hyp['edge_removal_filter']) has_computed_scene_graph = True logging.info(f"Evaluating: {model_key}") BoN_results_key = '/'.join([experiment.dataset.name] + model_path.split('/')[-2:] + ['BoN']) with pd.HDFStore(results_filename, 'a') as s: for ph in PREDICTION_HORIZONS: batch_metrics = evaluate_BoN(eval_env, ph, eval_stg, hyp) df = pd.DataFrame(batch_metrics) df['ph'] = ph s.put(BoN_results_key, df, format='t', append=True, data_columns=True) ML_results_key = '/'.join([experiment.dataset.name] + model_path.split('/')[-2:] + ['ML']) with pd.HDFStore(results_filename, 'a') as s: for ph in PREDICTION_HORIZONS: batch_metrics = evaluate_most_likely(eval_env, ph, eval_stg, hyp) df = pd.DataFrame(batch_metrics) df['ph'] = ph s.put(ML_results_key, df, format='t', append=True, data_columns=True) full_results_key = '/'.join([experiment.dataset.name] + model_path.split('/')[-2:] + ['Full']) other_results_key = '/'.join([experiment.dataset.name] + model_path.split('/')[-2:] + ['Other']) for ph in PREDICTION_HORIZONS: batch_metrics = evaluate_full(eval_env, ph, eval_stg, hyp) with pd.HDFStore(results_filename, 'a') as s: df = pd.DataFrame({'fde': batch_metrics['fde'], 'ade': batch_metrics['ade'], 'ph': ph }) s.put(full_results_key, df, format='t', append=True, data_columns=True) df = pd.DataFrame({'kde': batch_metrics['kde'], 'offroad_viols': batch_metrics['offroad_viols'], 'ph': ph }) s.put(other_results_key, df, format='t', append=True, data_columns=True) del eval_stg del hyp del eval_env logging.info("done evaluating experiments") def run_evaluate_baselines(config): #################### # Evaluate baselines #################### results_filename = "results_baseline.h5" logging.info("Evaluating baselines") for dataset in DATASETS: logging.info(f"Evaluating baseline on dataset: {dataset.name}: {dataset.desc}") eval_env = load_dataset(dataset) logging.info(f"Using baseline: {baseline_model.desc}") eval_stg, hyp = _load_model(baseline_model.path, eval_env) prefix = f"Preparing Node Graph: " for scene in tqdm(eval_env.scenes, desc=prefix, dynamic_ncols=True, leave=True): scene.calculate_scene_graph(eval_env.attention_radius, hyp['edge_addition_filter'], hyp['edge_removal_filter']) BoN_results_key = '/'.join([dataset.name] + baseline_model.path.split('/')[-2:] + ['BoN']) with pd.HDFStore(results_filename, 'a') as s: for ph in PREDICTION_HORIZONS: batch_metrics = evaluate_BoN(eval_env, ph, eval_stg, hyp) df = pd.DataFrame(batch_metrics) df['ph'] = ph s.put(BoN_results_key, df, format='t', append=True, data_columns=True) ML_results_key = '/'.join([dataset.name] + baseline_model.path.split('/')[-2:] + ['ML']) with pd.HDFStore(results_filename, 'a') as s: for ph in PREDICTION_HORIZONS: batch_metrics = evaluate_most_likely(eval_env, ph, eval_stg, hyp) df = pd.DataFrame(batch_metrics) df['ph'] = ph s.put(ML_results_key, df, format='t', append=True, data_columns=True) full_results_key = '/'.join([dataset.name] + baseline_model.path.split('/')[-2:] + ['Full']) other_results_key = '/'.join([dataset.name] + baseline_model.path.split('/')[-2:] + ['Other']) for ph in PREDICTION_HORIZONS: batch_metrics = evaluate_full(eval_env, ph, eval_stg, hyp) with pd.HDFStore(results_filename, 'a') as s: df = pd.DataFrame({'fde': batch_metrics['fde'], 'ade': batch_metrics['ade'], 'ph': ph }) s.put(full_results_key, df, format='t', append=True, data_columns=True) df = pd.DataFrame({'kde': batch_metrics['kde'], 'offroad_viols': batch_metrics['offroad_viols'], 'ph': ph }) s.put(other_results_key, df, format='t', append=True, data_columns=True) del hyp del eval_stg del eval_env logging.info("Done evaluating baselines") RESULTS_FILENAMES = [ 'results_20210801.h5', 'results_20210802.h5', 'results_20210803.h5', 'results_20210804.h5', 'results_20210805.h5', 'results_20210812.h5', 'results_20210815.h5', 'results_20210816.h5', 'results_baseline.h5',] ALPHABET = tuple(k for k in string.ascii_uppercase) def run_summarize_experiments(config): scores = {} logging.info("Run summarize experiments.") for h5_filename in RESULTS_FILENAMES: logging.info(f"Reading scores from H5 file {h5_filename}.") with pd.HDFStore(h5_filename, 'r') as store: for key in store.keys(): logging.info(f"Getting scores for {key}.") key_fragments = key.split('/')[1:] # for example # dataset_name v3-1-1_split1_test # experiment_name 20210816 # model_name models_17_Aug_2021_13_25_38_carla_v3-1-2_base_distmapV4_modfm_K15_ph8 # score_type BoN dataset_name, experiment_name, model_name, score_type = key_fragments _experiment_name = f"{experiment_name}/{dataset_name}" if _experiment_name not in scores: scores[_experiment_name] = {} if model_name not in scores[_experiment_name]: scores[_experiment_name][model_name] = {} fig1, axes1 = plt.subplots(2, 2, figsize=(15,15)) fig2, axes2 = plt.subplots(2, 2, figsize=(15,15)) for fig in [fig1, fig2]: if score_type == 'BoN': fig.suptitle("Bag-of-20 Metrics", fontsize=14) elif score_type == 'ML': fig.suptitle("Most Likely (ML) Metrics", fontsize=14) elif score_type == 'Full' or score_type == 'Other': fig.suptitle("Metrics aggregated over 2000 samples", fontsize=14) axes1 = axes1.ravel() axes2 = axes2.ravel() for idx, ph in enumerate(PREDICTION_HORIZONS): logging.info(f" scores for PH = {ph}.") if ph not in scores[_experiment_name][model_name]: scores[_experiment_name][model_name][ph] = {} df = store[key][store[key]['ph'] == ph] if score_type == 'BoN': scores[_experiment_name][model_name][ph]['min_ade_mean'] = df['min_ade'].mean() scores[_experiment_name][model_name][ph]['min_fde_mean'] = df['min_fde'].mean() scores[_experiment_name][model_name][ph]['min_ade_var'] = df['min_ade'].var() scores[_experiment_name][model_name][ph]['min_fde_var'] = df['min_fde'].var() axes1[idx].hist(df['min_ade'], bins=100) axes1[idx].set_title(f"Min ADE @{ph / 2.}s") axes2[idx].hist(df['min_fde'], bins=100) axes2[idx].set_title(f"Min FDE @{ph / 2.}s") elif score_type == 'ML': scores[_experiment_name][model_name][ph]['ade_ml_mean'] = df['ade'].mean() scores[_experiment_name][model_name][ph]['fde_ml_mean'] = df['fde'].mean() scores[_experiment_name][model_name][ph]['ade_ml_var'] = df['ade'].var() scores[_experiment_name][model_name][ph]['fde_ml_var'] = df['fde'].var() axes1[idx].hist(df['ade'], bins=100) axes1[idx].set_title(f"ADE ML @{ph / 2.}s") axes2[idx].hist(df['fde'], bins=100) axes2[idx].set_title(f"FDE ML @{ph / 2.}s") elif score_type == 'Full': scores[_experiment_name][model_name][ph]['ade_mean'] = df['ade'].mean() scores[_experiment_name][model_name][ph]['fde_mean'] = df['fde'].mean() scores[_experiment_name][model_name][ph]['ade_var'] = df['ade'].var() scores[_experiment_name][model_name][ph]['fde_var'] = df['fde'].var() axes1[idx].hist(df['ade'], bins=100) axes1[idx].set_title(f"ADE @{ph / 2.}s") axes2[idx].hist(df['fde'], bins=100) axes2[idx].set_title(f"FDE @{ph / 2.}s") elif score_type == 'Other': scores[_experiment_name][model_name][ph]['kde_mean'] = df['kde'].mean() scores[_experiment_name][model_name][ph]['offroad_viols_mean'] = df['offroad_viols'].mean() scores[_experiment_name][model_name][ph]['kde_var'] = df['kde'].mean() scores[_experiment_name][model_name][ph]['offroad_viols_var'] = df['offroad_viols'].mean() axes1[idx].hist(df['kde'], bins=100) axes1[idx].set_title(f"KDE NLL @{ph / 2.}s") axes2[idx].hist(df['offroad_viols'], bins=100) axes2[idx].set_title(f"Off-road violations @{ph / 2.}s") else: raise Exception(f"Score type {score_type} is not recognized.") savekey = f"{experiment_name}_{dataset_name}" logging.info(" saving plots.") if score_type == 'BoN': fig1.savefig(f"plots/{savekey}_min_ade.png", dpi=180) fig2.savefig(f"plots/{savekey}_min_fde.png", dpi=180) elif score_type == 'ML': fig1.savefig(f"plots/{savekey}_ade_ml.png", dpi=180) fig2.savefig(f"plots/{savekey}_fde_ml.png", dpi=180) elif score_type == 'Full': fig1.savefig(f"plots/{savekey}_ade.png", dpi=180) fig2.savefig(f"plots/{savekey}_fde.png", dpi=180) elif score_type == 'Other': fig1.savefig(f"plots/{savekey}_kde.png", dpi=180) fig2.savefig(f"plots/{savekey}_offroad_viols.png", dpi=180) plt.close('all') logging.info("Generating tables.") with open('plots/tables.txt', 'w') as f: for _experiment_name, v in scores.items(): experiment_name, dataset_name = _experiment_name.split('/') print(f"Writing (experiment {experiment_name} using dataset {dataset_name})") print(f"Experiment {experiment_name} using dataset {dataset_name}", file=f) # Get model legend table headers = [f"Model Legend\nName (for experiment {experiment_name})", "\nIndex"] model_df = pd.DataFrame(columns=headers) for idx, (model_name, vv) in enumerate(v.items()): model_data = pd.Series({ headers[0]: model_name, headers[1]: ALPHABET[idx] }) model_df = model_df.append(model_data, ignore_index=True) print(file=f) print(tabulate(model_df, headers='keys', showindex=False, tablefmt="simple"), file=f) score_tup = [ ("Min ADE", "min_ade"), ("Min FDE", "min_fde"), ("ADE ML", "ade_ml"), ("FDE ML", "fde_ml"), ("ADE", "ade"), ("FDE", "fde"), ("KDE NLL", "kde"), ("Offroad Viols", "offroad_viols"),] for score_name, score_key in score_tup: headers = ["\nModel", f"{score_name}\n@1s", "\n@2s", "\n@3s", "\n@4s"] mean_key = f"{score_key}_mean" var_key = f"{score_key}_var" # Get score table score_df = pd.DataFrame(columns=headers) for idx, (model_name, vv) in enumerate(v.items()): score_data = { headers[0]: ALPHABET[idx] } for ph, vvv in vv.items(): kdx = ph // 2 mean_val = np.around(vvv[mean_key], decimals=2 ) dev_val = np.around( np.sqrt(vvv[var_key]), decimals=2 ) score_data[headers[kdx]] = f"{mean_val} +/- {dev_val}" model_df = model_df.append(model_data, ignore_index=True) score_df = score_df.append(score_data, ignore_index=True) print(file=f) print(tabulate(score_df, headers='keys', showindex=False, tablefmt="simple"), file=f) # newline print(file=f) def parse_arguments(): argparser = argparse.ArgumentParser( description=__doc__) subparsers = argparser.add_subparsers(dest="task") compute_parser = subparsers.add_parser('compute', help="Compute evaluation scores.") compute_parser.add_argument( '--experiment-index', default=0, type=int, help="Experiment index number to run") summarize_parser = subparsers.add_parser('summarize', help="Summarize evaluation scores and generate plots.") return argparser.parse_args() if __name__ == "__main__": config = parse_arguments() if config.task == 'compute': if config.experiment_index == 0: run_evaluate_baselines(config) else: run_evaluate_experiments(config) elif config.task == 'summarize': run_summarize_experiments(config) else: logging.warning("No task selected.")
[ "utility.AttrDict", "pandas.HDFStore", "argparse.ArgumentParser", "numpy.around", "numpy.mean", "numpy.linalg.norm", "numpy.arange", "glob.glob", "torch.no_grad", "pandas.set_option", "pandas.DataFrame", "logging.warning", "matplotlib.pyplot.close", "dill.load", "numpy.max", "matplotli...
[((273, 367), 'logging.basicConfig', 'logging.basicConfig', ([], {'format': '"""%(asctime)s: %(levelname)s: %(message)s"""', 'level': 'logging.INFO'}), "(format='%(asctime)s: %(levelname)s: %(message)s', level\n =logging.INFO)\n", (292, 367), False, 'import logging\n'), ((845, 892), 'pandas.set_option', 'pd.set_option', (['"""io.hdf.default_format"""', '"""table"""'], {}), "('io.hdf.default_format', 'table')\n", (858, 892), True, 'import pandas as pd\n'), ((10449, 10664), 'utility.AttrDict', 'util.AttrDict', ([], {'test_set_path': 'f"""{dataset_dir}/carla_v3-1_dataset/v3-1_split1_test.pkl"""', 'name': '"""v3-1_split1_test"""', 'desc': '"""CARLA synthesized dataset with heading fix, occlusion fix, and 32 timesteps."""'}), "(test_set_path=\n f'{dataset_dir}/carla_v3-1_dataset/v3-1_split1_test.pkl', name=\n 'v3-1_split1_test', desc=\n 'CARLA synthesized dataset with heading fix, occlusion fix, and 32 timesteps.'\n )\n", (10462, 10664), True, 'import utility as util\n'), ((10685, 10906), 'utility.AttrDict', 'util.AttrDict', ([], {'test_set_path': 'f"""{dataset_dir}/carla_v3-1-1_dataset/v3-1-1_split1_test.pkl"""', 'name': '"""v3-1-1_split1_test"""', 'desc': '"""CARLA synthesized dataset with heading fix, occlusion fix, and 32 timesteps."""'}), "(test_set_path=\n f'{dataset_dir}/carla_v3-1-1_dataset/v3-1-1_split1_test.pkl', name=\n 'v3-1-1_split1_test', desc=\n 'CARLA synthesized dataset with heading fix, occlusion fix, and 32 timesteps.'\n )\n", (10698, 10906), True, 'import utility as util\n'), ((10927, 11148), 'utility.AttrDict', 'util.AttrDict', ([], {'test_set_path': 'f"""{dataset_dir}/carla_v3-1-2_dataset/v3-1-2_split1_test.pkl"""', 'name': '"""v3-1-2_split1_test"""', 'desc': '"""CARLA synthesized dataset with heading fix, occlusion fix, and 32 timesteps."""'}), "(test_set_path=\n f'{dataset_dir}/carla_v3-1-2_dataset/v3-1-2_split1_test.pkl', name=\n 'v3-1-2_split1_test', desc=\n 'CARLA synthesized dataset with heading fix, occlusion fix, and 32 timesteps.'\n )\n", (10940, 11148), True, 'import utility as util\n'), ((12395, 12593), 'utility.AttrDict', 'util.AttrDict', ([], {'path': 'f"""{model_dir}/20210621/models_19_Mar_2021_22_14_19_int_ee_me_ph8"""', 'desc': '"""Base model +Dynamics Integration, Maps with K=25 latent values (on NuScenes dataset)"""'}), "(path=\n f'{model_dir}/20210621/models_19_Mar_2021_22_14_19_int_ee_me_ph8', desc\n =\n 'Base model +Dynamics Integration, Maps with K=25 latent values (on NuScenes dataset)'\n )\n", (12408, 12593), True, 'import utility as util\n'), ((12625, 12802), 'utility.AttrDict', 'util.AttrDict', ([], {'models_dir': 'f"""{model_dir}/20210801"""', 'dataset': 'dataset_2', 'desc': '"""20210801 have models trained from v3-1-1 (train set has 200 scenes). Compare MapV2, MapV3."""'}), "(models_dir=f'{model_dir}/20210801', dataset=dataset_2, desc=\n '20210801 have models trained from v3-1-1 (train set has 200 scenes). Compare MapV2, MapV3.'\n )\n", (12638, 12802), True, 'import utility as util\n'), ((12836, 13013), 'utility.AttrDict', 'util.AttrDict', ([], {'models_dir': 'f"""{model_dir}/20210802"""', 'dataset': 'dataset_2', 'desc': '"""20210802 have models trained from v3-1-1. MapV5 squeezes map encoding to size 32 using FC."""'}), "(models_dir=f'{model_dir}/20210802', dataset=dataset_2, desc=\n '20210802 have models trained from v3-1-1. MapV5 squeezes map encoding to size 32 using FC.'\n )\n", (12849, 13013), True, 'import utility as util\n'), ((13047, 13273), 'utility.AttrDict', 'util.AttrDict', ([], {'models_dir': 'f"""{model_dir}/20210803"""', 'dataset': 'dataset_2', 'desc': '"""20210803 have models trained from v3-1-1. Compare map, mapV4. MapV4 with multi K values. MapV4 does not apply FC. May have size 100 or 150."""'}), "(models_dir=f'{model_dir}/20210803', dataset=dataset_2, desc=\n '20210803 have models trained from v3-1-1. Compare map, mapV4. MapV4 with multi K values. MapV4 does not apply FC. May have size 100 or 150.'\n )\n", (13060, 13273), True, 'import utility as util\n'), ((13323, 13500), 'utility.AttrDict', 'util.AttrDict', ([], {'models_dir': 'f"""{model_dir}/20210804"""', 'dataset': 'dataset_1', 'desc': '"""20210804 have models trained from v3-1 (train set has 300 scenes). Compare map with mapV4."""'}), "(models_dir=f'{model_dir}/20210804', dataset=dataset_1, desc=\n '20210804 have models trained from v3-1 (train set has 300 scenes). Compare map with mapV4.'\n )\n", (13336, 13500), True, 'import utility as util\n'), ((13534, 13714), 'utility.AttrDict', 'util.AttrDict', ([], {'models_dir': 'f"""{model_dir}/20210805"""', 'dataset': 'dataset_1', 'desc': '"""20210805 have models trained from v3-1 (train set has 300 scenes). MapV4 with multi K values."""'}), "(models_dir=f'{model_dir}/20210805', dataset=dataset_1, desc=\n '20210805 have models trained from v3-1 (train set has 300 scenes). MapV4 with multi K values.'\n )\n", (13547, 13714), True, 'import utility as util\n'), ((13748, 13917), 'utility.AttrDict', 'util.AttrDict', ([], {'models_dir': 'f"""{model_dir}/20210812"""', 'dataset': 'dataset_2', 'desc': '"""20210812 have models trained from v3-1-1 rebalanced. Models are trained 20 epochs."""'}), "(models_dir=f'{model_dir}/20210812', dataset=dataset_2, desc=\n '20210812 have models trained from v3-1-1 rebalanced. Models are trained 20 epochs.'\n )\n", (13761, 13917), True, 'import utility as util\n'), ((13951, 14131), 'utility.AttrDict', 'util.AttrDict', ([], {'models_dir': 'f"""{model_dir}/20210815"""', 'dataset': 'dataset_2', 'ts': '(40)', 'desc': '"""20210815 have models trained from v3-1-1 rebalanced. Models are trained 40 epochs."""'}), "(models_dir=f'{model_dir}/20210815', dataset=dataset_2, ts=40,\n desc=\n '20210815 have models trained from v3-1-1 rebalanced. Models are trained 40 epochs.'\n )\n", (13964, 14131), True, 'import utility as util\n'), ((14161, 14327), 'utility.AttrDict', 'util.AttrDict', ([], {'models_dir': 'f"""{model_dir}/20210816"""', 'dataset': 'dataset_3', 'desc': '"""20210816 have models trained from v3-1-2 (train set has 600 scenes) rebalanced."""'}), "(models_dir=f'{model_dir}/20210816', dataset=dataset_3, desc=\n '20210816 have models trained from v3-1-2 (train set has 600 scenes) rebalanced.'\n )\n", (14174, 14327), True, 'import utility as util\n'), ((1220, 1237), 'numpy.min', 'np.min', (['mean_ades'], {}), '(mean_ades)\n', (1226, 1237), True, 'import numpy as np\n'), ((1355, 1471), 'utility.AttrDict', 'util.AttrDict', ([], {'ph': 'ph', 'num_samples': 'n_predictions', 'z_mode': '(False)', 'gmm_mode': '(False)', 'full_dist': '(False)', 'all_z_sep': '(False)'}), '(ph=ph, num_samples=n_predictions, z_mode=False, gmm_mode=\n False, full_dist=False, all_z_sep=False)\n', (1368, 1471), True, 'import utility as util\n'), ((2025, 2133), 'helper.prediction_output_to_trajectories', 'prediction_output_to_trajectories', (['predictions'], {'dt': 'scene.dt', 'max_h': 'max_hl', 'ph': 'predictconfig.ph', 'map': 'None'}), '(predictions, dt=scene.dt, max_h=max_hl,\n ph=predictconfig.ph, map=None)\n', (2058, 2133), False, 'from helper import load_model, prediction_output_to_trajectories\n'), ((2810, 2871), 'tqdm.tqdm', 'tqdm', (['env.scenes'], {'desc': 'prefix', 'dynamic_ncols': '(True)', 'leave': '(True)'}), '(env.scenes, desc=prefix, dynamic_ncols=True, leave=True)\n', (2814, 2871), False, 'from tqdm import tqdm\n'), ((5464, 5514), 'numpy.linalg.norm', 'np.linalg.norm', (['(predicted_trajs - gt_traj)'], {'axis': '(-1)'}), '(predicted_trajs - gt_traj, axis=-1)\n', (5478, 5514), True, 'import numpy as np\n'), ((5525, 5548), 'numpy.mean', 'np.mean', (['error'], {'axis': '(-1)'}), '(error, axis=-1)\n', (5532, 5548), True, 'import numpy as np\n'), ((5636, 5700), 'numpy.linalg.norm', 'np.linalg.norm', (['(predicted_trajs[:, :, -1] - gt_traj[-1])'], {'axis': '(-1)'}), '(predicted_trajs[:, :, -1] - gt_traj[-1], axis=-1)\n', (5650, 5700), True, 'import numpy as np\n'), ((5921, 6023), 'utility.AttrDict', 'util.AttrDict', ([], {'ph': 'ph', 'num_samples': '(1)', 'z_mode': '(True)', 'gmm_mode': '(True)', 'full_dist': '(False)', 'all_z_sep': '(False)'}), '(ph=ph, num_samples=1, z_mode=True, gmm_mode=True, full_dist=\n False, all_z_sep=False)\n', (5934, 6023), True, 'import utility as util\n'), ((6581, 6689), 'helper.prediction_output_to_trajectories', 'prediction_output_to_trajectories', (['predictions'], {'dt': 'scene.dt', 'max_h': 'max_hl', 'ph': 'predictconfig.ph', 'map': 'None'}), '(predictions, dt=scene.dt, max_h=max_hl,\n ph=predictconfig.ph, map=None)\n', (6614, 6689), False, 'from helper import load_model, prediction_output_to_trajectories\n'), ((7366, 7427), 'tqdm.tqdm', 'tqdm', (['env.scenes'], {'desc': 'prefix', 'dynamic_ncols': '(True)', 'leave': '(True)'}), '(env.scenes, desc=prefix, dynamic_ncols=True, leave=True)\n', (7370, 7427), False, 'from tqdm import tqdm\n'), ((7896, 8009), 'utility.AttrDict', 'util.AttrDict', ([], {'ph': 'ph', 'num_samples': 'num_samples', 'z_mode': '(False)', 'gmm_mode': '(False)', 'full_dist': '(False)', 'all_z_sep': '(False)'}), '(ph=ph, num_samples=num_samples, z_mode=False, gmm_mode=False,\n full_dist=False, all_z_sep=False)\n', (7909, 8009), True, 'import utility as util\n'), ((8568, 8676), 'helper.prediction_output_to_trajectories', 'prediction_output_to_trajectories', (['predictions'], {'dt': 'scene.dt', 'max_h': 'max_hl', 'ph': 'predictconfig.ph', 'map': 'None'}), '(predictions, dt=scene.dt, max_h=max_hl,\n ph=predictconfig.ph, map=None)\n', (8601, 8676), False, 'from helper import load_model, prediction_output_to_trajectories\n'), ((9889, 9950), 'tqdm.tqdm', 'tqdm', (['env.scenes'], {'desc': 'prefix', 'dynamic_ncols': '(True)', 'leave': '(True)'}), '(env.scenes, desc=prefix, dynamic_ncols=True, leave=True)\n', (9893, 9950), False, 'from tqdm import tqdm\n'), ((11234, 11298), 'logging.info', 'logging.info', (['f"""Loading dataset: {dataset.name}: {dataset.desc}"""'], {}), "(f'Loading dataset: {dataset.name}: {dataset.desc}')\n", (11246, 11298), False, 'import logging\n'), ((14540, 14579), 'helper.load_model', 'load_model', (['model_path', 'eval_env'], {'ts': 'ts'}), '(model_path, eval_env, ts=ts)\n', (14550, 14579), False, 'from helper import load_model, prediction_output_to_trajectories\n'), ((15065, 15107), 'logging.info', 'logging.info', (['"""Evaluating each experiment"""'], {}), "('Evaluating each experiment')\n", (15077, 15107), False, 'import logging\n'), ((18145, 18188), 'logging.info', 'logging.info', (['"""done evaluating experiments"""'], {}), "('done evaluating experiments')\n", (18157, 18188), False, 'import logging\n'), ((18352, 18388), 'logging.info', 'logging.info', (['"""Evaluating baselines"""'], {}), "('Evaluating baselines')\n", (18364, 18388), False, 'import logging\n'), ((20697, 20738), 'logging.info', 'logging.info', (['"""Done evaluating baselines"""'], {}), "('Done evaluating baselines')\n", (20709, 20738), False, 'import logging\n'), ((21099, 21141), 'logging.info', 'logging.info', (['"""Run summarize experiments."""'], {}), "('Run summarize experiments.')\n", (21111, 21141), False, 'import logging\n'), ((26931, 26965), 'logging.info', 'logging.info', (['"""Generating tables."""'], {}), "('Generating tables.')\n", (26943, 26965), False, 'import logging\n'), ((29427, 29471), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '__doc__'}), '(description=__doc__)\n', (29450, 29471), False, 'import argparse\n'), ((1037, 1094), 'numpy.linalg.norm', 'np.linalg.norm', (['(predict[..., -1, :] - future[-1])'], {'axis': '(-1)'}), '(predict[..., -1, :] - future[-1], axis=-1)\n', (1051, 1094), True, 'import numpy as np\n'), ((1157, 1198), 'numpy.linalg.norm', 'np.linalg.norm', (['(predict - future)'], {'axis': '(-1)'}), '(predict - future, axis=-1)\n', (1171, 1198), True, 'import numpy as np\n'), ((1531, 1546), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (1544, 1546), False, 'import torch\n'), ((6083, 6098), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (6096, 6098), False, 'import torch\n'), ((8070, 8085), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (8083, 8085), False, 'import torch\n'), ((11367, 11398), 'dill.load', 'dill.load', (['f'], {'encoding': '"""latin1"""'}), "(f, encoding='latin1')\n", (11376, 11398), False, 'import dill\n'), ((15265, 15332), 'logging.info', 'logging.info', (['f"""Evaluating models in experiment: {experiment.desc}"""'], {}), "(f'Evaluating models in experiment: {experiment.desc}')\n", (15277, 15332), False, 'import logging\n'), ((15341, 15388), 'logging.info', 'logging.info', (['f"""Writing to: {results_filename}"""'], {}), "(f'Writing to: {results_filename}')\n", (15353, 15388), False, 'import logging\n'), ((15592, 15626), 'glob.glob', 'glob', (['f"""{experiment.models_dir}/*"""'], {}), "(f'{experiment.models_dir}/*')\n", (15596, 15626), False, 'from glob import glob\n'), ((18426, 18505), 'logging.info', 'logging.info', (['f"""Evaluating baseline on dataset: {dataset.name}: {dataset.desc}"""'], {}), "(f'Evaluating baseline on dataset: {dataset.name}: {dataset.desc}')\n", (18438, 18505), False, 'import logging\n'), ((18555, 18609), 'logging.info', 'logging.info', (['f"""Using baseline: {baseline_model.desc}"""'], {}), "(f'Using baseline: {baseline_model.desc}')\n", (18567, 18609), False, 'import logging\n'), ((18742, 18808), 'tqdm.tqdm', 'tqdm', (['eval_env.scenes'], {'desc': 'prefix', 'dynamic_ncols': '(True)', 'leave': '(True)'}), '(eval_env.scenes, desc=prefix, dynamic_ncols=True, leave=True)\n', (18746, 18808), False, 'from tqdm import tqdm\n'), ((21192, 21251), 'logging.info', 'logging.info', (['f"""Reading scores from H5 file {h5_filename}."""'], {}), "(f'Reading scores from H5 file {h5_filename}.')\n", (21204, 21251), False, 'import logging\n'), ((1610, 1636), 'numpy.arange', 'np.arange', (['scene.timesteps'], {}), '(scene.timesteps)\n', (1619, 1636), True, 'import numpy as np\n'), ((3314, 3353), 'numpy.max', 'np.max', (['map.data[..., :, :, :]'], {'axis': '(-3)'}), '(map.data[..., :, :, :], axis=-3)\n', (3320, 3353), True, 'import numpy as np\n'), ((6162, 6188), 'numpy.arange', 'np.arange', (['scene.timesteps'], {}), '(scene.timesteps)\n', (6171, 6188), True, 'import numpy as np\n'), ((8149, 8175), 'numpy.arange', 'np.arange', (['scene.timesteps'], {}), '(scene.timesteps)\n', (8158, 8175), True, 'import numpy as np\n'), ((16233, 16273), 'logging.info', 'logging.info', (['f"""Evaluating: {model_key}"""'], {}), "(f'Evaluating: {model_key}')\n", (16245, 16273), False, 'import logging\n'), ((19067, 19101), 'pandas.HDFStore', 'pd.HDFStore', (['results_filename', '"""a"""'], {}), "(results_filename, 'a')\n", (19078, 19101), True, 'import pandas as pd\n'), ((19510, 19544), 'pandas.HDFStore', 'pd.HDFStore', (['results_filename', '"""a"""'], {}), "(results_filename, 'a')\n", (19521, 19544), True, 'import pandas as pd\n'), ((21265, 21294), 'pandas.HDFStore', 'pd.HDFStore', (['h5_filename', '"""r"""'], {}), "(h5_filename, 'r')\n", (21276, 21294), True, 'import pandas as pd\n'), ((27477, 27506), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': 'headers'}), '(columns=headers)\n', (27489, 27506), True, 'import pandas as pd\n'), ((30284, 30320), 'logging.warning', 'logging.warning', (['"""No task selected."""'], {}), "('No task selected.')\n", (30299, 30320), False, 'import logging\n'), ((5025, 5092), 'scipy.stats.gaussian_kde', 'scipy.stats.gaussian_kde', (['predicted_trajs[batch_num, :, timestep].T'], {}), '(predicted_trajs[batch_num, :, timestep].T)\n', (5049, 5092), False, 'import scipy\n'), ((15944, 16010), 'tqdm.tqdm', 'tqdm', (['eval_env.scenes'], {'desc': 'prefix', 'dynamic_ncols': '(True)', 'leave': '(True)'}), '(eval_env.scenes, desc=prefix, dynamic_ncols=True, leave=True)\n', (15948, 16010), False, 'from tqdm import tqdm\n'), ((16397, 16431), 'pandas.HDFStore', 'pd.HDFStore', (['results_filename', '"""a"""'], {}), "(results_filename, 'a')\n", (16408, 16431), True, 'import pandas as pd\n'), ((16874, 16908), 'pandas.HDFStore', 'pd.HDFStore', (['results_filename', '"""a"""'], {}), "(results_filename, 'a')\n", (16885, 16908), True, 'import pandas as pd\n'), ((19246, 19273), 'pandas.DataFrame', 'pd.DataFrame', (['batch_metrics'], {}), '(batch_metrics)\n', (19258, 19273), True, 'import pandas as pd\n'), ((19697, 19724), 'pandas.DataFrame', 'pd.DataFrame', (['batch_metrics'], {}), '(batch_metrics)\n', (19709, 19724), True, 'import pandas as pd\n'), ((20181, 20215), 'pandas.HDFStore', 'pd.HDFStore', (['results_filename', '"""a"""'], {}), "(results_filename, 'a')\n", (20192, 20215), True, 'import pandas as pd\n'), ((20243, 20329), 'pandas.DataFrame', 'pd.DataFrame', (["{'fde': batch_metrics['fde'], 'ade': batch_metrics['ade'], 'ph': ph}"], {}), "({'fde': batch_metrics['fde'], 'ade': batch_metrics['ade'],\n 'ph': ph})\n", (20255, 20329), True, 'import pandas as pd\n'), ((20436, 20543), 'pandas.DataFrame', 'pd.DataFrame', (["{'kde': batch_metrics['kde'], 'offroad_viols': batch_metrics[\n 'offroad_viols'], 'ph': ph}"], {}), "({'kde': batch_metrics['kde'], 'offroad_viols': batch_metrics[\n 'offroad_viols'], 'ph': ph})\n", (20448, 20543), True, 'import pandas as pd\n'), ((21358, 21400), 'logging.info', 'logging.info', (['f"""Getting scores for {key}."""'], {}), "(f'Getting scores for {key}.')\n", (21370, 21400), False, 'import logging\n'), ((22120, 22156), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(2)', '(2)'], {'figsize': '(15, 15)'}), '(2, 2, figsize=(15, 15))\n', (22132, 22156), True, 'import matplotlib.pyplot as plt\n'), ((22186, 22222), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(2)', '(2)'], {'figsize': '(15, 15)'}), '(2, 2, figsize=(15, 15))\n', (22198, 22222), True, 'import matplotlib.pyplot as plt\n'), ((26107, 26140), 'logging.info', 'logging.info', (['""" saving plots."""'], {}), "(' saving plots.')\n", (26119, 26140), False, 'import logging\n'), ((26909, 26925), 'matplotlib.pyplot.close', 'plt.close', (['"""all"""'], {}), "('all')\n", (26918, 26925), True, 'import matplotlib.pyplot as plt\n'), ((27599, 27661), 'pandas.Series', 'pd.Series', (['{headers[0]: model_name, headers[1]: ALPHABET[idx]}'], {}), '({headers[0]: model_name, headers[1]: ALPHABET[idx]})\n', (27608, 27661), True, 'import pandas as pd\n'), ((27782, 27852), 'tabulate.tabulate', 'tabulate', (['model_df'], {'headers': '"""keys"""', 'showindex': '(False)', 'tablefmt': '"""simple"""'}), "(model_df, headers='keys', showindex=False, tablefmt='simple')\n", (27790, 27852), False, 'from tabulate import tabulate\n'), ((28559, 28588), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': 'headers'}), '(columns=headers)\n', (28571, 28588), True, 'import pandas as pd\n'), ((16588, 16615), 'pandas.DataFrame', 'pd.DataFrame', (['batch_metrics'], {}), '(batch_metrics)\n', (16600, 16615), True, 'import pandas as pd\n'), ((17073, 17100), 'pandas.DataFrame', 'pd.DataFrame', (['batch_metrics'], {}), '(batch_metrics)\n', (17085, 17100), True, 'import pandas as pd\n'), ((17593, 17627), 'pandas.HDFStore', 'pd.HDFStore', (['results_filename', '"""a"""'], {}), "(results_filename, 'a')\n", (17604, 17627), True, 'import pandas as pd\n'), ((17659, 17745), 'pandas.DataFrame', 'pd.DataFrame', (["{'fde': batch_metrics['fde'], 'ade': batch_metrics['ade'], 'ph': ph}"], {}), "({'fde': batch_metrics['fde'], 'ade': batch_metrics['ade'],\n 'ph': ph})\n", (17671, 17745), True, 'import pandas as pd\n'), ((17860, 17967), 'pandas.DataFrame', 'pd.DataFrame', (["{'kde': batch_metrics['kde'], 'offroad_viols': batch_metrics[\n 'offroad_viols'], 'ph': ph}"], {}), "({'kde': batch_metrics['kde'], 'offroad_viols': batch_metrics[\n 'offroad_viols'], 'ph': ph})\n", (17872, 17967), True, 'import pandas as pd\n'), ((22822, 22864), 'logging.info', 'logging.info', (['f""" scores for PH = {ph}."""'], {}), "(f' scores for PH = {ph}.')\n", (22834, 22864), False, 'import logging\n'), ((29246, 29316), 'tabulate.tabulate', 'tabulate', (['score_df'], {'headers': '"""keys"""', 'showindex': '(False)', 'tablefmt': '"""simple"""'}), "(score_df, headers='keys', showindex=False, tablefmt='simple')\n", (29254, 29316), False, 'from tabulate import tabulate\n'), ((28839, 28875), 'numpy.around', 'np.around', (['vvv[mean_key]'], {'decimals': '(2)'}), '(vvv[mean_key], decimals=2)\n', (28848, 28875), True, 'import numpy as np\n'), ((28923, 28944), 'numpy.sqrt', 'np.sqrt', (['vvv[var_key]'], {}), '(vvv[var_key])\n', (28930, 28944), True, 'import numpy as np\n')]
import os import sys from copy import deepcopy import time import random import numpy as np import itertools # Adding project folder to import modules import mod.env.Point root = os.getcwd().replace("\\", "/") sys.path.append(root) from mod.env.matching import ( service_trips, optimal_rebalancing, play_decisions, mpc, ) import mod.util.log_util as la from mod.env.amod.AmodNetworkHired import ( AmodNetworkHired, # exe_times, # decision_post, ) from mod.env.visual import StepLog, EpisodeLog import mod.env.adp.adp as adp import mod.env.visual as vi from mod.env.config import ConfigNetwork import mod.env.config as conf from mod.env.fleet.Car import Car from mod.env.demand.trip_util import get_trip_count_step, get_trips_random_ods import mod.env.demand.trip_util as tp import mod.env.network as nw from mod.env.simulator import PlotTrack # Reproducibility of the experiments random.seed(1) def get_sim_config(update_dict): config = ConfigNetwork() # Pull graph info ( region, label, node_count, center_count, edge_count, region_type, ) = nw.query_info() info = ( "##############################################################" f"\n### Region: {region} G(V={node_count}, E={edge_count})" f"\n### Center count: {center_count}" f"\n### Region type: {region_type}" ) level_id_count_dict = { int(level): (i + 1, count) for i, (level, count) in enumerate(center_count.items()) } level_id_count_dict[0] = (0, node_count) print(info) # ---------------------------------------------------------------- # # Amod environment ############################################### # # ---------------------------------------------------------------- # config.update( { ConfigNetwork.TEST_LABEL: "HUGE", # Fleet ConfigNetwork.FLEET_SIZE: 5, ConfigNetwork.FLEET_START: conf.FLEET_START_LAST, ConfigNetwork.BATTERY_LEVELS: 1, # Time - Increment (min) ConfigNetwork.TIME_INCREMENT: 1, ConfigNetwork.OFFSET_REPOSITIONING_MIN: 15, ConfigNetwork.OFFSET_TERMINATION_MIN: 60, # -------------------------------------------------------- # # NETWORK ################################################ # # -------------------------------------------------------- # ConfigNetwork.NAME: label, ConfigNetwork.REGION: region, ConfigNetwork.NODE_COUNT: node_count, ConfigNetwork.EDGE_COUNT: edge_count, ConfigNetwork.CENTER_COUNT: center_count, # Region centers are created in steps of how much time? ConfigNetwork.STEP_SECONDS: 15, # Cars can access locations within region centers # established in which neighborhood level? ConfigNetwork.NEIGHBORHOOD_LEVEL: 0, # Penalize rebalancing by subtracting the potential # profit accrued by staying still during the rebalance # process. ConfigNetwork.PENALIZE_REBALANCE: False, # Cars rebalance to up to #region centers at each level # CAUTION! Change max_neighbors in tenv application if > 4 ConfigNetwork.N_CLOSEST_NEIGHBORS: ((0, 8), (1, 8)), # Only used when max idle step count is not None ConfigNetwork.N_CLOSEST_NEIGHBORS_EXPLORE: ((2, 16), (3, 16)), # ConfigNetwork.REBALANCE_REACH: 2, ConfigNetwork.REBALANCE_MULTILEVEL: False, ConfigNetwork.LEVEL_DIST_LIST: [0, 150, 300, 600], # Aggregation (temporal, spatial, contract, car type) # # FAVs and PAVS BEST HIERARCHICAL AGGREGATION # ConfigNetwork.AGGREGATION_LEVELS: [ # adp.AggLevel( # temporal=1, # spatial=0, # battery=adp.DISAGGREGATE, # contract=2, # car_type=adp.DISAGGREGATE, # car_origin=adp.DISAGGREGATE, # ), # adp.AggLevel( # temporal=1, # spatial=0, # battery=adp.DISAGGREGATE, # contract=3, # car_type=adp.DISAGGREGATE, # car_origin=3, # ), # adp.AggLevel( # temporal=1, # spatial=0, # battery=adp.DISAGGREGATE, # contract=adp.DISCARD, # car_type=adp.DISAGGREGATE, # car_origin=adp.DISCARD, # ), # adp.AggLevel( # temporal=3, # spatial=2, # battery=adp.DISAGGREGATE, # contract=adp.DISCARD, # car_type=adp.DISAGGREGATE, # car_origin=adp.DISCARD, # ), # adp.AggLevel( # temporal=3, # spatial=3, # battery=adp.DISAGGREGATE, # contract=adp.DISCARD, # car_type=adp.DISAGGREGATE, # car_origin=adp.DISCARD, # ), # ], # #### ONLY PAVs - BEST PERFORMANCE HiERARCHICAL AGGREGATION # ConfigNetwork.AGGREGATION_LEVELS: [ # adp.AggLevel( # temporal=1, # spatial=adp.DISAGGREGATE, # battery=adp.DISAGGREGATE, # contract=adp.DISCARD, # car_type=adp.DISAGGREGATE, # car_origin=adp.DISCARD, # ), # adp.AggLevel( # temporal=3, # spatial=2, # battery=adp.DISAGGREGATE, # contract=adp.DISCARD, # car_type=adp.DISAGGREGATE, # car_origin=adp.DISCARD, # ), # adp.AggLevel( # temporal=3, # spatial=3, # battery=adp.DISAGGREGATE, # contract=adp.DISCARD, # car_type=adp.DISAGGREGATE, # car_origin=adp.DISCARD, # ), # ], # #### ONLY PAVs - BEST PERFORMANCE HiERARCHICAL AGGREGATION ConfigNetwork.AGGREGATION_LEVELS: [ # adp.AggLevel( # temporal=1, # spatial=adp.DISAGGREGATE, # battery=adp.DISAGGREGATE, # contract=adp.DISCARD, # car_type=adp.DISAGGREGATE, # car_origin=adp.DISCARD, # ), adp.AggLevel( temporal=0, spatial=1, battery=adp.DISAGGREGATE, contract=adp.DISCARD, car_type=adp.DISAGGREGATE, car_origin=adp.DISCARD, ), adp.AggLevel( temporal=1, spatial=2, battery=adp.DISAGGREGATE, contract=adp.DISCARD, car_type=adp.DISAGGREGATE, car_origin=adp.DISCARD, ), adp.AggLevel( temporal=2, spatial=3, battery=adp.DISAGGREGATE, contract=adp.DISCARD, car_type=adp.DISAGGREGATE, car_origin=adp.DISCARD, ), ], # ConfigNetwork.LEVEL_TIME_LIST: [0.5, 1, 2, 3], # TIME LIST multiplies the time increment. E.g.: # time increment=5 then [1,2] = [5, 10] # time increment=1 then [1,3] = [1, 3] ConfigNetwork.LEVEL_TIME_LIST: [1, 2, 3], ConfigNetwork.LEVEL_CAR_ORIGIN: { Car.TYPE_FLEET: {adp.DISCARD: adp.DISCARD}, Car.TYPE_HIRED: {0: 0, 1: 1, 2: 2, 3: 3, 4: 4}, }, ConfigNetwork.LEVEL_CAR_TYPE: { Car.TYPE_FLEET: { adp.DISAGGREGATE: Car.TYPE_FLEET, adp.DISCARD: Car.TYPE_FLEET, }, Car.TYPE_HIRED: { adp.DISAGGREGATE: Car.TYPE_HIRED, adp.DISCARD: Car.TYPE_FLEET, }, }, ConfigNetwork.LEVEL_CONTRACT_DURATION: { Car.TYPE_FLEET: {adp.DISCARD: Car.INFINITE_CONTRACT_DURATION}, Car.TYPE_HIRED: { adp.DISAGGREGATE: adp.CONTRACT_DISAGGREGATE, 1: adp.CONTRACT_L1, 2: adp.CONTRACT_L2, 3: adp.CONTRACT_L3, adp.DISCARD: Car.INFINITE_CONTRACT_DURATION, }, }, # From which region center levels cars are hired ConfigNetwork.LEVEL_RC: 5, # Trips and cars have to match in these levels # 9 = 990 and 10=1140 ConfigNetwork.MATCHING_LEVELS: (0, 0), # How many levels separated by step secresize_factorc # LEVEL_DIST_LIST must be filled (1=disaggregate) ConfigNetwork.SPEED: 20, # -------------------------------------------------------- # # DEMAND ################################################# # # -------------------------------------------------------- # ConfigNetwork.DEMAND_TOTAL_HOURS: 4, ConfigNetwork.DEMAND_EARLIEST_HOUR: 5, ConfigNetwork.DEMAND_RESIZE_FACTOR: 0.1, ConfigNetwork.DEMAND_SAMPLING: True, # Demand spawn from how many centers? ConfigNetwork.ORIGIN_CENTERS: 3, # Demand arrives in how many centers? ConfigNetwork.DESTINATION_CENTERS: 3, # OD level extension ConfigNetwork.DEMAND_CENTER_LEVEL: 0, # Demand scenario ConfigNetwork.DEMAND_SCENARIO: conf.SCENARIO_NYC, ConfigNetwork.TRIP_REJECTION_PENALTY: (("A", 0), ("B", 0)), ConfigNetwork.TRIP_BASE_FARE: (("A", 4.8), ("B", 2.4)), ConfigNetwork.TRIP_DISTANCE_RATE_KM: (("A", 1), ("B", 1)), ConfigNetwork.TRIP_TOLERANCE_DELAY_MIN: (("A", 5), ("B", 5)), ConfigNetwork.TRIP_MAX_PICKUP_DELAY: (("A", 5), ("B", 10)), ConfigNetwork.TRIP_CLASS_PROPORTION: (("A", 0), ("B", 1)), # -------------------------------------------------------- # # LEARNING ############################################### # # -------------------------------------------------------- # ConfigNetwork.DISCOUNT_FACTOR: 0.1, ConfigNetwork.HARMONIC_STEPSIZE: 1, ConfigNetwork.STEPSIZE_CONSTANT: 0.1, ConfigNetwork.STEPSIZE_RULE: adp.STEPSIZE_MCCLAIN, # ConfigNetwork.STEPSIZE_RULE: adp.STEPSIZE_CONSTANT, # -------------------------------------------------------- # # HIRING ################################################# # # -------------------------------------------------------- # ConfigNetwork.CONTRACT_DURATION_LEVEL: 1, ConfigNetwork.CONGESTION_PRICE: 0, # -------------------------------------------------------- # ConfigNetwork.MATCH_METHOD: ConfigNetwork.MATCH_DISTANCE, ConfigNetwork.MATCH_LEVEL: 2, ConfigNetwork.MAX_TARGETS: 1000, } ) config.update(update_dict) return config def alg_adp( plot_track, config, # PLOT ########################################################### # step_delay=PlotTrack.STEP_DELAY, # LOG ############################################################ # skip_steps=1, # TRIPS ########################################################## # classed_trips=True, # Create service rate and fleet status plots for each iteration save_plots=True, # Save .csv files for each iteration with fleet and demand statuses # throughtout all time steps save_df=True, # Save total reward, total service rate, and weights after iteration save_overall_stats=True, log_config_dict={ # Write each vehicles status la.LOG_FLEET_ACTIVITY: False, # Write profit, service level, # trips, car/satus count la.LOG_STEP_SUMMARY: True, # ############# ADP ############################################ # Log duals update process la.LOG_DUALS: False, la.LOG_VALUE_UPDATE: False, la.LOG_COSTS: False, la.LOG_SOLUTIONS: False, la.LOG_WEIGHTS: False, # Log .lp and .log from MIP models la.LOG_MIP: False, # Log time spent across every step in each code section la.LOG_TIMES: False, # Save fleet, demand, and delay plots la.SAVE_PLOTS: False, # Save fleet and demand dfs for live plot la.SAVE_DF: False, # Log level saved in file la.LEVEL_FILE: la.DEBUG, # Log level printed in screen la.LEVEL_CONSOLE: la.INFO, la.FORMATTER_FILE: la.FORMATTER_TERSE, # Log everything la.LOG_ALL: False, # Log chosen (if LOG_ALL, set to lowest, i.e., DEBUG) la.LOG_LEVEL: la.INFO, }, ): # Set tabu size (vehicles cannot visit nodes in tabu) Car.SIZE_TABU = config.car_size_tabu print(f'### Saving experimental settings at: "{config.exp_settings}"') config.save() # ---------------------------------------------------------------- # # Episodes ####################################################### # # ---------------------------------------------------------------- # amod = AmodNetworkHired(config, online=True) print( f"### Nodes with no neighbors (within time increment) " f"({len(amod.unreachable_ods)})" f" = {amod.unreachable_ods}" f" --- #neighbors (avg, max, min) = {amod.stats_neighbors}" ) episode_log = EpisodeLog( amod.config.save_progress, config=config, adp=amod.adp ) if plot_track: plot_track.set_env(amod) # ---------------------------------------------------------------- # # Plot centers and guidelines #################################### # # ---------------------------------------------------------------- # if plot_track: plot_track.plot_centers( amod.points, mod.env.Point.Point.levels, mod.env.Point.Point.levels[config.demand_center_level], mod.env.Point.Point.levels[config.neighborhood_level], show_sp_lines=PlotTrack.SHOW_SP_LINES, show_lines=PlotTrack.SHOW_LINES, ) if config.use_class_prob: try: print( "### Loading first-class probabilities " f"from '{config.path_class_prob}'..." ) prob_dict = np.load( config.path_class_prob, allow_pickle=True ).item() time_bin = prob_dict["time_bin"] start_time = prob_dict["start"] end_time = prob_dict["end"] print(f"### bin={time_bin}, start={start_time}, end={end_time}") except Exception as e: print(f"Exception: '{e}'. Cannot load class probabilities.") else: prob_dict = None print(f"### Loading demand scenario '{config.demand_scenario}'...") try: if config.myopic or config.policy_random or config.policy_reactive: print("Ignore training.") else: # Load last episode episode_log.load_progress() print("Data loaded successfully.") except Exception as e: print(f"No previous episodes were saved (Exception: '{e}').") # ---------------------------------------------------------------- # # Process demand ################################################# # # ---------------------------------------------------------------- # if config.demand_scenario == conf.SCENARIO_UNBALANCED: origins, destinations = episode_log.get_od_lists(amod) # Get demand pattern from NY city step_trip_count = get_trip_count_step( conf.TRIP_FILES[0], step=config.time_increment, multiply_for=config.demand_resize_factor, earliest_step=config.demand_earliest_step_min, max_steps=config.demand_max_steps, ) # ---------------------------------------------------------------- # # Experiment ##################################################### # # ---------------------------------------------------------------- # # Loop all episodes, pick up trips, and learn where they are if config.method == ConfigNetwork.METHOD_ADP_TRAIN: start = episode_log.n else: start = 0 print(f" - Iterating from {start:>4} to {config.iterations:>4}...") for n in range(start, config.iterations): config.current_iteration = n t_update = 0 t_mip = 0 t_log = 0 t_save_plots = 0 t_add_record = 0 if config.demand_scenario == conf.SCENARIO_UNBALANCED: # Sample ods for iteration n step_trip_list = get_trips_random_ods( amod.points, step_trip_count, offset_start=amod.config.offset_repositioning_steps, offset_end=amod.config.offset_termination_steps, origins=origins, destinations=destinations, classed=classed_trips, ) elif config.demand_scenario == conf.SCENARIO_NYC: # Load a random .csv file with trips from NYC if config.train: folder = config.folder_training_files list_files = conf.get_file_paths(folder) trips_file_path = random.choice(list_files) test_i = n # print(f" -> Trip file - {trips_file_path}") else: folder = config.folder_testing_files list_files = conf.get_file_paths(folder) # If testing, select different trip files test_i = n % len(list_files) trips_file_path = list_files[test_i] # print(f" -> Trip file test ({test_i:02}) - {trips_file_path}") step_trip_list, step_trip_count = tp.get_ny_demand( config, trips_file_path, amod.points, seed=n, prob_dict=prob_dict, centroid_level=amod.config.centroid_level, unreachable_ods=amod.unreachable_ods, ) # Save random data (trip samples) if amod.config.save_trip_data: df = tp.get_df_from_sampled_trips(step_trip_list) df.to_csv( f"{config.sampled_tripdata_path}trips_{test_i:04}.csv", index=False, ) if amod.config.unbound_max_cars_trip_destinations: # Trip destination ids are unrestricted, i.e., cars can # always arrive at destinations all_trips = list(itertools.chain(*step_trip_list)) id_destinations = set([t.d.id for t in all_trips]) amod.unrestricted_parking_node_ids = id_destinations else: amod.unrestricted_parking_node_ids = set() # Log events of iteration n logger = la.get_logger( config.log_path(amod.adp.n), log_file=config.log_path(amod.adp.n), **log_config_dict, ) logger.debug( "##################################" f" Iteration {n:04} " f"- Demand (min={min(step_trip_count)}" f", max={max(step_trip_count)})" f", step={config.time_increment}" f", earliest_step={config.demand_earliest_step_min}" f", max_steps={config.demand_max_steps}" f", offset_start={amod.config.offset_repositioning_steps}" f", offset_end={amod.config.offset_termination_steps}" f", steps={amod.config.time_steps}" ) if plot_track: plot_track.opt_episode = n # Start saving data of each step in the adp_network step_log = StepLog(amod) # Resetting environment amod.reset(seed=n) # Save random data (initial positions) if amod.config.save_fleet_data: # Save car distribution df_cars = amod.get_fleet_df() df_cars.to_csv( f"{config.fleet_data_path}cars_{test_i:04}.csv", index=False ) # ------------------------------------------------------------ # # Plot fleet current status ################################## # # ------------------------------------------------------------ # if plot_track: # Computing initial timestep plot_track.compute_movements(0) start_time = time.time() # Outstanding trips between steps (user backlogging) outstanding = list() # Trips from this iteration (make sure it can be used again) it_step_trip_list = deepcopy(step_trip_list) # Get decisions for optimal rebalancing new_fleet_size = None if config.method == ConfigNetwork.METHOD_OPTIMAL: ( it_decisions, it_step_trip_list, new_fleet_size, ) = optimal_rebalancing( amod, it_step_trip_list, log_mip=log_config_dict[la.LOG_MIP] ) print(f"MPC optimal fleet size: {new_fleet_size}") if ( log_config_dict[la.SAVE_PLOTS] or log_config_dict[la.SAVE_DF] or log_config_dict[la.LOG_STEP_SUMMARY] ): logger.debug(" - Computing fleet status...") # Compute fleet status after making decision in step - 1 # What each car is doing when trips are arriving? step_log.compute_fleet_status() # When step=0, no users have come from previous round # step_log.add_record(0, [], []) total_trips = 0 # Iterate through all steps and match requests to cars for step, trip_list in enumerate(it_step_trip_list): # print(exe_times, len(decision_post)) config.current_step = step # Add trips from last step (when user backlogging is enabled) trips = trip_list + outstanding outstanding = [] if plot_track: # Update optimization time step plot_track.opt_step = step # Create trip dictionary of coordinates plot_track.trips_dict[step] = vi.compute_trips(trips) # ######################################################## # # TIME INCREMENT HAS PASSED ############################## # # ######################################################## # if amod.config.fav_fleet_size > 0: hired_cars = amod.step_favs.get(step, []) # Add hired fleet to model amod.hired_cars.extend(hired_cars) amod.available_hired.extend(hired_cars) amod.overall_hired.extend(hired_cars) # Loop cars and update their current status as well as the # the list of available vehicles (change available and # available_hired) t1 = time.time() # If policy is reactive, rebalancing cars can be rerouted # from the intermediate nodes along the shortest path # to the rebalancing target. Notice that, if level > 0, # miiddle points will correspond to corresponding hierarchi- # cal superior node. amod.update_fleet_status( step + 1, use_rebalancing_cars=amod.config.policy_reactive ) t_update += time.time() - t1 # Show the top highest vehicle count per position # amod.show_count_vehicles_top(step, 5) t1 = time.time() logger.debug("\n## Car attributes:") # Log both fleets for c in itertools.chain(amod.cars, amod.hired_cars): logger.debug(f"{c} - {c.attribute}") # What each vehicle is doing after update? la.log_fleet_activity( config.log_path(amod.adp.n), step + 1, skip_steps, step_log, filter_status=[], msg="post update", ) t_log += time.time() - t1 t1 = time.time() if config.policy_optimal: # print( # f"it={step:04} - Playing decisions {len(it_decisions[step])}" # ) revenue, serviced, rejected = play_decisions( amod, trips, step + 1, it_decisions[step] ) # ######################################################## # # METHOD - MPC - HORIZON ################################# # # ######################################################## # elif config.policy_mpc: # Predicted trips for next steps (exclusive) predicted_trips = it_step_trip_list[ step + 1 : step + amod.config.mpc_forecasting_horizon ] # Log events of iteration n logger = la.get_logger( config.log_path(step + 1), log_file=config.log_path(step + 1), **log_config_dict, ) # Trips within the same region are invalid decisions = mpc( # Amod environment with configuration file amod, # Trips to be matched trips, # Predicted trips within the forecasting horizon predicted_trips, # Service step (+1 trip placement step) step=step + 1, log_mip=log_config_dict[la.LOG_MIP], ) revenue, serviced, rejected = play_decisions( amod, trips, step + 1, decisions ) else: revenue, serviced, rejected = service_trips( # Amod environment with configuration file amod, # Trips to be matched trips, # Service step (+1 trip placement step) step + 1, # Save mip .lp and .log of iteration n iteration=n, log_mip=log_config_dict[la.LOG_MIP], log_times=log_config_dict[la.LOG_TIMES], car_type_hide=Car.TYPE_FLEET, ) if amod.config.separate_fleets: # Optimize revenue_fav, serviced_fav, rejected_fav = service_trips( # Amod environment with configuration file amod, # Trips to be matched rejected, # Service step (+1 trip placement step) step + 1, # Save mip .lp and .log of iteration n iteration=n, car_type_hide=Car.TYPE_FLEET, log_times=log_config_dict[la.LOG_TIMES], log_mip=log_config_dict[la.LOG_MIP], ) revenue += (revenue_fav,) serviced += (serviced_fav,) rejected = rejected_fav # ######################################################## # # METHOD - BACKLOG ####################################### # # ######################################################## # if amod.config.max_user_backlogging_delay > 0: expired = [] for r in rejected: # Add time increment to backlog delay r.backlog_delay += amod.config.time_increment r.times_backlogged += 1 # Max. backlog reached -> discard trip if ( r.backlog_delay > amod.config.max_user_backlogging_delay or step + 1 == amod.config.time_steps ): expired.append(r) else: outstanding.append(r) rejected = expired t_mip += time.time() - t1 # ######################################################## # # METHOD - REACTIVE REBALANCE ############################ # # ######################################################## # t_reactive_rebalance_1 = time.time() if amod.config.policy_reactive and (rejected or outstanding): # If reactive rebalance, send vehicles to rejected # user's origins logger.debug( "####################" f"[{n:04}]-[{step:04}] REACTIVE REBALANCE " "####################" ) logger.debug("Rejected requests (rebalancing targets):") for r in rejected: logger.debug(f"{r}") # print(step, amod.available_fleet_size, len(rejected)) # Update fleet headings to isolate Idle vehicles. # Only empty cars are considered for rebalancing. t1 = time.time() amod.update_fleet_status(step + 1) t_update += time.time() - t1 t1 = time.time() # What each vehicle is doing? la.log_fleet_activity( config.log_path(amod.adp.n), step, skip_steps, step_log, filter_status=[], msg="before rebalancing", ) t_log += time.time() - t1 # Service idle vehicles rebal_costs, _, _ = service_trips( # Amod environment with configuration file amod, # Trips to be matched rejected + outstanding, # Service step (+1 trip placement step) step + 1, # # Save mip .lp and .log of iteration n iteration=n, log_mip=log_config_dict[la.LOG_MIP], log_times=log_config_dict[la.LOG_TIMES], car_type_hide=Car.TYPE_FLEET, reactive=True, ) revenue -= rebal_costs logger.debug(f"\n# REB. COSTS: {rebal_costs:6.2f}") t_reactive_rebalance = time.time() - t_reactive_rebalance_1 t1 = time.time() if ( log_config_dict[la.SAVE_PLOTS] or log_config_dict[la.SAVE_DF] or log_config_dict[la.LOG_STEP_SUMMARY] ): logger.debug(" - Computing fleet status...") # Compute fleet status after making decision in step - 1 # What each car is doing when trips are arriving? step_log.compute_fleet_status() t_save_plots += time.time() - t1 t1 = time.time() # -------------------------------------------------------- # # Update log with iteration ############################## # # -------------------------------------------------------- # step_log.add_record( revenue, serviced, rejected, outstanding, trips=trips ) t_add_record += time.time() - t1 # -------------------------------------------------------- # # Plotting fleet activity ################################ # # -------------------------------------------------------- # t1 = time.time() # What each vehicle is doing? la.log_fleet_activity( config.log_path(amod.adp.n), step, skip_steps, step_log, filter_status=[], msg="after decision", ) t_log += time.time() - t1 if plot_track: logger.debug("Computing movements...") plot_track.compute_movements(step + 1) logger.debug("Finished computing...") time.sleep(step_delay) # print(step, "weighted value:", amod.adp.get_weighted_value.cache_info()) # print(step, "preview decision:", amod.preview_decision.cache_info()) # print(step, "preview decision:", amod.preview_move.cache_info()) # amod.adp.get_weighted_value.cache_clear() # self.post_cost.cache_clear() # LAST UPDATE (Closing the episode) t1 = time.time() amod.update_fleet_status(step + 1) t_update += time.time() - t1 # Save random data (fleet and trips) if amod.config.save_trip_data: df = tp.get_df_from_sampled_trips( it_step_trip_list, show_service_data=True, earliest_datetime=config.demand_earliest_datetime, ) df.to_csv( f"{config.sampled_tripdata_path}trips_{test_i:04}_result.csv", index=False, ) if amod.config.save_fleet_data: df_cars = amod.get_fleet_df() df_cars.to_csv( f"{config.fleet_data_path}cars_{test_i:04}_result.csv", index=False, ) # -------------------------------------------------------------# # Compute episode info ######################################### # -------------------------------------------------------------# logger.debug(" - Computing iteration...") t1 = time.time() episode_log.compute_episode( step_log, it_step_trip_list, time.time() - start_time, fleet_size=new_fleet_size, save_df=log_config_dict[la.SAVE_DF], plots=log_config_dict[la.SAVE_PLOTS], save_learning=amod.config.save_progress, save_overall_stats=save_overall_stats, ) t_epi = t1 = time.time() - t1 # Clean weight track amod.adp.reset_weight_track() logger.info( f"####### " f"[Episode {n+1:>5}] " f"- {episode_log.last_episode_stats()} " f"serviced={step_log.serviced}, " f"rejected={step_log.rejected}, " f"total={step_log.total} " f"t(episode={t_epi:.2f}, " f"t_log={t_log:.2f}, " f"t_mip={t_mip:.2f}, " f"t_save_plots={t_save_plots:.2f}, " f"t_up={t_update:.2f}, " f"t_add_record={t_add_record:.2f})" f"#######" ) # If True, saves time details in file times.csv # if log_config_dict[la.LOG_TIMES]: # logger.debug("weighted values:", len(amod.adp.weighted_values)) # logger.debug("get_state:", amod.adp.get_state.cache_info()) # logger.debug( # "preview_decision:", amod.preview_decision.cache_info() # ) # logger.debug(f"Rebalance: {amod.get_zone_neighbors.cache_info()}") # logger.debug("post_cost:", amod.post_cost.cache_info()) # Increasingly let cars to be idle if config.idle_annealing is not None: # By the end of all iterations, cars cannot be forced to # rebalance anymore config.config[ConfigNetwork.IDLE_ANNEALING] += 1 # 1/episodes # pprint({k:v for k, v in amod.beta_ab.items() if v["a"]>2}) # Plot overall performance (reward, service rate, and weights) episode_log.compute_learning() return amod.adp.reward if __name__ == "__main__": instance_name = None # instance_name = f"{conf.FOLDER_OUTPUT}BA_LIN_C1_V=0400-0000(R)_I=5_L[3]=(01-0-, 02-0-, 03-0-)_R=([1-6][L(05)]_T=[06h,+30m+06h+30m]_0.10(S)_1.00_0.10_A_2.40_10.00_0.00_0.00_0.00_B_2.40_10.00_0.00_0.00_1.00/exp_settings.json" if instance_name: log_mip = False log_times = False save_plots = False save_df = False log_all = False log_level = la.INFO print(f'Loading settings from "{instance_name}"') start_config = ConfigNetwork.load(instance_name) else: # Default is training method = ConfigNetwork.METHOD_ADP_TEST save_progress_interval = None # Isolate arguments (first is filename) args = sys.argv[1:] try: test_label = args[0] except: test_label = "TESTDE" try: iterations = args.index("-n") n_iterations = int(args[iterations + 1]) except: n_iterations = 400 try: ibacklog = args.index("-backlog") backlog_delay_min = int(args[ibacklog + 1]) except: backlog_delay_min = 0 # Enable logs log_all = "-log_all" in args log_mip = "-log_mip" in args log_times = "-log_times" in args log_fleet = "-log_fleet" in args log_trips = "-log_trips" in args log_summary = "-log_summary" in args # Save supply and demand plots and dataframes save_plots = "-save_plots" in args save_df = "-save_df" in args # Optimization methods myopic = "-myopic" in args policy_random = "-random" in args policy_reactive = "-reactive" in args train = "-train" in args test = "-test" in args optimal = "-optimal" in args policy_mpc = "-mpc" in args mpc_horizon = 5 # Progress file will be updated every X iterations save_progress_interval = None if policy_random: method = ConfigNetwork.METHOD_RANDOM elif policy_reactive: method = ConfigNetwork.METHOD_REACTIVE elif myopic: method = ConfigNetwork.METHOD_MYOPIC elif train: method = ConfigNetwork.METHOD_ADP_TRAIN try: i = int(args.index("-train")) save_progress_interval = int(args[i + 1]) except: save_progress_interval = 1 elif test: method = ConfigNetwork.METHOD_ADP_TEST elif optimal: method = ConfigNetwork.METHOD_OPTIMAL n_iterations = 1 elif policy_mpc: method = ConfigNetwork.METHOD_MPC try: i = int(args.index("-mpc")) mpc_horizon = int(args[i + 1]) except: mpc_horizon = 5 n_iterations = 1 else: raise ("Error! Which method?") print( f"### method={method}, save progress={(save_progress_interval if save_progress_interval else 'no')}" ) try: fleet_size_i = args.index(f"-{ConfigNetwork.FLEET_SIZE}") fleet_size = int(args[fleet_size_i + 1]) except: fleet_size = 100 try: fav_fleet_size_i = args.index(f"-{ConfigNetwork.FAV_FLEET_SIZE}") fav_fleet_size = int(args[fav_fleet_size_i + 1]) except: fav_fleet_size = 0 try: log_level_i = args.index("-level") log_level_label = args[log_level_i + 1] log_level = la.levels[log_level_label] except: log_level = la.INFO print(f"###### STARTING EXPERIMENTS. METHOD: {method}") start_config = get_sim_config( { # ConfigNetwork.CASE_STUDY: "N08Z08SD02", ConfigNetwork.CASE_STUDY: "N08Z08CD02", # Cars can rebalance/stay/travel to trip destinations # indiscriminately ConfigNetwork.UNBOUND_MAX_CARS_TRIP_DESTINATIONS: False, # All trip decisions can be realized ConfigNetwork.UNBOUND_MAX_CARS_TRIP_DECISIONS: True, ConfigNetwork.PATH_CLASS_PROB: "distr/class_prob_distribution_p5min_6h.npy", ConfigNetwork.ITERATIONS: n_iterations, ConfigNetwork.TEST_LABEL: test_label, ConfigNetwork.DISCOUNT_FACTOR: 1, ConfigNetwork.FLEET_SIZE: fleet_size, # DEMAND ############################################# # ConfigNetwork.UNIVERSAL_SERVICE: False, ConfigNetwork.DEMAND_RESIZE_FACTOR: 0.1, ConfigNetwork.DEMAND_TOTAL_HOURS: 6, ConfigNetwork.DEMAND_EARLIEST_HOUR: 6, ConfigNetwork.OFFSET_TERMINATION_MIN: 30, ConfigNetwork.OFFSET_REPOSITIONING_MIN: 30, ConfigNetwork.TIME_INCREMENT: 5, ConfigNetwork.DEMAND_SAMPLING: True, # Service quality ConfigNetwork.MATCHING_DELAY: 15, ConfigNetwork.MAX_USER_BACKLOGGING_DELAY: backlog_delay_min, ConfigNetwork.SQ_GUARANTEE: False, ConfigNetwork.RECHARGE_COST_DISTANCE: 0.1, ConfigNetwork.APPLY_BACKLOG_REJECTION_PENALTY: True, ConfigNetwork.TRIP_REJECTION_PENALTY: (("A", 2.5), ("B", 2.5)), ConfigNetwork.TRIP_OUTSTANDING_PENALTY: ( ("A", 0.25), ("B", 0.25), ), ConfigNetwork.TRIP_BASE_FARE: (("A", 7.5), ("B", 2.5)), ConfigNetwork.TRIP_DISTANCE_RATE_KM: (("A", 1), ("B", 1)), ConfigNetwork.TRIP_TOLERANCE_DELAY_MIN: (("A", 0), ("B", 0)), ConfigNetwork.TRIP_MAX_PICKUP_DELAY: (("A", 15), ("B", 15)), ConfigNetwork.TRIP_CLASS_PROPORTION: (("A", 0), ("B", 1)), # ADP EXECUTION ###################################### # ConfigNetwork.METHOD: method, ConfigNetwork.SAVE_PROGRESS: save_progress_interval, ConfigNetwork.ADP_IGNORE_ZEROS: True, ConfigNetwork.LINEARIZE_INTEGER_MODEL: False, ConfigNetwork.USE_ARTIFICIAL_DUALS: False, # MPC ################################################ # ConfigNetwork.MPC_FORECASTING_HORIZON: mpc_horizon, ConfigNetwork.MPC_USE_PERFORMANCE_TO_GO: False, ConfigNetwork.MPC_REBALANCE_TO_NEIGHBORS: False, ConfigNetwork.MPC_USE_TRIP_ODS_ONLY: True, # EXPLORATION ######################################## # # ANNEALING + THOMPSON # If zero, cars increasingly gain the right of stay # still. This obliges them to rebalance consistently. # If None, disabled. ConfigNetwork.IDLE_ANNEALING: None, ConfigNetwork.ACTIVATE_THOMPSON: False, ConfigNetwork.MAX_TARGETS: 12, # When cars start in the last visited point, the model takes # a long time to figure out the best time ConfigNetwork.FLEET_START: conf.FLEET_START_RANDOM, # ConfigNetwork.FLEET_START: conf.FLEET_START_REJECTED_TRIP_ORIGINS, # ConfigNetwork.FLEET_START: conf.FLEET_START_PARKING_LOTS, # ConfigNetwork.LEVEL_PARKING_LOTS: 2, # ConfigNetwork.FLEET_START: conf.FLEET_START_LAST_TRIP_ORIGINS, ConfigNetwork.CAR_SIZE_TABU: 0, # REBALANCING ########################################## # If REACHABLE_NEIGHBORS is True, then PENALIZE_REBALANCE # is False ConfigNetwork.PENALIZE_REBALANCE: False, # All rebalancing finishes within time increment ConfigNetwork.REBALANCING_TIME_RANGE_MIN: (0, 10), # Consider only rebalance targets from sublevel ConfigNetwork.REBALANCE_SUB_LEVEL: None, # Rebalance to at most max targets ConfigNetwork.REBALANCE_MAX_TARGETS: None, # Remove nodes that dont have at least min. neighbors ConfigNetwork.MIN_NEIGHBORS: 1, ConfigNetwork.REACHABLE_NEIGHBORS: False, ConfigNetwork.N_CLOSEST_NEIGHBORS: ((1, 6), (2, 6), (3, 6),), ConfigNetwork.CENTROID_LEVEL: 1, # FLEET ############################################## # # Car operation ConfigNetwork.MAX_CARS_LINK: 5, ConfigNetwork.MAX_IDLE_STEP_COUNT: None, # FAV configuration # Functions ConfigNetwork.DEPOT_SHARE: 0.01, ConfigNetwork.FAV_DEPOT_LEVEL: None, ConfigNetwork.FAV_FLEET_SIZE: fav_fleet_size, ConfigNetwork.SEPARATE_FLEETS: False, ConfigNetwork.MAX_CONTRACT_DURATION: True, # mean, std, clip_a, clip_b # ConfigNetwork.FAV_EARLIEST_FEATURES = (8, 1, 5, 9) # ConfigNetwork.FAV_AVAILABILITY_FEATURES = (2, 1, 1, 4) # ConfigNetwork.PARKING_RATE_MIN = 1.50/60 # 1.50/h # ConfigNetwork.PARKING_RATE_MIN = 0.1*20/60 # , # = rebalancing 1 min ConfigNetwork.PARKING_RATE_MIN: 0, # = rebalancing 1 min # Saving ConfigNetwork.USE_SHORT_PATH: False, ConfigNetwork.SAVE_TRIP_DATA: log_trips, ConfigNetwork.SAVE_FLEET_DATA: log_fleet, # Load 1st class probabilities dictionary ConfigNetwork.USE_CLASS_PROB: True, ConfigNetwork.ENABLE_RECHARGING: False, # PLOT ############################################### # ConfigNetwork.PLOT_FLEET_XTICKS_LABELS: [ "", "6AM", "", "7AM", "", "8AM", "", "9AM", "", "10AM", "", "11AM", "", "12AM", "", ], ConfigNetwork.PLOT_FLEET_X_MIN: 0, ConfigNetwork.PLOT_FLEET_X_MAX: 84, ConfigNetwork.PLOT_FLEET_X_NUM: 15, ConfigNetwork.PLOT_FLEET_OMIT_CRUISING: False, ConfigNetwork.PLOT_DEMAND_Y_MAX: 3500, ConfigNetwork.PLOT_DEMAND_Y_NUM: 8, ConfigNetwork.PLOT_DEMAND_Y_MIN: 0, } ) # Toggle what is going to be logged log_config = { # Write each vehicles status la.LOG_FLEET_ACTIVITY: False, # Write profit, service level, # trips, car/satus count la.LOG_STEP_SUMMARY: log_summary, # ############# ADP ############################################ # Log duals update process la.LOG_WEIGHTS: False, la.LOG_VALUE_UPDATE: False, la.LOG_DUALS: False, la.LOG_COSTS: False, la.LOG_SOLUTIONS: False, la.LOG_ATTRIBUTE_CARS: False, la.LOG_DECISION_INFO: False, # Log .lp and .log from MIP models la.LOG_MIP: log_mip, # Log time spent across every step in each code section la.LOG_TIMES: log_times, # Save fleet, demand, and delay plots la.SAVE_PLOTS: save_plots, # Save fleet and demand dfs for live plot la.SAVE_DF: save_df, # Log level saved in file la.LEVEL_FILE: la.DEBUG, # Log level printed in screen la.LEVEL_CONSOLE: la.INFO, la.FORMATTER_FILE: la.FORMATTER_TERSE, # Log everything la.LOG_ALL: log_all, # Log chosen (if LOG_ALL, set to lowest, i.e., DEBUG) la.LOG_LEVEL: (log_level if not log_all else la.DEBUG), } alg_adp(None, start_config, log_config_dict=log_config)
[ "numpy.load", "mod.env.matching.service_trips", "mod.env.visual.EpisodeLog", "mod.env.adp.adp.AggLevel", "sys.path.append", "mod.env.demand.trip_util.get_ny_demand", "mod.env.demand.trip_util.get_trip_count_step", "mod.env.config.get_file_paths", "mod.env.demand.trip_util.get_df_from_sampled_trips",...
[((212, 233), 'sys.path.append', 'sys.path.append', (['root'], {}), '(root)\n', (227, 233), False, 'import sys\n'), ((918, 932), 'random.seed', 'random.seed', (['(1)'], {}), '(1)\n', (929, 932), False, 'import random\n'), ((982, 997), 'mod.env.config.ConfigNetwork', 'ConfigNetwork', ([], {}), '()\n', (995, 997), False, 'from mod.env.config import ConfigNetwork\n'), ((1149, 1164), 'mod.env.network.query_info', 'nw.query_info', ([], {}), '()\n', (1162, 1164), True, 'import mod.env.network as nw\n'), ((14048, 14085), 'mod.env.amod.AmodNetworkHired.AmodNetworkHired', 'AmodNetworkHired', (['config'], {'online': '(True)'}), '(config, online=True)\n', (14064, 14085), False, 'from mod.env.amod.AmodNetworkHired import AmodNetworkHired\n'), ((14332, 14398), 'mod.env.visual.EpisodeLog', 'EpisodeLog', (['amod.config.save_progress'], {'config': 'config', 'adp': 'amod.adp'}), '(amod.config.save_progress, config=config, adp=amod.adp)\n', (14342, 14398), False, 'from mod.env.visual import StepLog, EpisodeLog\n'), ((181, 192), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (190, 192), False, 'import os\n'), ((16531, 16731), 'mod.env.demand.trip_util.get_trip_count_step', 'get_trip_count_step', (['conf.TRIP_FILES[0]'], {'step': 'config.time_increment', 'multiply_for': 'config.demand_resize_factor', 'earliest_step': 'config.demand_earliest_step_min', 'max_steps': 'config.demand_max_steps'}), '(conf.TRIP_FILES[0], step=config.time_increment,\n multiply_for=config.demand_resize_factor, earliest_step=config.\n demand_earliest_step_min, max_steps=config.demand_max_steps)\n', (16550, 16731), False, 'from mod.env.demand.trip_util import get_trip_count_step, get_trips_random_ods\n'), ((20736, 20749), 'mod.env.visual.StepLog', 'StepLog', (['amod'], {}), '(amod)\n', (20743, 20749), False, 'from mod.env.visual import StepLog, EpisodeLog\n'), ((21446, 21457), 'time.time', 'time.time', ([], {}), '()\n', (21455, 21457), False, 'import time\n'), ((21647, 21671), 'copy.deepcopy', 'deepcopy', (['step_trip_list'], {}), '(step_trip_list)\n', (21655, 21671), False, 'from copy import deepcopy\n'), ((33736, 33747), 'time.time', 'time.time', ([], {}), '()\n', (33745, 33747), False, 'import time\n'), ((34776, 34787), 'time.time', 'time.time', ([], {}), '()\n', (34785, 34787), False, 'import time\n'), ((37318, 37351), 'mod.env.config.ConfigNetwork.load', 'ConfigNetwork.load', (['instance_name'], {}), '(instance_name)\n', (37336, 37351), False, 'from mod.env.config import ConfigNetwork\n'), ((17594, 17827), 'mod.env.demand.trip_util.get_trips_random_ods', 'get_trips_random_ods', (['amod.points', 'step_trip_count'], {'offset_start': 'amod.config.offset_repositioning_steps', 'offset_end': 'amod.config.offset_termination_steps', 'origins': 'origins', 'destinations': 'destinations', 'classed': 'classed_trips'}), '(amod.points, step_trip_count, offset_start=amod.config\n .offset_repositioning_steps, offset_end=amod.config.\n offset_termination_steps, origins=origins, destinations=destinations,\n classed=classed_trips)\n', (17614, 17827), False, 'from mod.env.demand.trip_util import get_trip_count_step, get_trips_random_ods\n'), ((21936, 22022), 'mod.env.matching.optimal_rebalancing', 'optimal_rebalancing', (['amod', 'it_step_trip_list'], {'log_mip': 'log_config_dict[la.LOG_MIP]'}), '(amod, it_step_trip_list, log_mip=log_config_dict[la.\n LOG_MIP])\n', (21955, 22022), False, 'from mod.env.matching import service_trips, optimal_rebalancing, play_decisions, mpc\n'), ((23964, 23975), 'time.time', 'time.time', ([], {}), '()\n', (23973, 23975), False, 'import time\n'), ((24587, 24598), 'time.time', 'time.time', ([], {}), '()\n', (24596, 24598), False, 'import time\n'), ((24700, 24743), 'itertools.chain', 'itertools.chain', (['amod.cars', 'amod.hired_cars'], {}), '(amod.cars, amod.hired_cars)\n', (24715, 24743), False, 'import itertools\n'), ((25153, 25164), 'time.time', 'time.time', ([], {}), '()\n', (25162, 25164), False, 'import time\n'), ((29487, 29498), 'time.time', 'time.time', ([], {}), '()\n', (29496, 29498), False, 'import time\n'), ((31625, 31636), 'time.time', 'time.time', ([], {}), '()\n', (31634, 31636), False, 'import time\n'), ((32131, 32142), 'time.time', 'time.time', ([], {}), '()\n', (32140, 32142), False, 'import time\n'), ((32762, 32773), 'time.time', 'time.time', ([], {}), '()\n', (32771, 32773), False, 'import time\n'), ((33811, 33822), 'time.time', 'time.time', ([], {}), '()\n', (33820, 33822), False, 'import time\n'), ((33931, 34057), 'mod.env.demand.trip_util.get_df_from_sampled_trips', 'tp.get_df_from_sampled_trips', (['it_step_trip_list'], {'show_service_data': '(True)', 'earliest_datetime': 'config.demand_earliest_datetime'}), '(it_step_trip_list, show_service_data=True,\n earliest_datetime=config.demand_earliest_datetime)\n', (33959, 34057), True, 'import mod.env.demand.trip_util as tp\n'), ((35189, 35200), 'time.time', 'time.time', ([], {}), '()\n', (35198, 35200), False, 'import time\n'), ((6952, 7091), 'mod.env.adp.adp.AggLevel', 'adp.AggLevel', ([], {'temporal': '(0)', 'spatial': '(1)', 'battery': 'adp.DISAGGREGATE', 'contract': 'adp.DISCARD', 'car_type': 'adp.DISAGGREGATE', 'car_origin': 'adp.DISCARD'}), '(temporal=0, spatial=1, battery=adp.DISAGGREGATE, contract=adp.\n DISCARD, car_type=adp.DISAGGREGATE, car_origin=adp.DISCARD)\n', (6964, 7091), True, 'import mod.env.adp.adp as adp\n'), ((7243, 7382), 'mod.env.adp.adp.AggLevel', 'adp.AggLevel', ([], {'temporal': '(1)', 'spatial': '(2)', 'battery': 'adp.DISAGGREGATE', 'contract': 'adp.DISCARD', 'car_type': 'adp.DISAGGREGATE', 'car_origin': 'adp.DISCARD'}), '(temporal=1, spatial=2, battery=adp.DISAGGREGATE, contract=adp.\n DISCARD, car_type=adp.DISAGGREGATE, car_origin=adp.DISCARD)\n', (7255, 7382), True, 'import mod.env.adp.adp as adp\n'), ((7534, 7673), 'mod.env.adp.adp.AggLevel', 'adp.AggLevel', ([], {'temporal': '(2)', 'spatial': '(3)', 'battery': 'adp.DISAGGREGATE', 'contract': 'adp.DISCARD', 'car_type': 'adp.DISAGGREGATE', 'car_origin': 'adp.DISCARD'}), '(temporal=2, spatial=3, battery=adp.DISAGGREGATE, contract=adp.\n DISCARD, car_type=adp.DISAGGREGATE, car_origin=adp.DISCARD)\n', (7546, 7673), True, 'import mod.env.adp.adp as adp\n'), ((18762, 18936), 'mod.env.demand.trip_util.get_ny_demand', 'tp.get_ny_demand', (['config', 'trips_file_path', 'amod.points'], {'seed': 'n', 'prob_dict': 'prob_dict', 'centroid_level': 'amod.config.centroid_level', 'unreachable_ods': 'amod.unreachable_ods'}), '(config, trips_file_path, amod.points, seed=n, prob_dict=\n prob_dict, centroid_level=amod.config.centroid_level, unreachable_ods=\n amod.unreachable_ods)\n', (18778, 18936), True, 'import mod.env.demand.trip_util as tp\n'), ((23222, 23245), 'mod.env.visual.compute_trips', 'vi.compute_trips', (['trips'], {}), '(trips)\n', (23238, 23245), True, 'import mod.env.visual as vi\n'), ((24437, 24448), 'time.time', 'time.time', ([], {}), '()\n', (24446, 24448), False, 'import time\n'), ((25118, 25129), 'time.time', 'time.time', ([], {}), '()\n', (25127, 25129), False, 'import time\n'), ((25379, 25436), 'mod.env.matching.play_decisions', 'play_decisions', (['amod', 'trips', '(step + 1)', 'it_decisions[step]'], {}), '(amod, trips, step + 1, it_decisions[step])\n', (25393, 25436), False, 'from mod.env.matching import service_trips, optimal_rebalancing, play_decisions, mpc\n'), ((27581, 27751), 'mod.env.matching.service_trips', 'service_trips', (['amod', 'rejected', '(step + 1)'], {'iteration': 'n', 'car_type_hide': 'Car.TYPE_FLEET', 'log_times': 'log_config_dict[la.LOG_TIMES]', 'log_mip': 'log_config_dict[la.LOG_MIP]'}), '(amod, rejected, step + 1, iteration=n, car_type_hide=Car.\n TYPE_FLEET, log_times=log_config_dict[la.LOG_TIMES], log_mip=\n log_config_dict[la.LOG_MIP])\n', (27594, 27751), False, 'from mod.env.matching import service_trips, optimal_rebalancing, play_decisions, mpc\n'), ((29212, 29223), 'time.time', 'time.time', ([], {}), '()\n', (29221, 29223), False, 'import time\n'), ((30246, 30257), 'time.time', 'time.time', ([], {}), '()\n', (30255, 30257), False, 'import time\n'), ((30376, 30387), 'time.time', 'time.time', ([], {}), '()\n', (30385, 30387), False, 'import time\n'), ((30831, 31029), 'mod.env.matching.service_trips', 'service_trips', (['amod', '(rejected + outstanding)', '(step + 1)'], {'iteration': 'n', 'log_mip': 'log_config_dict[la.LOG_MIP]', 'log_times': 'log_config_dict[la.LOG_TIMES]', 'car_type_hide': 'Car.TYPE_FLEET', 'reactive': '(True)'}), '(amod, rejected + outstanding, step + 1, iteration=n, log_mip=\n log_config_dict[la.LOG_MIP], log_times=log_config_dict[la.LOG_TIMES],\n car_type_hide=Car.TYPE_FLEET, reactive=True)\n', (30844, 31029), False, 'from mod.env.matching import service_trips, optimal_rebalancing, play_decisions, mpc\n'), ((31570, 31581), 'time.time', 'time.time', ([], {}), '()\n', (31579, 31581), False, 'import time\n'), ((32096, 32107), 'time.time', 'time.time', ([], {}), '()\n', (32105, 32107), False, 'import time\n'), ((32507, 32518), 'time.time', 'time.time', ([], {}), '()\n', (32516, 32518), False, 'import time\n'), ((33079, 33090), 'time.time', 'time.time', ([], {}), '()\n', (33088, 33090), False, 'import time\n'), ((33306, 33328), 'time.sleep', 'time.sleep', (['step_delay'], {}), '(step_delay)\n', (33316, 33328), False, 'import time\n'), ((34890, 34901), 'time.time', 'time.time', ([], {}), '()\n', (34899, 34901), False, 'import time\n'), ((15257, 15307), 'numpy.load', 'np.load', (['config.path_class_prob'], {'allow_pickle': '(True)'}), '(config.path_class_prob, allow_pickle=True)\n', (15264, 15307), True, 'import numpy as np\n'), ((18171, 18198), 'mod.env.config.get_file_paths', 'conf.get_file_paths', (['folder'], {}), '(folder)\n', (18190, 18198), True, 'import mod.env.config as conf\n'), ((18233, 18258), 'random.choice', 'random.choice', (['list_files'], {}), '(list_files)\n', (18246, 18258), False, 'import random\n'), ((18449, 18476), 'mod.env.config.get_file_paths', 'conf.get_file_paths', (['folder'], {}), '(folder)\n', (18468, 18476), True, 'import mod.env.config as conf\n'), ((19165, 19209), 'mod.env.demand.trip_util.get_df_from_sampled_trips', 'tp.get_df_from_sampled_trips', (['step_trip_list'], {}), '(step_trip_list)\n', (19193, 19209), True, 'import mod.env.demand.trip_util as tp\n'), ((26271, 26361), 'mod.env.matching.mpc', 'mpc', (['amod', 'trips', 'predicted_trips'], {'step': '(step + 1)', 'log_mip': 'log_config_dict[la.LOG_MIP]'}), '(amod, trips, predicted_trips, step=step + 1, log_mip=log_config_dict[la\n .LOG_MIP])\n', (26274, 26361), False, 'from mod.env.matching import service_trips, optimal_rebalancing, play_decisions, mpc\n'), ((26757, 26805), 'mod.env.matching.play_decisions', 'play_decisions', (['amod', 'trips', '(step + 1)', 'decisions'], {}), '(amod, trips, step + 1, decisions)\n', (26771, 26805), False, 'from mod.env.matching import service_trips, optimal_rebalancing, play_decisions, mpc\n'), ((26909, 27076), 'mod.env.matching.service_trips', 'service_trips', (['amod', 'trips', '(step + 1)'], {'iteration': 'n', 'log_mip': 'log_config_dict[la.LOG_MIP]', 'log_times': 'log_config_dict[la.LOG_TIMES]', 'car_type_hide': 'Car.TYPE_FLEET'}), '(amod, trips, step + 1, iteration=n, log_mip=log_config_dict[\n la.LOG_MIP], log_times=log_config_dict[la.LOG_TIMES], car_type_hide=Car\n .TYPE_FLEET)\n', (26922, 27076), False, 'from mod.env.matching import service_trips, optimal_rebalancing, play_decisions, mpc\n'), ((30337, 30348), 'time.time', 'time.time', ([], {}), '()\n', (30346, 30348), False, 'import time\n'), ((30737, 30748), 'time.time', 'time.time', ([], {}), '()\n', (30746, 30748), False, 'import time\n'), ((19582, 19614), 'itertools.chain', 'itertools.chain', (['*step_trip_list'], {}), '(*step_trip_list)\n', (19597, 19614), False, 'import itertools\n')]
import os import csv import cv2 import numpy as np import matplotlib.pyplot as plt from sklearn.utils import shuffle from keras.models import Sequential from keras.layers import Dense,Dropout,Flatten,Conv2D,MaxPooling2D,Lambda,Cropping2D from keras.callbacks import LearningRateScheduler def learning_rate(epoch): return 0.001*(0.1**int(epoch/10)) samples = [] correction=0.15 with open('./data/driving_log.csv') as csvfile: reader = csv.reader(csvfile) for line in reader: samples.append(line) images=[] angles=[] for batch_sample in samples: cenimage = cv2.imread(batch_sample[0]) center_image=cv2.cvtColor(cenimage,cv2.COLOR_BGR2RGB) limage=cv2.imread(batch_sample[1]) left_image=cv2.cvtColor(limage,cv2.COLOR_BGR2RGB) rimage=cv2.imread(batch_sample[2]) right_image=cv2.cvtColor(rimage,cv2.COLOR_BGR2RGB) center_angle = float(batch_sample[3]) left_angle=center_angle+correction right_angle=center_angle-correction #images.append(center_image) #angles.append(center_angle) images.extend([center_image,left_image,right_image]) angles.extend([center_angle,left_angle,right_angle]) def flip(image): return np.fliplr(image) for i in range(len(images)): image1=flip(images[i]) images.append(image1) angles.append(-1*angles[i]) X_train = np.array(images) y_train = np.array(angles) X_train,y_train=shuffle(X_train,y_train) model=Sequential() model.add(Cropping2D(cropping=((50,20), (0,10)),input_shape=(160,320,3))) model.add(Lambda(lambda x: (x / 255.0) - 0.5)) model.add(Conv2D(24, (5, 5), activation="relu", strides=(2, 2))) model.add(Conv2D(36, (5, 5), activation="relu", strides=(2, 2))) model.add(Conv2D(48, (5, 5), activation="relu", strides=(2, 2))) model.add(Conv2D(64, (3, 3), activation="relu")) model.add(Conv2D(64, (3, 3), activation="relu")) model.add(MaxPooling2D(pool_size=(2,2))) model.add(Flatten()) model.add(Dense(100,activation="relu")) model.add(Dropout(0.5)) model.add(Dense(50,activation="relu")) model.add(Dropout(0.5)) model.add(Dense(10,activation="relu")) model.add(Dropout(0.5)) model.add(Dense(1)) model.load_weights('weights.h5') model.compile(loss='mse', optimizer='adam') logits=model.fit(X_train,y_train,epochs=20,shuffle=True,validation_split=0.2,callbacks=[LearningRateScheduler(learning_rate)]) model.save_weights('weights.h5') model.save('model.h5') plt.plot(logits.history['loss']) plt.plot(logits.history['val_loss']) plt.title('Training loss vs Validation loss') plt.xlabel('epochs') plt.ylabel('Loss') plt.legend(['Train','Validation'],loc='upper right') plt.savefig('Learning.jpg')
[ "matplotlib.pyplot.title", "csv.reader", "keras.layers.Cropping2D", "keras.callbacks.LearningRateScheduler", "cv2.cvtColor", "keras.layers.Flatten", "keras.layers.MaxPooling2D", "keras.layers.Dropout", "matplotlib.pyplot.legend", "numpy.fliplr", "keras.layers.Conv2D", "matplotlib.pyplot.ylabel...
[((1361, 1377), 'numpy.array', 'np.array', (['images'], {}), '(images)\n', (1369, 1377), True, 'import numpy as np\n'), ((1388, 1404), 'numpy.array', 'np.array', (['angles'], {}), '(angles)\n', (1396, 1404), True, 'import numpy as np\n'), ((1422, 1447), 'sklearn.utils.shuffle', 'shuffle', (['X_train', 'y_train'], {}), '(X_train, y_train)\n', (1429, 1447), False, 'from sklearn.utils import shuffle\n'), ((1455, 1467), 'keras.models.Sequential', 'Sequential', ([], {}), '()\n', (1465, 1467), False, 'from keras.models import Sequential\n'), ((2418, 2450), 'matplotlib.pyplot.plot', 'plt.plot', (["logits.history['loss']"], {}), "(logits.history['loss'])\n", (2426, 2450), True, 'import matplotlib.pyplot as plt\n'), ((2451, 2487), 'matplotlib.pyplot.plot', 'plt.plot', (["logits.history['val_loss']"], {}), "(logits.history['val_loss'])\n", (2459, 2487), True, 'import matplotlib.pyplot as plt\n'), ((2488, 2533), 'matplotlib.pyplot.title', 'plt.title', (['"""Training loss vs Validation loss"""'], {}), "('Training loss vs Validation loss')\n", (2497, 2533), True, 'import matplotlib.pyplot as plt\n'), ((2534, 2554), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""epochs"""'], {}), "('epochs')\n", (2544, 2554), True, 'import matplotlib.pyplot as plt\n'), ((2555, 2573), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Loss"""'], {}), "('Loss')\n", (2565, 2573), True, 'import matplotlib.pyplot as plt\n'), ((2574, 2628), 'matplotlib.pyplot.legend', 'plt.legend', (["['Train', 'Validation']"], {'loc': '"""upper right"""'}), "(['Train', 'Validation'], loc='upper right')\n", (2584, 2628), True, 'import matplotlib.pyplot as plt\n'), ((2627, 2654), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""Learning.jpg"""'], {}), "('Learning.jpg')\n", (2638, 2654), True, 'import matplotlib.pyplot as plt\n'), ((444, 463), 'csv.reader', 'csv.reader', (['csvfile'], {}), '(csvfile)\n', (454, 463), False, 'import csv\n'), ((595, 622), 'cv2.imread', 'cv2.imread', (['batch_sample[0]'], {}), '(batch_sample[0])\n', (605, 622), False, 'import cv2\n'), ((640, 681), 'cv2.cvtColor', 'cv2.cvtColor', (['cenimage', 'cv2.COLOR_BGR2RGB'], {}), '(cenimage, cv2.COLOR_BGR2RGB)\n', (652, 681), False, 'import cv2\n'), ((692, 719), 'cv2.imread', 'cv2.imread', (['batch_sample[1]'], {}), '(batch_sample[1])\n', (702, 719), False, 'import cv2\n'), ((735, 774), 'cv2.cvtColor', 'cv2.cvtColor', (['limage', 'cv2.COLOR_BGR2RGB'], {}), '(limage, cv2.COLOR_BGR2RGB)\n', (747, 774), False, 'import cv2\n'), ((785, 812), 'cv2.imread', 'cv2.imread', (['batch_sample[2]'], {}), '(batch_sample[2])\n', (795, 812), False, 'import cv2\n'), ((829, 868), 'cv2.cvtColor', 'cv2.cvtColor', (['rimage', 'cv2.COLOR_BGR2RGB'], {}), '(rimage, cv2.COLOR_BGR2RGB)\n', (841, 868), False, 'import cv2\n'), ((1214, 1230), 'numpy.fliplr', 'np.fliplr', (['image'], {}), '(image)\n', (1223, 1230), True, 'import numpy as np\n'), ((1478, 1545), 'keras.layers.Cropping2D', 'Cropping2D', ([], {'cropping': '((50, 20), (0, 10))', 'input_shape': '(160, 320, 3)'}), '(cropping=((50, 20), (0, 10)), input_shape=(160, 320, 3))\n', (1488, 1545), False, 'from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D, Lambda, Cropping2D\n'), ((1552, 1585), 'keras.layers.Lambda', 'Lambda', (['(lambda x: x / 255.0 - 0.5)'], {}), '(lambda x: x / 255.0 - 0.5)\n', (1558, 1585), False, 'from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D, Lambda, Cropping2D\n'), ((1600, 1653), 'keras.layers.Conv2D', 'Conv2D', (['(24)', '(5, 5)'], {'activation': '"""relu"""', 'strides': '(2, 2)'}), "(24, (5, 5), activation='relu', strides=(2, 2))\n", (1606, 1653), False, 'from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D, Lambda, Cropping2D\n'), ((1665, 1718), 'keras.layers.Conv2D', 'Conv2D', (['(36)', '(5, 5)'], {'activation': '"""relu"""', 'strides': '(2, 2)'}), "(36, (5, 5), activation='relu', strides=(2, 2))\n", (1671, 1718), False, 'from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D, Lambda, Cropping2D\n'), ((1730, 1783), 'keras.layers.Conv2D', 'Conv2D', (['(48)', '(5, 5)'], {'activation': '"""relu"""', 'strides': '(2, 2)'}), "(48, (5, 5), activation='relu', strides=(2, 2))\n", (1736, 1783), False, 'from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D, Lambda, Cropping2D\n'), ((1796, 1833), 'keras.layers.Conv2D', 'Conv2D', (['(64)', '(3, 3)'], {'activation': '"""relu"""'}), "(64, (3, 3), activation='relu')\n", (1802, 1833), False, 'from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D, Lambda, Cropping2D\n'), ((1845, 1882), 'keras.layers.Conv2D', 'Conv2D', (['(64)', '(3, 3)'], {'activation': '"""relu"""'}), "(64, (3, 3), activation='relu')\n", (1851, 1882), False, 'from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D, Lambda, Cropping2D\n'), ((1894, 1924), 'keras.layers.MaxPooling2D', 'MaxPooling2D', ([], {'pool_size': '(2, 2)'}), '(pool_size=(2, 2))\n', (1906, 1924), False, 'from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D, Lambda, Cropping2D\n'), ((1935, 1944), 'keras.layers.Flatten', 'Flatten', ([], {}), '()\n', (1942, 1944), False, 'from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D, Lambda, Cropping2D\n'), ((1956, 1985), 'keras.layers.Dense', 'Dense', (['(100)'], {'activation': '"""relu"""'}), "(100, activation='relu')\n", (1961, 1985), False, 'from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D, Lambda, Cropping2D\n'), ((1996, 2008), 'keras.layers.Dropout', 'Dropout', (['(0.5)'], {}), '(0.5)\n', (2003, 2008), False, 'from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D, Lambda, Cropping2D\n'), ((2020, 2048), 'keras.layers.Dense', 'Dense', (['(50)'], {'activation': '"""relu"""'}), "(50, activation='relu')\n", (2025, 2048), False, 'from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D, Lambda, Cropping2D\n'), ((2059, 2071), 'keras.layers.Dropout', 'Dropout', (['(0.5)'], {}), '(0.5)\n', (2066, 2071), False, 'from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D, Lambda, Cropping2D\n'), ((2083, 2111), 'keras.layers.Dense', 'Dense', (['(10)'], {'activation': '"""relu"""'}), "(10, activation='relu')\n", (2088, 2111), False, 'from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D, Lambda, Cropping2D\n'), ((2122, 2134), 'keras.layers.Dropout', 'Dropout', (['(0.5)'], {}), '(0.5)\n', (2129, 2134), False, 'from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D, Lambda, Cropping2D\n'), ((2146, 2154), 'keras.layers.Dense', 'Dense', (['(1)'], {}), '(1)\n', (2151, 2154), False, 'from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D, Lambda, Cropping2D\n'), ((2322, 2358), 'keras.callbacks.LearningRateScheduler', 'LearningRateScheduler', (['learning_rate'], {}), '(learning_rate)\n', (2343, 2358), False, 'from keras.callbacks import LearningRateScheduler\n')]
# coding=utf-8 # Copyright 2022 The Google Research Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Wrapper around pybind module that provides convenience functions for instantiating ScaNN searchers.""" # pylint: disable=g-import-not-at-top,g-bad-import-order,unused-import import os import sys import numpy as np # needed because of C++ dependency on TF headers import tensorflow as _tf sys.path.append( os.path.join( os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "cc/python")) import scann_pybind from scann.scann_ops.py import scann_builder class ScannSearcher(object): """Wrapper class around pybind module that provides a cleaner interface.""" def __init__(self, searcher): self.searcher = searcher def search(self, q, final_num_neighbors=None, pre_reorder_num_neighbors=None, leaves_to_search=None): final_nn = -1 if final_num_neighbors is None else final_num_neighbors pre_nn = -1 if pre_reorder_num_neighbors is None else pre_reorder_num_neighbors leaves = -1 if leaves_to_search is None else leaves_to_search return self.searcher.search(q, final_nn, pre_nn, leaves) def search_batched(self, queries, final_num_neighbors=None, pre_reorder_num_neighbors=None, leaves_to_search=None): final_nn = -1 if final_num_neighbors is None else final_num_neighbors pre_nn = -1 if pre_reorder_num_neighbors is None else pre_reorder_num_neighbors leaves = -1 if leaves_to_search is None else leaves_to_search return self.searcher.search_batched(queries, final_nn, pre_nn, leaves, False) def search_batched_parallel(self, queries, final_num_neighbors=None, pre_reorder_num_neighbors=None, leaves_to_search=None): final_nn = -1 if final_num_neighbors is None else final_num_neighbors pre_nn = -1 if pre_reorder_num_neighbors is None else pre_reorder_num_neighbors leaves = -1 if leaves_to_search is None else leaves_to_search return self.searcher.search_batched(queries, final_nn, pre_nn, leaves, True) def serialize(self, artifacts_dir): self.searcher.serialize(artifacts_dir) def builder(db, num_neighbors, distance_measure): """pybind analogue of builder() in scann_ops.py; see docstring there.""" def builder_lambda(db, config, training_threads, **kwargs): return create_searcher(db, config, training_threads, **kwargs) return scann_builder.ScannBuilder( db, num_neighbors, distance_measure).set_builder_lambda(builder_lambda) def create_searcher(db, scann_config, training_threads=0): return ScannSearcher( scann_pybind.ScannNumpy(db, scann_config, training_threads)) def load_searcher(artifacts_dir): """Loads searcher assets from artifacts_dir and returns a ScaNN searcher.""" def load_if_exists(filename): path = os.path.join(artifacts_dir, filename) return np.load(path) if os.path.isfile(path) else None db = load_if_exists("dataset.npy") tokenization = load_if_exists("datapoint_to_token.npy") hashed_db = load_if_exists("hashed_dataset.npy") int8_db = load_if_exists("int8_dataset.npy") int8_multipliers = load_if_exists("int8_multipliers.npy") db_norms = load_if_exists("dp_norms.npy") return ScannSearcher( scann_pybind.ScannNumpy(db, tokenization, hashed_db, int8_db, int8_multipliers, db_norms, artifacts_dir))
[ "numpy.load", "os.path.abspath", "scann_pybind.ScannNumpy", "os.path.isfile", "scann.scann_ops.py.scann_builder.ScannBuilder", "os.path.join" ]
[((3354, 3413), 'scann_pybind.ScannNumpy', 'scann_pybind.ScannNumpy', (['db', 'scann_config', 'training_threads'], {}), '(db, scann_config, training_threads)\n', (3377, 3413), False, 'import scann_pybind\n'), ((3574, 3611), 'os.path.join', 'os.path.join', (['artifacts_dir', 'filename'], {}), '(artifacts_dir, filename)\n', (3586, 3611), False, 'import os\n'), ((4000, 4108), 'scann_pybind.ScannNumpy', 'scann_pybind.ScannNumpy', (['db', 'tokenization', 'hashed_db', 'int8_db', 'int8_multipliers', 'db_norms', 'artifacts_dir'], {}), '(db, tokenization, hashed_db, int8_db,\n int8_multipliers, db_norms, artifacts_dir)\n', (4023, 4108), False, 'import scann_pybind\n'), ((3157, 3220), 'scann.scann_ops.py.scann_builder.ScannBuilder', 'scann_builder.ScannBuilder', (['db', 'num_neighbors', 'distance_measure'], {}), '(db, num_neighbors, distance_measure)\n', (3183, 3220), False, 'from scann.scann_ops.py import scann_builder\n'), ((3640, 3660), 'os.path.isfile', 'os.path.isfile', (['path'], {}), '(path)\n', (3654, 3660), False, 'import os\n'), ((3623, 3636), 'numpy.load', 'np.load', (['path'], {}), '(path)\n', (3630, 3636), True, 'import numpy as np\n'), ((977, 1002), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (992, 1002), False, 'import os\n')]
# taken from http://hyperphysics.phy-astr.gsu.edu/hbase/phyopt/antiref.html#c1 import numpy import pylab import EMpy_gpu # define multilayer n = numpy.array([1., 1.38, 1.9044]) d = numpy.array([numpy.inf, 387.5e-9 / 1.38, numpy.inf]) iso_layers = EMpy_gpu.utils.Multilayer() for i in xrange(n.size): n0 = EMpy_gpu.materials.RefractiveIndex(n[i]) iso_layers.append( EMpy_gpu.utils.Layer(EMpy_gpu.materials.IsotropicMaterial('mat', n0=n0), d[i])) # define incident wave plane theta_inc = EMpy_gpu.utils.deg2rad(10.) wls = numpy.linspace(0.85e-6, 2.25e-6, 300) # solve tm = EMpy_gpu.transfer_matrix.IsotropicTransferMatrix(iso_layers, theta_inc) solution_iso = tm.solve(wls) # plot pylab.figure() pylab.plot(wls, 10 * numpy.log10(solution_iso.Rs), 'rx-', wls, 10*numpy.log10(solution_iso.Rp), 'g.-') pylab.legend(('Rs', 'Rp')) pylab.title('Single Layer Anti-Reflection Coating') pylab.xlabel('wavelength /m') pylab.ylabel('Power /dB') pylab.grid() pylab.xlim(wls.min(), wls.max()) pylab.savefig(__file__ + '.png') pylab.show()
[ "EMpy_gpu.utils.deg2rad", "pylab.title", "pylab.show", "pylab.ylabel", "pylab.grid", "EMpy_gpu.utils.Multilayer", "pylab.savefig", "EMpy_gpu.materials.IsotropicMaterial", "numpy.array", "pylab.figure", "numpy.linspace", "pylab.xlabel", "EMpy_gpu.transfer_matrix.IsotropicTransferMatrix", "E...
[((148, 180), 'numpy.array', 'numpy.array', (['[1.0, 1.38, 1.9044]'], {}), '([1.0, 1.38, 1.9044])\n', (159, 180), False, 'import numpy\n'), ((184, 237), 'numpy.array', 'numpy.array', (['[numpy.inf, 3.875e-07 / 1.38, numpy.inf]'], {}), '([numpy.inf, 3.875e-07 / 1.38, numpy.inf])\n', (195, 237), False, 'import numpy\n'), ((250, 277), 'EMpy_gpu.utils.Multilayer', 'EMpy_gpu.utils.Multilayer', ([], {}), '()\n', (275, 277), False, 'import EMpy_gpu\n'), ((506, 534), 'EMpy_gpu.utils.deg2rad', 'EMpy_gpu.utils.deg2rad', (['(10.0)'], {}), '(10.0)\n', (528, 534), False, 'import EMpy_gpu\n'), ((540, 578), 'numpy.linspace', 'numpy.linspace', (['(8.5e-07)', '(2.25e-06)', '(300)'], {}), '(8.5e-07, 2.25e-06, 300)\n', (554, 578), False, 'import numpy\n'), ((592, 663), 'EMpy_gpu.transfer_matrix.IsotropicTransferMatrix', 'EMpy_gpu.transfer_matrix.IsotropicTransferMatrix', (['iso_layers', 'theta_inc'], {}), '(iso_layers, theta_inc)\n', (640, 663), False, 'import EMpy_gpu\n'), ((701, 715), 'pylab.figure', 'pylab.figure', ([], {}), '()\n', (713, 715), False, 'import pylab\n'), ((830, 856), 'pylab.legend', 'pylab.legend', (["('Rs', 'Rp')"], {}), "(('Rs', 'Rp'))\n", (842, 856), False, 'import pylab\n'), ((857, 908), 'pylab.title', 'pylab.title', (['"""Single Layer Anti-Reflection Coating"""'], {}), "('Single Layer Anti-Reflection Coating')\n", (868, 908), False, 'import pylab\n'), ((909, 938), 'pylab.xlabel', 'pylab.xlabel', (['"""wavelength /m"""'], {}), "('wavelength /m')\n", (921, 938), False, 'import pylab\n'), ((939, 964), 'pylab.ylabel', 'pylab.ylabel', (['"""Power /dB"""'], {}), "('Power /dB')\n", (951, 964), False, 'import pylab\n'), ((965, 977), 'pylab.grid', 'pylab.grid', ([], {}), '()\n', (975, 977), False, 'import pylab\n'), ((1011, 1043), 'pylab.savefig', 'pylab.savefig', (["(__file__ + '.png')"], {}), "(__file__ + '.png')\n", (1024, 1043), False, 'import pylab\n'), ((1044, 1056), 'pylab.show', 'pylab.show', ([], {}), '()\n', (1054, 1056), False, 'import pylab\n'), ((312, 352), 'EMpy_gpu.materials.RefractiveIndex', 'EMpy_gpu.materials.RefractiveIndex', (['n[i]'], {}), '(n[i])\n', (346, 352), False, 'import EMpy_gpu\n'), ((737, 765), 'numpy.log10', 'numpy.log10', (['solution_iso.Rs'], {}), '(solution_iso.Rs)\n', (748, 765), False, 'import numpy\n'), ((793, 821), 'numpy.log10', 'numpy.log10', (['solution_iso.Rp'], {}), '(solution_iso.Rp)\n', (804, 821), False, 'import numpy\n'), ((405, 455), 'EMpy_gpu.materials.IsotropicMaterial', 'EMpy_gpu.materials.IsotropicMaterial', (['"""mat"""'], {'n0': 'n0'}), "('mat', n0=n0)\n", (441, 455), False, 'import EMpy_gpu\n')]
import os import sys import warnings import typing import time import keras import keras.preprocessing.image import tensorflow as tf import pandas as pd import numpy as np from object_detection_retinanet import layers from object_detection_retinanet import losses from object_detection_retinanet import models from collections import OrderedDict from d3m import container, utils from d3m.container import DataFrame as d3m_DataFrame from d3m.metadata import base as metadata_base, hyperparams, params from d3m.primitive_interfaces.base import PrimitiveBase, CallResult from object_detection_retinanet.callbacks import RedirectModel from object_detection_retinanet.callbacks.eval import Evaluate from object_detection_retinanet.utils.eval import evaluate from object_detection_retinanet.models.retinanet import retinanet_bbox from object_detection_retinanet.preprocessing.csv_generator import CSVGenerator from object_detection_retinanet.utils.anchors import make_shapes_callback from object_detection_retinanet.utils.model import freeze as freeze_model from object_detection_retinanet.utils.gpu import setup_gpu from object_detection_retinanet.utils.image import read_image_bgr, preprocess_image, resize_image Inputs = container.pandas.DataFrame Outputs = container.pandas.DataFrame class Hyperparams(hyperparams.Hyperparams): backbone = hyperparams.Union( OrderedDict({ 'resnet50': hyperparams.Constant[str]( default = 'resnet50', semantic_types = ['https://metadata.datadrivendiscovery.org/types/TuningParameter'], description = "Backbone architecture from resnet50 architecture (https://arxiv.org/abs/1512.03385)" ) # 'resnet101': hyperparams.Constant[str]( # default = 'resnet101', # semantic_types = ['https://metadata.datadrivendiscovery.org/types/TuningParameter'], # description = "Backbone architecture from resnet101 architecture (https://arxiv.org/abs/1512.03385)" # ), # 'resnet152': hyperparams.Constant[str]( # default = 'resnet152', # semantic_types = ['https://metadata.datadrivendiscovery.org/types/TuningParameter'], # description = "Backbone architecture from resnet152 architecture (https://arxiv.org/abs/1512.03385)" # ) }), default = 'resnet50', semantic_types = ['https://metadata.datadrivendiscovery.org/types/TuningParameter'], description = "Backbone architecture from which RetinaNet is built. All backbones " + "require a weights file downloaded for use during runtime." ) batch_size = hyperparams.Hyperparameter[int]( default = 1, semantic_types = ['https://metadata.datadrivendiscovery.org/types/TuningParameter'], description = "Size of the batches as input to the model." ) n_epochs = hyperparams.Hyperparameter[int]( default = 20, semantic_types = ['https://metadata.datadrivendiscovery.org/types/TuningParameter'], description = "Number of epochs to train." ) freeze_backbone = hyperparams.Hyperparameter[bool]( default = True, semantic_types = ['https://metadata.datadrivendiscovery.org/types/ControlParameter'], description = "Freeze training of backbone layers." ) weights = hyperparams.Hyperparameter[bool]( default = True, semantic_types = ['https://metadata.datadrivendiscovery.org/types/ControlParameter'], description = "Load the model with pretrained weights specific to selected backbone." ) learning_rate = hyperparams.Hyperparameter[float]( default = 1e-5, semantic_types = ['https://metadata.datadrivendiscovery.org/types/ControlParameter'], description = "Learning rate." ) n_steps = hyperparams.Hyperparameter[int]( default = 50, semantic_types = ['https://metadata.datadrivendiscovery.org/types/TuningParameter'], description = "Number of steps/epoch." ) output = hyperparams.Hyperparameter[bool]( default = False, semantic_types = ['https://metadata.datadrivendiscovery.org/types/ControlParameter'], description = "Output images and predicted bounding boxes after evaluation." ) class Params(params.Params): pass class ObjectDetectionRNPrimitive(PrimitiveBase[Inputs, Outputs, Params, Hyperparams]): """ Primitive that utilizes RetinaNet, a convolutional neural network (CNN), for object detection. The methodology comes from "Focal Loss for Dense Object Detection" by Lin et al. 2017 (https://arxiv.org/abs/1708.02002). The code implementation is based off of the base library found at: https://github.com/fizyr/keras-retinanet. The primitive accepts a Dataset consisting of images, labels as input and returns a dataframe as output which include the bounding boxes for each object in each image. """ metadata = metadata_base.PrimitiveMetadata( { 'id': 'd921be1e-b158-4ab7-abb3-cb1b17f42639', 'version': '0.1.0', 'name': 'retina_net', 'python_path': 'd3m.primitives.object_detection.retinanet', 'keywords': ['object detection', 'convolutional neural network', 'digital image processing', 'RetinaNet'], 'source': { 'name': 'Distil', 'contact': 'mailto:<EMAIL>', 'uris': [ 'https://github.com/NewKnowledge/object-detection-d3m-wrapper', ], }, 'installation': [ { 'type': 'PIP', 'package_uri': 'git+https://github.com/NewKnowledge/object-detection-d3m-wrapper.git@{git_commit}#egg=objectDetectionD3MWrapper'.format( git_commit = utils.current_git_commit(os.path.dirname(__file__)),) }, { 'type': "FILE", 'key': "resnet50", 'file_uri': "http://public.datadrivendiscovery.org/ResNet-50-model.keras.h5", 'file_digest': "0128cdfa3963288110422e4c1a57afe76aa0d760eb706cda4353ef1432c31b9c" } ], 'algorithm_types': [metadata_base.PrimitiveAlgorithmType.RETINANET], 'primitive_family': metadata_base.PrimitiveFamily.OBJECT_DETECTION, } ) def __init__(self, *, hyperparams: Hyperparams, volumes: typing.Dict[str,str] = None) -> None: super().__init__(hyperparams = hyperparams, volumes = volumes) self.image_paths = None self.annotations = None self.base_dir = None self.classes = None self.backbone = None self.y_true = None self.workers = 1 self.multiprocessing = 1 self.max_queue_size = 10 def get_params(self) -> Params: return self._params def set_params(self, *, params: Params) -> None: self.params = params def set_training_data(self, *, inputs: Inputs, outputs: Outputs) -> None: """ Sets the primitive's training data and preprocesses the files for RetinaNet format. Parameters ---------- inputs: numpy ndarray of size (n_images, dimension) containing the d3m Index, image name, and bounding box for each image. Returns ------- No returns. Function is called by pipeline at runtime. """ # Prepare annotation file ## Generate image paths image_cols = inputs.metadata.get_columns_with_semantic_type('https://metadata.datadrivendiscovery.org/types/FileName') self.base_dir = [inputs.metadata.query((metadata_base.ALL_ELEMENTS, t))['location_base_uris'][0].replace('file:///', '/') for t in image_cols] self.image_paths = np.array([[os.path.join(self.base_dir, filename) for filename in inputs.iloc[:,col]] for self.base_dir, col in zip(self.base_dir, image_cols)]).flatten() self.image_paths = pd.Series(self.image_paths) ## Arrange proper bounding coordinates bounding_coords = inputs.bounding_box.str.split(',', expand = True) bounding_coords = bounding_coords.drop(bounding_coords.columns[[2, 5, 6, 7]], axis = 1) bounding_coords.columns = ['x1', 'y1', 'y2', 'x2'] bounding_coords = bounding_coords[['x1', 'y1', 'x2', 'y2']] ## Generate class names class_name = pd.Series(['class'] * inputs.shape[0]) ## Assemble annotation file self.annotations = pd.concat([self.image_paths, bounding_coords, class_name], axis = 1) self.annotations.columns = ['img_file', 'x1', 'y1', 'x2', 'y2', 'class_name'] # Prepare ID file self.classes = pd.DataFrame({'class_name': ['class'], 'class_id': [0]}) def _create_callbacks(self, model, training_model, prediction_model): """ Creates the callbacks to use during training. Parameters ---------- model : The base model. training_model : The model that is used for training. prediction_model : The model that should be used for validation. validation_generator : The generator for creating validation data. Returns ------- callbacks : A list of callbacks used for training. """ callbacks = [] callbacks.append(keras.callbacks.ReduceLROnPlateau( monitor = 'loss', factor = 0.1, patience = 2, verbose = 1, mode = 'auto', min_delta = 0.0001, cooldown = 0, min_lr = 0 )) return callbacks def _create_models(self, backbone_retinanet, num_classes, weights, freeze_backbone = False, lr = 1e-5): """ Creates three models (model, training_model, prediction_model). Parameters ---------- backbone_retinanet : A function to call to create a retinanet model with a given backbone. num_classes : The number of classes to train. weights : The weights to load into the model. multi_gpu : The number of GPUs to use for training. freeze_backbone : If True, disables learning for the backbone. config : Config parameters, None indicates the default configuration. Returns ------- model : The base model. training_model : The training model. If multi_gpu=0, this is identical to model. prediction_model : The model wrapped with utility functions to perform object detection (applies regression values and performs NMS). """ modifier = freeze_model if freeze_backbone else None anchor_params = None num_anchors = None model = self._model_with_weights(backbone_retinanet(num_classes, num_anchors = num_anchors, modifier = modifier), weights = weights, skip_mismatch = True) training_model = model prediction_model = retinanet_bbox(model = model, anchor_params = anchor_params) training_model.compile( loss = { 'regression' : losses.smooth_l1(), 'classification': losses.focal() }, optimizer = keras.optimizers.adam(lr = lr, clipnorm = 0.001) ) return model, training_model, prediction_model def _num_classes(self): """ Number of classes in the dataset. """ return max(self.classes.values()) + 1 def _model_with_weights(self, model, weights, skip_mismatch): """ Load weights for model. Parameters ---------- model : The model to load weights for. weights : The weights to load. skip_mismatch : If True, skips layers whose shape of weights doesn't match with the model. Returns ------- model : Model with loaded weights. """ if weights is not None: model.load_weights(weights, by_name = True, skip_mismatch = skip_mismatch) return model def _create_generator(self, annotations, classes, shuffle_groups): """ Create generator for evaluation. """ validation_generator = CSVGenerator(self.annotations, self.classes, self.base_dir, self.hyperparams['batch_size'], self.backbone.preprocess_image, shuffle_groups = False) return validation_generator def _fill_empty_predictions(self, empty_predictions_image_names, d3mIdx_image_mapping): """ D3M metrics evaluator needs at least one prediction per image. If RetinaNet does not return predictions for an image, this method creates a dummy empty prediction row to add to results_df for that missing image. TODO: DUMMY CONFIDENCE SCORES LOWER AVERAGE PRECISION. FIND A FIX. """ # Prepare D3M index empty_predictions_d3mIdx = [d3mIdx_image_mapping.get(key) for key in empty_predictions_image_names] empty_predictions_d3mIdx = [item for sublist in empty_predictions_d3mIdx for item in sublist] # Prepare dummy columns d3mIdx = empty_predictions_d3mIdx bounding_box = ["0,0,0,0,0,0,0,0"] * len(empty_predictions_d3mIdx) confidence = [float(0)] * len(empty_predictions_d3mIdx) empty_predictions_df = pd.DataFrame({ 'd3mIndex': d3mIdx, 'bounding_box': bounding_box, 'confidence': confidence }) return empty_predictions_df def fit(self, *, timeout: float = None, iterations: int = None) -> CallResult[None]: """ Creates the image generators and then trains RetinaNet model on the image paths in the input dataframe column. Can choose to use validation generator. If no weight file is provided, the default is to use the ImageNet weights. """ # Create object that stores backbone information self.backbone = models.backbone(self.hyperparams['backbone']) # Create the generators train_generator = CSVGenerator(self.annotations, self.classes, self.base_dir, self.hyperparams['batch_size'], self.backbone.preprocess_image) # Running the model ## Assign weights if self.hyperparams['weights'] is False: weights = None else: weights = self.volumes[self.hyperparams['backbone']] ## Create model print('Creating model...', file = sys.__stdout__) model, self.training_model, prediction_model = self._create_models( backbone_retinanet = self.backbone.retinanet, num_classes = train_generator.num_classes(), weights = weights, freeze_backbone = self.hyperparams['freeze_backbone'], lr = self.hyperparams['learning_rate'] ) model.summary() ### !!! vgg AND densenet BACKBONES CURRENTLY NOT IMPLEMENTED !!! ## Let the generator compute the backbone layer shapes using the actual backbone model # if 'vgg' in self.hyperparams['backbone'] or 'densenet' in self.hyperparams['backbone']: # train_generator.compute_shapes = make_shapes_callback(model) # if validation_generator: # validation_generator.compute_shapes = train_generator.compute_shapes ## Set up callbacks callbacks = self._create_callbacks( model, self.training_model, prediction_model, ) start_time = time.time() print('Starting training...', file = sys.__stdout__) self.training_model.fit_generator( generator = train_generator, steps_per_epoch = self.hyperparams['n_steps'], epochs = self.hyperparams['n_epochs'], verbose = 1, callbacks = callbacks, workers = self.workers, use_multiprocessing = self.multiprocessing, max_queue_size = self.max_queue_size ) print(f'Training complete. Training took {time.time()-start_time} seconds.', file = sys.__stdout__) return CallResult(None) def produce(self, *, inputs: Inputs, timeout: float = None, iterations: int = None) -> CallResult[Outputs]: """ Produce image detection predictions. Parameters ---------- inputs : numpy ndarray of size (n_images, dimension) containing the d3m Index, image name, and bounding box for each image. Returns ------- outputs : A d3m dataframe container with the d3m index, image name, bounding boxes as a string (8 coordinate format), and confidence scores. """ iou_threshold = 0.5 # Bounding box overlap threshold for false positive or true positive score_threshold = 0.05 # The score confidence threshold to use for detections max_detections = 100 # Maxmimum number of detections to use per image # Convert training model to inference model inference_model = models.convert_model(self.training_model) # Generate image paths image_cols = inputs.metadata.get_columns_with_semantic_type('https://metadata.datadrivendiscovery.org/types/FileName') self.base_dir = [inputs.metadata.query((metadata_base.ALL_ELEMENTS, t))['location_base_uris'][0].replace('file:///', '/') for t in image_cols] self.image_paths = np.array([[os.path.join(self.base_dir, filename) for filename in inputs.iloc[:,col]] for self.base_dir, col in zip(self.base_dir, image_cols)]).flatten() self.image_paths = pd.Series(self.image_paths) # Initialize output objects box_list = [] score_list = [] image_name_list = [] # Predict bounding boxes and confidence scores for each image image_list = [x for i, x in enumerate(self.image_paths.tolist()) if self.image_paths.tolist().index(x) == i] start_time = time.time() print('Starting testing...', file = sys.__stdout__) for i in image_list: image = read_image_bgr(i) # preprocess image for network image = preprocess_image(image) image, scale = resize_image(image) boxes, scores, labels = inference_model.predict_on_batch(tf.constant(np.expand_dims(image, axis = 0), dtype = tf.float32)) # correct for image scale boxes /= scale for box, score in zip(boxes[0], scores[0]): if score < 0.5: break b = box.astype(int) box_list.append(b) score_list.append(score) image_name_list.append(i * len(b)) print(f'Testing complete. Testing took {time.time()-start_time} seconds.', file = sys.__stdout__) ## Convert predicted boxes from a list of arrays to a list of strings boxes = np.array(box_list).tolist() boxes = list(map(lambda x : [x[0], x[1], x[0], x[3], x[2], x[3], x[2], x[1]], boxes)) # Convert to 8 coordinate format for D3M boxes = list(map(lambda x : ",".join(map(str, x)), boxes)) # Create mapping between image names and D3M index input_df = pd.DataFrame({ 'd3mIndex': inputs.d3mIndex, 'image': [os.path.basename(list) for list in self.image_paths] }) d3mIdx_image_mapping = input_df.set_index('image').T.to_dict('list') # Extract values for image name keys and get missing image predictions (if they exist) image_name_list = [os.path.basename(list) for list in image_name_list] d3mIdx = [d3mIdx_image_mapping.get(key) for key in image_name_list] empty_predictions_image_names = [k for k,v in d3mIdx_image_mapping.items() if v not in d3mIdx] d3mIdx = [item for sublist in d3mIdx for item in sublist] # Flatten list of lists ## Assemble in a Pandas DataFrame results = pd.DataFrame({ 'd3mIndex': d3mIdx, 'bounding_box': boxes, 'confidence': score_list }) # D3M metrics evaluator needs at least one prediction per image. If RetinaNet does not return # predictions for an image, create a dummy empty prediction row to add to results_df for that # missing image. if len(empty_predictions_image_names) != 0: # Create data frame of empty predictions for missing each image and concat with results. # Sort results_df. empty_predictions_df = self._fill_empty_predictions(empty_predictions_image_names, d3mIdx_image_mapping) results_df = pd.concat([results, empty_predictions_df]).sort_values('d3mIndex') else: results_df = results # Convert to DataFrame container results_df = d3m_DataFrame(results_df) ## Assemble first output column ('d3mIndex) col_dict = dict(results_df.metadata.query((metadata_base.ALL_ELEMENTS, 0))) col_dict['structural_type'] = type("1") col_dict['name'] = 'd3mIndex' col_dict['semantic_types'] = ('http://schema.org/Integer', 'https://metadata.datadrivendiscovery.org/types/PrimaryKey') results_df.metadata = results_df.metadata.update((metadata_base.ALL_ELEMENTS, 0), col_dict) ## Assemble second output column ('bounding_box') col_dict = dict(results_df.metadata.query((metadata_base.ALL_ELEMENTS, 1))) col_dict['structural_type'] = type("1") col_dict['name'] = 'bounding_box' col_dict['semantic_types'] = ('http://schema.org/Text', 'https://metadata.datadrivendiscovery.org/types/PredictedTarget', 'https://metadata.datadrivendiscovery.org/types/BoundingPolygon') results_df.metadata = results_df.metadata.update((metadata_base.ALL_ELEMENTS, 1), col_dict) ## Assemble third output column ('confidence') col_dict = dict(results_df.metadata.query((metadata_base.ALL_ELEMENTS, 2))) col_dict['structural_type'] = type("1") col_dict['name'] = 'confidence' col_dict['semantic_types'] = ('http://schema.org/Integer', 'https://metadata.datadrivendiscovery.org/types/Score') results_df.metadata = results_df.metadata.update((metadata_base.ALL_ELEMENTS, 2), col_dict) return CallResult(results_df)
[ "os.path.join", "pandas.DataFrame", "keras.optimizers.adam", "os.path.dirname", "object_detection_retinanet.models.backbone", "object_detection_retinanet.models.retinanet.retinanet_bbox", "d3m.container.DataFrame", "keras.callbacks.ReduceLROnPlateau", "pandas.concat", "object_detection_retinanet.u...
[((8002, 8029), 'pandas.Series', 'pd.Series', (['self.image_paths'], {}), '(self.image_paths)\n', (8011, 8029), True, 'import pandas as pd\n'), ((8431, 8469), 'pandas.Series', 'pd.Series', (["(['class'] * inputs.shape[0])"], {}), "(['class'] * inputs.shape[0])\n", (8440, 8469), True, 'import pandas as pd\n'), ((8534, 8600), 'pandas.concat', 'pd.concat', (['[self.image_paths, bounding_coords, class_name]'], {'axis': '(1)'}), '([self.image_paths, bounding_coords, class_name], axis=1)\n', (8543, 8600), True, 'import pandas as pd\n'), ((8739, 8795), 'pandas.DataFrame', 'pd.DataFrame', (["{'class_name': ['class'], 'class_id': [0]}"], {}), "({'class_name': ['class'], 'class_id': [0]})\n", (8751, 8795), True, 'import pandas as pd\n'), ((11187, 11243), 'object_detection_retinanet.models.retinanet.retinanet_bbox', 'retinanet_bbox', ([], {'model': 'model', 'anchor_params': 'anchor_params'}), '(model=model, anchor_params=anchor_params)\n', (11201, 11243), False, 'from object_detection_retinanet.models.retinanet import retinanet_bbox\n'), ((12478, 12632), 'object_detection_retinanet.preprocessing.csv_generator.CSVGenerator', 'CSVGenerator', (['self.annotations', 'self.classes', 'self.base_dir', "self.hyperparams['batch_size']", 'self.backbone.preprocess_image'], {'shuffle_groups': '(False)'}), "(self.annotations, self.classes, self.base_dir, self.\n hyperparams['batch_size'], self.backbone.preprocess_image,\n shuffle_groups=False)\n", (12490, 12632), False, 'from object_detection_retinanet.preprocessing.csv_generator import CSVGenerator\n'), ((13578, 13672), 'pandas.DataFrame', 'pd.DataFrame', (["{'d3mIndex': d3mIdx, 'bounding_box': bounding_box, 'confidence': confidence}"], {}), "({'d3mIndex': d3mIdx, 'bounding_box': bounding_box,\n 'confidence': confidence})\n", (13590, 13672), True, 'import pandas as pd\n'), ((14226, 14271), 'object_detection_retinanet.models.backbone', 'models.backbone', (["self.hyperparams['backbone']"], {}), "(self.hyperparams['backbone'])\n", (14241, 14271), False, 'from object_detection_retinanet import models\n'), ((14331, 14459), 'object_detection_retinanet.preprocessing.csv_generator.CSVGenerator', 'CSVGenerator', (['self.annotations', 'self.classes', 'self.base_dir', "self.hyperparams['batch_size']", 'self.backbone.preprocess_image'], {}), "(self.annotations, self.classes, self.base_dir, self.\n hyperparams['batch_size'], self.backbone.preprocess_image)\n", (14343, 14459), False, 'from object_detection_retinanet.preprocessing.csv_generator import CSVGenerator\n'), ((15787, 15798), 'time.time', 'time.time', ([], {}), '()\n', (15796, 15798), False, 'import time\n'), ((16398, 16414), 'd3m.primitive_interfaces.base.CallResult', 'CallResult', (['None'], {}), '(None)\n', (16408, 16414), False, 'from d3m.primitive_interfaces.base import PrimitiveBase, CallResult\n'), ((17354, 17395), 'object_detection_retinanet.models.convert_model', 'models.convert_model', (['self.training_model'], {}), '(self.training_model)\n', (17374, 17395), False, 'from object_detection_retinanet import models\n'), ((17914, 17941), 'pandas.Series', 'pd.Series', (['self.image_paths'], {}), '(self.image_paths)\n', (17923, 17941), True, 'import pandas as pd\n'), ((18264, 18275), 'time.time', 'time.time', ([], {}), '()\n', (18273, 18275), False, 'import time\n'), ((20283, 20370), 'pandas.DataFrame', 'pd.DataFrame', (["{'d3mIndex': d3mIdx, 'bounding_box': boxes, 'confidence': score_list}"], {}), "({'d3mIndex': d3mIdx, 'bounding_box': boxes, 'confidence':\n score_list})\n", (20295, 20370), True, 'import pandas as pd\n'), ((21147, 21172), 'd3m.container.DataFrame', 'd3m_DataFrame', (['results_df'], {}), '(results_df)\n', (21160, 21172), True, 'from d3m.container import DataFrame as d3m_DataFrame\n'), ((22793, 22815), 'd3m.primitive_interfaces.base.CallResult', 'CallResult', (['results_df'], {}), '(results_df)\n', (22803, 22815), False, 'from d3m.primitive_interfaces.base import PrimitiveBase, CallResult\n'), ((9473, 9614), 'keras.callbacks.ReduceLROnPlateau', 'keras.callbacks.ReduceLROnPlateau', ([], {'monitor': '"""loss"""', 'factor': '(0.1)', 'patience': '(2)', 'verbose': '(1)', 'mode': '"""auto"""', 'min_delta': '(0.0001)', 'cooldown': '(0)', 'min_lr': '(0)'}), "(monitor='loss', factor=0.1, patience=2,\n verbose=1, mode='auto', min_delta=0.0001, cooldown=0, min_lr=0)\n", (9506, 9614), False, 'import keras\n'), ((18386, 18403), 'object_detection_retinanet.utils.image.read_image_bgr', 'read_image_bgr', (['i'], {}), '(i)\n', (18400, 18403), False, 'from object_detection_retinanet.utils.image import read_image_bgr, preprocess_image, resize_image\n'), ((18468, 18491), 'object_detection_retinanet.utils.image.preprocess_image', 'preprocess_image', (['image'], {}), '(image)\n', (18484, 18491), False, 'from object_detection_retinanet.utils.image import read_image_bgr, preprocess_image, resize_image\n'), ((18519, 18538), 'object_detection_retinanet.utils.image.resize_image', 'resize_image', (['image'], {}), '(image)\n', (18531, 18538), False, 'from object_detection_retinanet.utils.image import read_image_bgr, preprocess_image, resize_image\n'), ((19899, 19921), 'os.path.basename', 'os.path.basename', (['list'], {}), '(list)\n', (19915, 19921), False, 'import os\n'), ((11445, 11489), 'keras.optimizers.adam', 'keras.optimizers.adam', ([], {'lr': 'lr', 'clipnorm': '(0.001)'}), '(lr=lr, clipnorm=0.001)\n', (11466, 11489), False, 'import keras\n'), ((19234, 19252), 'numpy.array', 'np.array', (['box_list'], {}), '(box_list)\n', (19242, 19252), True, 'import numpy as np\n'), ((11336, 11354), 'object_detection_retinanet.losses.smooth_l1', 'losses.smooth_l1', ([], {}), '()\n', (11352, 11354), False, 'from object_detection_retinanet import losses\n'), ((11391, 11405), 'object_detection_retinanet.losses.focal', 'losses.focal', ([], {}), '()\n', (11403, 11405), False, 'from object_detection_retinanet import losses\n'), ((18621, 18650), 'numpy.expand_dims', 'np.expand_dims', (['image'], {'axis': '(0)'}), '(image, axis=0)\n', (18635, 18650), True, 'import numpy as np\n'), ((19634, 19656), 'os.path.basename', 'os.path.basename', (['list'], {}), '(list)\n', (19650, 19656), False, 'import os\n'), ((20970, 21012), 'pandas.concat', 'pd.concat', (['[results, empty_predictions_df]'], {}), '([results, empty_predictions_df])\n', (20979, 21012), True, 'import pandas as pd\n'), ((16325, 16336), 'time.time', 'time.time', ([], {}), '()\n', (16334, 16336), False, 'import time\n'), ((19073, 19084), 'time.time', 'time.time', ([], {}), '()\n', (19082, 19084), False, 'import time\n'), ((7832, 7869), 'os.path.join', 'os.path.join', (['self.base_dir', 'filename'], {}), '(self.base_dir, filename)\n', (7844, 7869), False, 'import os\n'), ((17744, 17781), 'os.path.join', 'os.path.join', (['self.base_dir', 'filename'], {}), '(self.base_dir, filename)\n', (17756, 17781), False, 'import os\n'), ((5866, 5891), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (5881, 5891), False, 'import os\n')]
# Copyright 2020 Verily Life Sciences LLC # # Use of this source code is governed by a BSD-style # license that can be found in the LICENSE file or at # https://developers.google.com/open-source/licenses/bsd """Utilities for simulating recruitment and infection of trial participants.""" # I know you mean well, pytype, but I'd like my janky JaxDataset. # pytype: skip-file from typing import List from flax import nn import jax.numpy as jnp import numpy as np import xarray as xr from bsst import sim_scenarios from bsst import util class JaxDataset: """Roughly a xr.Dataset with all arrays turned into jnp.arrays. Warning: this doesn't do any intelligent broadcasting or indexing. It just shoves array values into jnp.arrays. """ def __init__(self, ds): for var_name, var in ds.data_vars.items(): if var.dtype == np.dtype('O'): print(f'Skipping jax conversion of {var_name} (dtype is "object")') continue if var.dims: setattr(self, var_name, jnp.array(var.values)) elif np.issubdtype(var.dtype, np.datetime64): setattr(self, var_name, var.values) else: setattr(self, var_name, var.item()) def __repr__(self): return repr(self.__dict__) def cumsum_capper(x, threshold): """A multiplier for capping the cumsum of x to the given threshold. Args: x: one-dimensional xr.DataArray with non-negative values. threshold: maximum desired cumsum value. Returns: An xr.DataArray with the same shape as x with the property that (result * x).cumsum() = where(x.cumsum() < threshold, x.cumsum(), threshold) """ # The variable naming here assumes the coordinate is time and the intervals # are days. cumsum = x.cumsum() time = x.dims[0] first_idx_over = np.searchsorted(cumsum, threshold) if first_idx_over == len(x): # No capping necessary because cumsum never hits the threshold. return xr.ones_like(x) x_that_day = x.isel({time: first_idx_over}) if first_idx_over == 0: x_allowed_that_day = threshold else: x_allowed_that_day = (threshold - cumsum.isel({time: first_idx_over - 1})) scale_that_day = x_allowed_that_day / x_that_day capper = xr.ones_like(x) capper[first_idx_over] = scale_that_day capper[first_idx_over + 1:] = 0.0 return capper def differentiable_cumsum_capper(x, threshold, width): """Starts out 1 and decays to 0 so that (result * x).cumsum() <= threshold.""" cumsum = x.cumsum() capped_cumsum = threshold - width * nn.softplus((threshold - cumsum) / width) capped_x = jnp.concatenate([x[:1], jnp.diff(capped_cumsum)]) # The "double where" trick is needed to ensure non-nan gradients here. See # https://github.com/google/jax/issues/1052#issuecomment-514083352 nonzero_x = jnp.where(x == 0.0, 1.0, x) capper = jnp.where(x == 0.0, 0.0, capped_x / nonzero_x) return capper def differentiable_greater_than(x, threshold, width): """A smoothed version of (x > threshold).astype(float).""" return nn.sigmoid((x - threshold) / width) def recruitment_rules_simple(c: xr.Dataset) -> List[str]: return [f'At most {c.trial_size_cap.item()} participants can be recruited.'] def recruitment_simple(c: xr.Dataset) -> xr.DataArray: # pyformat: disable """Returns new recruited participants each day. Args: c: xr.Dataset capturing recruitment rules. This is required to have data variables with the following names and shapes: * site_activation [location, time], 0-to-1 float valued array indicating what proportion of its capacity each site recruits on each future day. * site_capacity [location, time], the maximum number of new recruits at each site on each future day. * historical_participants [location, historical_time, ...], the number of participants recruited at each location in each demographic bucket for each day in the past. * participant_fraction [location, ...], the proportion of recruits at a given location falling into given demographic buckets. * trial_size_cap [], maximum number of participants. Returns: An xr.DataArray of shape [location, time, ...], the number of participants recruited at a given location on a given day within each demographic bucket. This includes both control and vaccine arms. The time dimension of this array includes both the past and the future. """ # pyformat: enable if c.site_activation.isnull().any(): raise ValueError('NaNs in site_activation array!') if c.site_capacity.isnull().any(): raise ValueError('NaNs in site_capacity array!') if c.historical_participants.isnull().any(): raise ValueError('NaNs in historical_participants array!') if c.participant_fraction.isnull().any(): raise ValueError('NaNs in participant_fraction array!') if c.trial_size_cap.isnull(): raise ValueError('trial_size_cap is NaN!') future_participants = c.site_activation * c.site_capacity # Prepend historical_participants, which is assumed to start on start_day. historical = c.historical_participants.rename(historical_time='time') historical = util.sum_all_but_dims(['location', 'time'], historical) participants = xr.concat([historical, future_participants], dim='time') # After the trial size is reached globally, all locations must stop # recruiting. capper = cumsum_capper(participants.sum('location'), c.trial_size_cap) participants *= capper # Break into demographic buckets. fractions = ( c.participant_fraction / util.sum_all_but_dims(['location'], c.participant_fraction)) participants = participants * fractions # Overwrite historical participants; the fractions are wrong otherwise. the_future = (future_participants.time.values[0] <= participants.time) participants = xr.concat([ c.historical_participants.rename(historical_time='time'), participants.sel(time=the_future) ], dim='time') # Ensure the dimensions are ordered correctly. dims = ('location', 'time') + c.participant_fraction.dims[1:] return participants.transpose(*dims).rename('participants') def differentiable_recruitment_simple(c: JaxDataset, width=1 / 3.): """Smoothed version of recruitment_simple with jnp.arrays. It is expected that the values of recruitment_simple(c) closely matches differentiable_recruitment_simple(JaxDataset(c)), especially with small width. Args: c: a JaxDataset specifying the trial. See the documentation of recruitment_simple for what fields are required. width: how sharp the smoothed step functions should be, measured approximately in days. Returns: A jnp.array of shape [location, time, ...], the number of participants recruited at a given location on a given day within each demographic bucket. This includes both control and vaccine arms. The time dimension of this array includes both the past and the future. """ # [future_]participants is of shape [location, start_time] future_participants = c.site_activation * c.site_capacity # Prepend historical_participants, which is assumed to start on start_day. historical = c.historical_participants historical = util.sum_all_but_axes([0, 1], historical) participants = jnp.concatenate([historical, future_participants], axis=1) first_future_idx = historical.shape[1] mean_daily_recruitment = util.sum_all_but_axes([1], participants).mean() # After the trial size is reached globally, all locations must stop # recruiting. capper = differentiable_cumsum_capper( participants.sum(axis=0), c.trial_size_cap, width=mean_daily_recruitment * width) participants = participants * capper[jnp.newaxis, :] # Break into demographic buckets. fractions = ( c.participant_fraction / util.sum_all_but_axes([0], c.participant_fraction, keepdims=True)) fractions = fractions[:, jnp.newaxis, ...] # add dimension for time # Add dimensions for demographic labels. for _ in range(len(c.participant_fraction.shape) - 1): participants = participants[..., jnp.newaxis] participants = participants * fractions # Overwrite historical participants; the fractions are wrong otherwise. participants = jnp.concatenate( [c.historical_participants, participants[:, first_future_idx:]], axis=1) return participants def control_arm_events(c, participants, incidence_scenarios, keep_location=False): # pyformat: disable """Returns numbers of control arm events over time in the future. Args: c: a xr.Dataset specifying the trial. This is required to have data variables with the following names and shapes: * proportion_control_arm [], what fraction of participants are in the control arm of the trial. * observation_delay [], how long after a participant is recruited before they enter the observation period. * incidence_scaler [...], the relative risk of a participant in a given demographic bucket. * incidence_to_event_factor [...], the proportion of incidence which meets the criteria to be a trial event. * population_fraction [location, ...], the proportion of the population in each demographic bucket in each location. participants: xr.DataArray of shape [location, time, ...], the number of participants recruited each day at each location in each demographic bucket. This includes both control and vaccine arms. The time dimension of this array includes both the past and the future. incidence_scenarios: xr.DataArray of shape [scenario, location, time], the fraction of the population at each location who will be infected on each day in the future. keep_location: If True, don't sum over the location dimension. Returns: A xr.DataArray of shape [scenario, time] (or [scenario, location, time] if keep_location is True), the number of events each day in the control arm of the trial in each scenario. """ # pyformat: enable if c.proportion_control_arm.isnull(): raise ValueError('proportion_control_arm is NaN!') if c.observation_delay.isnull(): raise ValueError('observation_delay is NaN!') if c.incidence_scaler.isnull().any(): raise ValueError('NaNs in incidence_scaler array!') if c.incidence_to_event_factor.isnull().any(): raise ValueError('NaNs in incidence_to_event_factor array!') if c.population_fraction.isnull().any(): raise ValueError('NaNs in population_fraction array!') if participants.isnull().any(): raise ValueError('NaNs in participants array!') if incidence_scenarios.isnull().any(): raise ValueError('NaNs in incidence_scenarios array!') observation_delay = int(c.observation_delay) if observation_delay < 0 or participants.time.size < observation_delay: raise ValueError(f'Observation delay ({observation_delay}) is negative or ' f'greater than the trial duration.') # Restrict to control arm participants. participants = participants * c.proportion_control_arm # Switch to start of observation instead of recruitment date. participants = participants.shift(time=observation_delay).fillna(0.0) # Treat all participants whose observation period starts on or before the # first day of forecast as starting on the first day of forecast. immediate_participants = participants.sel( time=( participants.time <= incidence_scenarios.time.values[0])).sum('time') immediate_participants = immediate_participants.expand_dims( 'time').assign_coords(dict(time=incidence_scenarios.time.values[:1])) participants = xr.concat([ immediate_participants, participants.sel(time=incidence_scenarios.time.values[1:]) ], dim='time') participants = participants.rename(time='observation_start') # Incidence for a subpopulation with incidence_scaler 1.0. Its shape is # [scenario, location, time]. normalizing_constant = c.population_fraction.dot(c.incidence_scaler) bad_locations = list( normalizing_constant.location.values[(normalizing_constant == 0).values]) if bad_locations: print(bad_locations) raise ValueError( 'The following locations have no people in the population who can get ' 'infected (i.e. population_fraction.dot(incidence_scaler) is zero). It ' 'is impossible to account for incidence!\n' + ','.join(bad_locations)) baseline_incidence = incidence_scenarios / normalizing_constant # The effective number of "unit risk" participants who start observation each # day. Its shape is [location, observation_start]. By dotting out the # dimensions having to do with demographic labels early, we avoid # instantiating a huge array when we multiply by baseline_incidence; # an array of shape [scenario, location, time, observation_start] (when # keep_location=True) is large enough without additional dimensions for # demographics. event_factor = c.incidence_scaler * c.incidence_to_event_factor effective_participants = participants.dot(event_factor) if keep_location: ctrl_arm_events = baseline_incidence * effective_participants final_dims = ('scenario', 'location', 'time') else: ctrl_arm_events = baseline_incidence.dot(effective_participants) final_dims = ('scenario', 'time') # You cannot have an event before the start of observation. ctrl_arm_events = xr.where( baseline_incidence.time < effective_participants.observation_start, 0.0, ctrl_arm_events) return ctrl_arm_events.sum('observation_start').transpose(*final_dims) def shift_pad_zeros(arr, shift, axis): """Like jnp.roll, but fills with zeros instead of wrapping around.""" axis = axis % len(arr.shape) # to handle things like axis=-1 sl = (slice(None),) * axis zeros = jnp.zeros_like(arr[sl + (slice(0, shift),)]) trim_last_n = slice(None, arr.shape[axis] - shift) return jnp.concatenate([zeros, arr[sl + (trim_last_n,)]], axis=axis) def differentiable_control_arm_events(c, participants, incidence_scenarios): """Smoothed version of control_arm_events with jnp.arrays. Args: c: a jax-ified TrialConfig specifying the trial. participants: jnp.array of shape [location, time, age, ...], the number of participants recruited each day at each location in each demographic bucket. This includes both control and vaccine arms. incidence_scenarios: jnp.array of shape [scenario, location, time], the fraction of the population at each location who will be infected on each day. Returns: A jnp.array of shape [scenario, time], the number of events each day in the control arm of the trial in each scenario. """ # Restrict to control arm participants. participants = participants * c.proportion_control_arm # Switch from recruitment date to the start of observation. The shape of # participants is now [location, observation_start, age, ...]. participants = shift_pad_zeros(participants, c.observation_delay, axis=1) # Treat all participants whose observation period starts on or before the # first day of forecast as starting on the first day of forecast. second_day_of_forecast = -incidence_scenarios.shape[2] + 1 immediate_participants = participants[:, :second_day_of_forecast].sum( axis=1, keepdims=True) participants = jnp.concatenate( [immediate_participants, participants[:, second_day_of_forecast:]], axis=1) # Incidence for a subpopulation with incidence_scaler 1.0. Its shape is # [scenario, location, time]. normalizing_constant = jnp.einsum('l...,...->l', c.population_fraction, c.incidence_scaler) normalizing_constant = normalizing_constant[jnp.newaxis, :, jnp.newaxis] baseline_incidence = incidence_scenarios / normalizing_constant # The effective number of "unit risk" participants who start observation each # day. Its shape is [location, observation_start]. event_factor = c.incidence_scaler * c.incidence_to_event_factor effective_participants = jnp.einsum('lo...,...->lo', participants, event_factor) ctrl_arm_events = jnp.einsum('slt,lo->sto', baseline_incidence, effective_participants) # You cannot have an event before the start of observation. t_less_than_o = (slice(None),) + jnp.triu_indices_from( ctrl_arm_events[0], k=1) ctrl_arm_events = ctrl_arm_events.at[t_less_than_o].set(0.0) return ctrl_arm_events.sum(axis=-1) RECRUITMENT_REGISTRY = dict() def register_recruitment_type(name, recruitment_fn, differentiable_fn, rules_fn): """Register a recruitment scheme. Args: name: a string to identify the recruitment scheme. recruitment_fn: a function which takes an xr.Dataset specifying the trial and returns an xr.DataArray of recruited participants. differentiable_fn: a differentiable version of recruitment_fn which takes a jax-ified trial dataset and returns a jnp.array. This function is assumed to also have an optional `width` argument specifying the amount of smoothing. If width is made close to 0.0, differentiable_fn(JaxDataset(c), width) should be very close to recruitment_fn(c).values. rules_fn: a function which takes an xr.Dataset specifying the trial and returns a list of human-readable descriptions of what rules are used for recruitment. """ RECRUITMENT_REGISTRY[name] = (recruitment_fn, differentiable_fn, rules_fn) register_recruitment_type('default', recruitment_simple, differentiable_recruitment_simple, recruitment_rules_simple) def get_recruitment_type(c): if 'recruitment_type' in c: return c.recruitment_type.item() return 'default' def recruitment(c: xr.Dataset) -> xr.DataArray: recruitment_fn, _, _ = RECRUITMENT_REGISTRY[get_recruitment_type(c)] return recruitment_fn(c) def recruitment_rules(c: xr.Dataset): _, _, rules_fn = RECRUITMENT_REGISTRY[get_recruitment_type(c)] return rules_fn(c) def add_stuff_to_ville(c, incidence_model, site_df, num_scenarios=300): """Adds incidence and site data we've deemed important to a trial dataset. Args: c: xr.Dataset, a trial config suitable for running recruitment and event simulation. incidence_model: xr.DataArray of shape [model, sample, location, time], the forecast incidence. site_df: pd.Dataframe with information about sites. num_scenarios: the number of scenarios to generate. """ included_days = np.logical_and(c.time.values[0] <= incidence_model.time, incidence_model.time <= c.time.values[-1]) incidence_model = incidence_model.sel(time=included_days) c['incidence_model'] = incidence_model c['incidence_flattened'] = sim_scenarios.get_incidence_flattened( c.incidence_model, c) c['incidence_scenarios'] = sim_scenarios.generate_scenarios_independently( c.incidence_flattened, num_scenarios) if 'participants' not in c.data_vars: print('Populating participants.') participants = recruitment(c) c['participants'] = participants.sel(time=c.time) else: participants = c.participants if 'control_arm_events' not in c.data_vars: print('Populating control_arm_events based on independent scenarios.') ctrl_arm_events = control_arm_events( c, participants, c.incidence_scenarios, keep_location=True) c['control_arm_events'] = ctrl_arm_events site_fields = [ 'subregion1_name', 'subregion2_name', 'address', 'lat', 'lon', 'opencovid_key', 'population', 'site_name', 'site_id', 'full_population', ] for f in site_fields: if f in site_df.columns: c[f] = site_df[f].to_xarray()
[ "jax.numpy.where", "jax.numpy.einsum", "bsst.sim_scenarios.get_incidence_flattened", "xarray.where", "xarray.ones_like", "jax.numpy.concatenate", "bsst.sim_scenarios.generate_scenarios_independently", "xarray.concat", "jax.numpy.triu_indices_from", "flax.nn.sigmoid", "numpy.issubdtype", "jax.n...
[((1770, 1804), 'numpy.searchsorted', 'np.searchsorted', (['cumsum', 'threshold'], {}), '(cumsum, threshold)\n', (1785, 1804), True, 'import numpy as np\n'), ((2188, 2203), 'xarray.ones_like', 'xr.ones_like', (['x'], {}), '(x)\n', (2200, 2203), True, 'import xarray as xr\n'), ((2761, 2788), 'jax.numpy.where', 'jnp.where', (['(x == 0.0)', '(1.0)', 'x'], {}), '(x == 0.0, 1.0, x)\n', (2770, 2788), True, 'import jax.numpy as jnp\n'), ((2800, 2846), 'jax.numpy.where', 'jnp.where', (['(x == 0.0)', '(0.0)', '(capped_x / nonzero_x)'], {}), '(x == 0.0, 0.0, capped_x / nonzero_x)\n', (2809, 2846), True, 'import jax.numpy as jnp\n'), ((2989, 3024), 'flax.nn.sigmoid', 'nn.sigmoid', (['((x - threshold) / width)'], {}), '((x - threshold) / width)\n', (2999, 3024), False, 'from flax import nn\n'), ((5122, 5177), 'bsst.util.sum_all_but_dims', 'util.sum_all_but_dims', (["['location', 'time']", 'historical'], {}), "(['location', 'time'], historical)\n", (5143, 5177), False, 'from bsst import util\n'), ((5195, 5251), 'xarray.concat', 'xr.concat', (['[historical, future_participants]'], {'dim': '"""time"""'}), "([historical, future_participants], dim='time')\n", (5204, 5251), True, 'import xarray as xr\n'), ((7201, 7242), 'bsst.util.sum_all_but_axes', 'util.sum_all_but_axes', (['[0, 1]', 'historical'], {}), '([0, 1], historical)\n', (7222, 7242), False, 'from bsst import util\n'), ((7260, 7318), 'jax.numpy.concatenate', 'jnp.concatenate', (['[historical, future_participants]'], {'axis': '(1)'}), '([historical, future_participants], axis=1)\n', (7275, 7318), True, 'import jax.numpy as jnp\n'), ((8231, 8323), 'jax.numpy.concatenate', 'jnp.concatenate', (['[c.historical_participants, participants[:, first_future_idx:]]'], {'axis': '(1)'}), '([c.historical_participants, participants[:,\n first_future_idx:]], axis=1)\n', (8246, 8323), True, 'import jax.numpy as jnp\n'), ((13489, 13591), 'xarray.where', 'xr.where', (['(baseline_incidence.time < effective_participants.observation_start)', '(0.0)', 'ctrl_arm_events'], {}), '(baseline_incidence.time < effective_participants.observation_start,\n 0.0, ctrl_arm_events)\n', (13497, 13591), True, 'import xarray as xr\n'), ((13998, 14059), 'jax.numpy.concatenate', 'jnp.concatenate', (['[zeros, arr[sl + (trim_last_n,)]]'], {'axis': 'axis'}), '([zeros, arr[sl + (trim_last_n,)]], axis=axis)\n', (14013, 14059), True, 'import jax.numpy as jnp\n'), ((15426, 15521), 'jax.numpy.concatenate', 'jnp.concatenate', (['[immediate_participants, participants[:, second_day_of_forecast:]]'], {'axis': '(1)'}), '([immediate_participants, participants[:,\n second_day_of_forecast:]], axis=1)\n', (15441, 15521), True, 'import jax.numpy as jnp\n'), ((15663, 15731), 'jax.numpy.einsum', 'jnp.einsum', (['"""l...,...->l"""', 'c.population_fraction', 'c.incidence_scaler'], {}), "('l...,...->l', c.population_fraction, c.incidence_scaler)\n", (15673, 15731), True, 'import jax.numpy as jnp\n'), ((16135, 16190), 'jax.numpy.einsum', 'jnp.einsum', (['"""lo...,...->lo"""', 'participants', 'event_factor'], {}), "('lo...,...->lo', participants, event_factor)\n", (16145, 16190), True, 'import jax.numpy as jnp\n'), ((16250, 16319), 'jax.numpy.einsum', 'jnp.einsum', (['"""slt,lo->sto"""', 'baseline_incidence', 'effective_participants'], {}), "('slt,lo->sto', baseline_incidence, effective_participants)\n", (16260, 16319), True, 'import jax.numpy as jnp\n'), ((18684, 18788), 'numpy.logical_and', 'np.logical_and', (['(c.time.values[0] <= incidence_model.time)', '(incidence_model.time <= c.time.values[-1])'], {}), '(c.time.values[0] <= incidence_model.time, incidence_model.\n time <= c.time.values[-1])\n', (18698, 18788), True, 'import numpy as np\n'), ((18947, 19006), 'bsst.sim_scenarios.get_incidence_flattened', 'sim_scenarios.get_incidence_flattened', (['c.incidence_model', 'c'], {}), '(c.incidence_model, c)\n', (18984, 19006), False, 'from bsst import sim_scenarios\n'), ((19043, 19131), 'bsst.sim_scenarios.generate_scenarios_independently', 'sim_scenarios.generate_scenarios_independently', (['c.incidence_flattened', 'num_scenarios'], {}), '(c.incidence_flattened,\n num_scenarios)\n', (19089, 19131), False, 'from bsst import sim_scenarios\n'), ((1915, 1930), 'xarray.ones_like', 'xr.ones_like', (['x'], {}), '(x)\n', (1927, 1930), True, 'import xarray as xr\n'), ((5527, 5586), 'bsst.util.sum_all_but_dims', 'util.sum_all_but_dims', (["['location']", 'c.participant_fraction'], {}), "(['location'], c.participant_fraction)\n", (5548, 5586), False, 'from bsst import util\n'), ((7809, 7874), 'bsst.util.sum_all_but_axes', 'util.sum_all_but_axes', (['[0]', 'c.participant_fraction'], {'keepdims': '(True)'}), '([0], c.participant_fraction, keepdims=True)\n', (7830, 7874), False, 'from bsst import util\n'), ((16449, 16495), 'jax.numpy.triu_indices_from', 'jnp.triu_indices_from', (['ctrl_arm_events[0]'], {'k': '(1)'}), '(ctrl_arm_events[0], k=1)\n', (16470, 16495), True, 'import jax.numpy as jnp\n'), ((2496, 2537), 'flax.nn.softplus', 'nn.softplus', (['((threshold - cumsum) / width)'], {}), '((threshold - cumsum) / width)\n', (2507, 2537), False, 'from flax import nn\n'), ((2575, 2598), 'jax.numpy.diff', 'jnp.diff', (['capped_cumsum'], {}), '(capped_cumsum)\n', (2583, 2598), True, 'import jax.numpy as jnp\n'), ((7388, 7428), 'bsst.util.sum_all_but_axes', 'util.sum_all_but_axes', (['[1]', 'participants'], {}), '([1], participants)\n', (7409, 7428), False, 'from bsst import util\n'), ((842, 855), 'numpy.dtype', 'np.dtype', (['"""O"""'], {}), "('O')\n", (850, 855), True, 'import numpy as np\n'), ((1035, 1074), 'numpy.issubdtype', 'np.issubdtype', (['var.dtype', 'np.datetime64'], {}), '(var.dtype, np.datetime64)\n', (1048, 1074), True, 'import numpy as np\n'), ((1001, 1022), 'jax.numpy.array', 'jnp.array', (['var.values'], {}), '(var.values)\n', (1010, 1022), True, 'import jax.numpy as jnp\n')]
import pandas as pd import numpy as np # import matplotlib.pyplot as plt # import seaborn as sns # import all models from sklearn.linear_model import LogisticRegression from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import RandomForestClassifier import sklearn.model_selection as model_selection import xgboost as xgb import lightgbm as lgb # import all metrics import sklearn.metrics as metrics import warnings warnings.filterwarnings("ignore") # create a class response_encoding which fit and transform the categorical columns class response_encoding: """ This function is used to fit and transform the dataframe in one go. This is only made for binary classification problems. """ def __init__(self, cols, target="Churn", alpha=0, target_value=1): """ Parameters: ----------- cols: list of categorical columns target: the target column alpha: the smoothing parameter target_value: the target value """ self.cols = cols self.master_dict = {} # storing the original values self.alpha = alpha # smoothing parameter self.target = target self.target_value = 1 def fit(self, df): alpha = self.alpha target = self.target for column in self.cols: unique_values = df[ column ].unique() # all unique values in that categorical column dict_values = {} # storing the response encoding values for target=1 for value in unique_values: total = len( df[df[column] == value] ) # the total no. of datapoints with 'value' catgeory sum_promoted = len( df[(df[column] == value) & (df[target] == self.target_value)] ) # no. of all datapoints with category being 'value' and target=='yes' dict_values[value] = np.round( (sum_promoted + alpha) / (total + alpha * len(unique_values)), 2 ) # storing the obtained result in a dictionary dict_values[ "UNK" ] = 0.5 # unknown categories that are not seen in train will be assigned a score of 0.5 self.master_dict[ column ] = dict_values.copy() # storing the original values in a dictionary return None def transform(self, df): for column in self.cols: df[column] = df[column].map( self.master_dict[column] ) # map the values in the column to the dictionary return df def get_data(): train = pd.read_csv("data/train.csv") test = pd.read_csv("data/test.csv") return train, test def get_cols(data): get_obj_cols = [ col for col in data.columns if data[col].dtype == "object" & col != "Churn" ] get_int_cols = [ col for col in data.columns if data[col].dtype != "object" & col != "Churn" ] return get_obj_cols, get_int_cols def get_data_with_encoding(train, test): # get data train, test = get_data() # get columns get_obj_cols, get_int_cols = get_cols(train) # define the response encoding class response_encoding_obj = response_encoding( get_obj_cols, target="Churn", alpha=0.1, target_value=1 ) # fit the response encoding class response_encoding_obj.fit(train) # transform the data train = response_encoding_obj.transform(train) test = response_encoding_obj.transform(test) return train, test, get_obj_cols, get_int_cols def get_models(weight): # define the models models = { "Decision Tree": DecisionTreeClassifier(class_weight="balanced"), "Random Forest": RandomForestClassifier( class_weight="balanced_subsample", n_jobs=-1, n_estimators=50, max_depth=10 ), "XGBoost": xgb.XGBClassifier( scale_pos_weight=weight, use_label_encoder=False, n_jobs=-1 ), "LightGBM": lgb.LGBMClassifier(class_weight="balanced", n_jobs=-1), } return models def modelling(): # get data train, test = get_data() # get response encoded data train, test, get_obj_cols, get_int_cols = get_data_with_encoding(train, test) # define x and y x_train = train.drop(["Churn"], axis=1) y_train = train["Churn"] x_test = test.drop(["Churn"], axis=1) y_test = test["Churn"] del train, test # define the cv cv = model_selection.RepeatedStratifiedKFold( n_splits=3, n_repeats=2, random_state=42 ) # define the weight # for xgboost # weight = no. of negative classes/no. of positive classes weight = (y_train == 0).sum() / (y_train == 1).sum() # get the models models = get_models(weight) for model_name, model in models.items(): scores = model_selection.cross_val_score( model, x_train, y_train, cv=cv, scoring="f1" ) print(model_name) mean = np.mean(scores) # print(f"mean f1 score: {mean}") print(mean) print("\n") if __name__ == "__main__": modelling()
[ "sklearn.ensemble.RandomForestClassifier", "lightgbm.LGBMClassifier", "warnings.filterwarnings", "pandas.read_csv", "sklearn.model_selection.cross_val_score", "sklearn.model_selection.RepeatedStratifiedKFold", "sklearn.tree.DecisionTreeClassifier", "numpy.mean", "xgboost.XGBClassifier" ]
[((440, 473), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (463, 473), False, 'import warnings\n'), ((2687, 2716), 'pandas.read_csv', 'pd.read_csv', (['"""data/train.csv"""'], {}), "('data/train.csv')\n", (2698, 2716), True, 'import pandas as pd\n'), ((2728, 2756), 'pandas.read_csv', 'pd.read_csv', (['"""data/test.csv"""'], {}), "('data/test.csv')\n", (2739, 2756), True, 'import pandas as pd\n'), ((4529, 4614), 'sklearn.model_selection.RepeatedStratifiedKFold', 'model_selection.RepeatedStratifiedKFold', ([], {'n_splits': '(3)', 'n_repeats': '(2)', 'random_state': '(42)'}), '(n_splits=3, n_repeats=2,\n random_state=42)\n', (4568, 4614), True, 'import sklearn.model_selection as model_selection\n'), ((3719, 3766), 'sklearn.tree.DecisionTreeClassifier', 'DecisionTreeClassifier', ([], {'class_weight': '"""balanced"""'}), "(class_weight='balanced')\n", (3741, 3766), False, 'from sklearn.tree import DecisionTreeClassifier\n'), ((3793, 3896), 'sklearn.ensemble.RandomForestClassifier', 'RandomForestClassifier', ([], {'class_weight': '"""balanced_subsample"""', 'n_jobs': '(-1)', 'n_estimators': '(50)', 'max_depth': '(10)'}), "(class_weight='balanced_subsample', n_jobs=-1,\n n_estimators=50, max_depth=10)\n", (3815, 3896), False, 'from sklearn.ensemble import RandomForestClassifier\n'), ((3935, 4013), 'xgboost.XGBClassifier', 'xgb.XGBClassifier', ([], {'scale_pos_weight': 'weight', 'use_label_encoder': '(False)', 'n_jobs': '(-1)'}), '(scale_pos_weight=weight, use_label_encoder=False, n_jobs=-1)\n', (3952, 4013), True, 'import xgboost as xgb\n'), ((4057, 4111), 'lightgbm.LGBMClassifier', 'lgb.LGBMClassifier', ([], {'class_weight': '"""balanced"""', 'n_jobs': '(-1)'}), "(class_weight='balanced', n_jobs=-1)\n", (4075, 4111), True, 'import lightgbm as lgb\n'), ((4905, 4982), 'sklearn.model_selection.cross_val_score', 'model_selection.cross_val_score', (['model', 'x_train', 'y_train'], {'cv': 'cv', 'scoring': '"""f1"""'}), "(model, x_train, y_train, cv=cv, scoring='f1')\n", (4936, 4982), True, 'import sklearn.model_selection as model_selection\n'), ((5046, 5061), 'numpy.mean', 'np.mean', (['scores'], {}), '(scores)\n', (5053, 5061), True, 'import numpy as np\n')]
# coding: utf-8 # Copyright (c) Max-Planck-Institut für Eisenforschung GmbH - Computational Materials Design (CM) Department # Distributed under the terms of "New BSD License", see the LICENSE file. from __future__ import print_function from itertools import islice import numbers import numpy as np import os import pandas as pd import posixpath import scipy.constants from pyiron_base import Settings, GenericParameters, GenericJob, Executable, FlattenedStorage from pyiron_atomistics import ase_to_pyiron from pyiron_contrib.atomistics.mlip.cfgs import savecfgs, loadcfgs, Cfg from pyiron_contrib.atomistics.mlip.potential import MtpPotential __author__ = "<NAME>" __copyright__ = "Copyright 2020, Max-Planck-Institut für Eisenforschung GmbH - " \ "Computational Materials Design (CM) Department" __version__ = "1.0" __maintainer__ = "<NAME>" __email__ = "<EMAIL>" __status__ = "development" __date__ = "Sep 1, 2017" s = Settings() gpa_to_ev_ang = 1e22 / scipy.constants.physical_constants['joule-electron volt relationship'][0] class Mlip(GenericJob): def __init__(self, project, job_name): super(Mlip, self).__init__(project, job_name) self.__version__ = '0.1.0' self.__name__ = "Mlip" self._executable_activate() self._job_dict = {} self.input = MlipParameter() self._command_line = CommandLine() self._potential = MtpPotential() def _executable_activate(self, enforce=False): if self._executable is None or enforce: if len(self.__module__.split(".")) > 1: self._executable = Executable( codename=self.__name__, module=self.__module__.split(".")[-2], path_binary_codes=s.resource_paths, ) else: self._executable = Executable( codename=self.__name__, path_binary_codes=s.resource_paths ) @property def calculation_dataframe(self): job_id_lst, time_step_start_lst, time_step_end_lst, time_step_delta_lst = self._job_dict_lst(self._job_dict) return pd.DataFrame({'Job id': job_id_lst, 'Start config': time_step_start_lst, 'End config': time_step_end_lst, 'Step': time_step_delta_lst}) @property def potential_files(self): pot = os.path.join(self.working_directory, 'Trained.mtp_') states = os.path.join(self.working_directory, 'state.mvs') if os.path.exists(pot) and os.path.exists(states): return [pot, states] def potential_dataframe(self, elements=None): """ :class:`pandas.DataFrame`: potential dataframe for lammps jobs .. attention:: The `elements` argument must be given for in any case for non-unary alloys, as the scrapping code from the training data is currently broken! Args: elements (list of str, optional): name of elements in this potential in the order of their indices in pyiron structures, if not given use elements seen in training data """ if elements is None: elements = self.input["species"] if elements is None: raise ValueError("elements not defined in input, elements must be explicitely passed!") if self.status.finished: return pd.DataFrame({ "Name": ["".join(elements)], "Filename": [[self.potential_files[0]]], "Model": ["Custom"], "Species": [elements], "Config": [["pair_style mlip mlip.ini\n", "pair_coeff * *\n" ]] }) @property def potential(self): if self.status.finished: return self._potential else: raise ValueError("potential only available on successfully finished jobs") def set_input_to_read_only(self): """ This function enforces read-only mode for the input classes, but it has to be implement in the individual classes. """ self.input.read_only = True self._command_line.read_only = True def add_job_to_fitting(self, job_id, time_step_start=0, time_step_end=-1, time_step_delta=10): if time_step_end == -1: time_step_end = np.shape(self.project.inspect(int(job_id))['output/generic/cells'])[0]-1 self._job_dict[job_id] = {'time_step_start': time_step_start, 'time_step_end': time_step_end, 'time_step_delta': time_step_delta} def write_input(self): restart_file_lst = [ os.path.basename(f) for f in self._restart_file_list ] + list(self._restart_file_dict.values()) if 'testing.cfg' not in restart_file_lst: species = self._write_test_set(file_name='testing.cfg', cwd=self.working_directory) species_count = len(species) self.input['species'] = species elif self.input['filepath'] != 'auto': species_count = 0 else: raise ValueError('speciescount not set') if 'training.cfg' not in restart_file_lst: self._write_training_set(file_name='training.cfg', cwd=self.working_directory) self._copy_potential(species_count=species_count, file_name='start.mtp', cwd=self.working_directory) if self.version != '1.0.0': self._command_line.activate_postprocessing() self._command_line[0] = self._command_line[0].replace('energy_auto', str(self.input['energy-weight'])) self._command_line[0] = self._command_line[0].replace('force_auto', str(self.input['force-weight'])) self._command_line[0] = self._command_line[0].replace('stress_auto', str(self.input['stress-weight'])) self._command_line[0] = self._command_line[0].replace('iteration_auto', str(int(self.input['iteration']))) self._command_line.write_file(file_name='mlip.sh', cwd=self.working_directory) def collect_logfiles(self): pass def collect_output(self): file_name = os.path.join(self.working_directory, 'diff.cfg') if os.path.exists(file_name): _, _, _, _, _, _, _, job_id_diff_lst, timestep_diff_lst = read_cgfs(file_name) else: job_id_diff_lst, timestep_diff_lst = [], [] file_name = os.path.join(self.working_directory, 'selected.cfg') if os.path.exists(file_name): _, _, _, _, _, _, _, job_id_new_training_lst, timestep_new_training_lst = read_cgfs(file_name) else: job_id_new_training_lst, timestep_new_training_lst = [], [] file_name = os.path.join(self.working_directory, 'grades.cfg') if os.path.exists(file_name): _, _, _, _, _, _, grades_lst, job_id_grades_lst, timestep_grades_lst = read_cgfs(file_name) else: grades_lst, job_id_grades_lst, timestep_grades_lst = [], [], [] self._potential.load(os.path.join(self.working_directory, "Trained.mtp_")) training_store = FlattenedStorage() training_store.add_array('energy', dtype=np.float64, shape=(1,), per='chunk') training_store.add_array('forces', dtype=np.float64, shape=(3,), per='element') training_store.add_array('stress', dtype=np.float64, shape=(6,), per='chunk') training_store.add_array('grade', dtype=np.float64, shape=(1,), per='chunk') for cfg in loadcfgs(os.path.join(self.working_directory, "training_efs.cfg")): training_store.add_chunk(len(cfg.pos), identifier=cfg.desc, energy=cfg.energy, forces=cfg.forces, stress=cfg.stresses, grade=cfg.grade ) testing_store = FlattenedStorage() testing_store.add_array('energy', dtype=np.float64, shape=(1,), per='chunk') testing_store.add_array('forces', dtype=np.float64, shape=(3,), per='element') testing_store.add_array('stress', dtype=np.float64, shape=(6,), per='chunk') testing_store.add_array('grade', dtype=np.float64, shape=(1,), per='chunk') for cfg in loadcfgs(os.path.join(self.working_directory, "testing_efs.cfg")): testing_store.add_chunk(len(cfg.pos), identifier=cfg.desc, energy=cfg.energy, forces=cfg.forces, stress=cfg.stresses, grade=cfg.grade ) with self.project_hdf5.open('output') as hdf5_output: hdf5_output['grades'] = grades_lst hdf5_output['job_id'] = job_id_grades_lst hdf5_output['timestep'] = timestep_grades_lst hdf5_output['job_id_diff'] = job_id_diff_lst hdf5_output['timestep_diff'] = timestep_diff_lst hdf5_output['job_id_new'] = job_id_new_training_lst hdf5_output['timestep_new'] = timestep_new_training_lst self._potential.to_hdf(hdf=hdf5_output) hdf5_output['training_energies'] = training_energies hdf5_output['testing_energies'] = testing_energies training_store.to_hdf(hdf=hdf5_output, group_name="training_efs") testing_store.to_hdf(hdf=hdf5_output, group_name="testing_efs") def get_structure(self, iteration_step=-1): job = self.project.load(self['output/job_id_diff'][iteration_step]) return job.get_structure(self['output/timestep_diff'][iteration_step]) def to_hdf(self, hdf=None, group_name=None): super(Mlip, self).to_hdf(hdf=hdf, group_name=group_name) self.input.to_hdf(self._hdf5) with self._hdf5.open('input') as hdf_input: job_id_lst, time_step_start_lst, time_step_end_lst, time_step_delta_lst = self._job_dict_lst(self._job_dict) hdf_input["job_id_list"] = job_id_lst hdf_input["time_step_start_lst"] = time_step_start_lst hdf_input["time_step_end_lst"] = time_step_end_lst hdf_input["time_step_delta_lst"] = time_step_delta_lst def from_hdf(self, hdf=None, group_name=None): super(Mlip, self).from_hdf(hdf=hdf, group_name=group_name) self.input.from_hdf(self._hdf5) with self._hdf5.open('input') as hdf_input: for job_id, start, end, delta in zip( hdf_input["job_id_list"], hdf_input["time_step_start_lst"], hdf_input["time_step_end_lst"], hdf_input["time_step_delta_lst"] ): self.add_job_to_fitting( job_id=job_id, time_step_start=start, time_step_end=end, time_step_delta=delta ) if self.status.finished: with self._hdf5.open("output") as hdf_output: self._potential.from_hdf(hdf=hdf_output) def get_suggested_number_of_configuration(self, species_count=None, multiplication_factor=2.0): if self.input['filepath'] == 'auto': potential = self.input['potential'] if isinstance(potential, numbers.Integral): potential = f"{potential:02}g.mtp" source = self._find_potential(potential) else: source = self.input['filepath'] with open(source) as f: lines = f.readlines() radial_basis_size, radial_funcs_count, alpha_scalar_moments = 0.0, 0.0, 0.0 for line in lines: if 'radial_basis_size' in line: radial_basis_size = int(line.split()[2]) if 'radial_funcs_count' in line: radial_funcs_count = int(line.split()[2]) if 'species_count' in line and species_count is None: species_count = int(line.split()[2]) if 'alpha_scalar_moments' in line: alpha_scalar_moments = int(line.split()[2]) return int(multiplication_factor * \ (radial_basis_size * radial_funcs_count * species_count ** 2 + alpha_scalar_moments)) @staticmethod def _update_species_count(lines, species_count): ind = 0 for ind, line in enumerate(lines): if 'species_count' in line: break species_line = lines[ind].split() species_line[-1] = str(species_count) lines[ind] = ' '.join(species_line) + '\n' return lines @staticmethod def _update_min_max_distance(lines, min_distance, max_distance): min_dis_updated, max_dis_updated = False, False for ind, line in enumerate(lines): if 'min_dist' in line and min_distance is not None: min_dist_line = lines[ind].split() min_dist_line[2] = str(min_distance) lines[ind] = ' '.join(min_dist_line) + '\n' min_dis_updated = True elif 'max_dist' in line and max_distance is not None: max_dist_line = lines[ind].split() max_dist_line[2] = str(max_distance) lines[ind] = ' '.join(max_dist_line) + '\n' max_dis_updated = True elif min_dis_updated and max_dis_updated: break return lines def _copy_potential(self, species_count, file_name, cwd=None): if cwd is not None: file_name = posixpath.join(cwd, file_name) if self.input['filepath'] == 'auto': potential = self.input['potential'] if isinstance(potential, numbers.Integral): potential = f"{potential:02}g.mtp" source = self._find_potential(potential) else: source = self.input['filepath'] with open(source) as f: lines = f.readlines() if self.input['filepath'] == 'auto': lines_modified = self._update_species_count(lines, species_count) lines_modified = self._update_min_max_distance(lines=lines_modified, min_distance=self.input['min_dist'], max_distance=self.input['max_dist']) else: lines_modified = lines with open(file_name, 'w') as f: f.writelines(lines_modified) @staticmethod def stress_tensor_components(stresses): return np.array([stresses[0][0], stresses[1][1], stresses[2][2], stresses[1][2], stresses[0][1], stresses[0][2]]) * gpa_to_ev_ang def _write_configurations(self, file_name='training.cfg', cwd=None, respect_step=True): if cwd is not None: file_name = posixpath.join(cwd, file_name) indices_lst, position_lst, forces_lst, cell_lst, energy_lst, track_lst, stress_lst = [], [], [], [], [], [], [] all_species = set() for job_id, value in self._job_dict.items(): ham = self.project.inspect(job_id) if respect_step: start = value['time_step_start'] end = value['time_step_end']+1 delta = value['time_step_delta'] else: start, end, delta = 0, None, 1 time_step = start # HACK: until the training container has a proper HDF5 interface if ham.__name__ == "TrainingContainer": job = ham.to_object() all_species.update(job.get_elements()) pd = job.to_pandas() for time_step, (name, atoms, energy, forces, _) in islice(enumerate(pd.itertuples(index=False)), start, end, delta): atoms = ase_to_pyiron(atoms) indices_lst.append(atoms.indices) position_lst.append(atoms.positions) forces_lst.append(forces) cell_lst.append(atoms.cell) energy_lst.append(energy) track_lst.append(str(ham.job_id) + "_" + str(time_step)) continue original_dict = {el: ind for ind, el in enumerate(sorted(ham['input/structure/species']))} species_dict = {ind: original_dict[el] for ind, el in enumerate(ham['input/structure/species'])} # HACK: this does not preserve element order, but the old code is broken for structures with different # species anyway all_species.update(ham['input/structure/species']) if ham.__name__ in ['Vasp', 'ThermoIntDftEam', 'ThermoIntDftMtp', 'ThermoIntVasp']: if len(ham['output/outcar/stresses']) != 0: for position, forces, cell, energy, stresses, volume in zip(ham['output/generic/positions'][start:end:delta], ham['output/generic/forces'][start:end:delta], ham['output/generic/cells'][start:end:delta], ham['output/generic/dft/energy_free'][start:end:delta], ham['output/outcar/stresses'][start:end:delta], ham['output/generic/volume'][start:end:delta]): indices_lst.append([species_dict[el] for el in ham['input/structure/indices']]) position_lst.append(position) forces_lst.append(forces) cell_lst.append(cell) energy_lst.append(energy) stress_lst.append(stresses * volume / gpa_to_ev_ang) track_lst.append(str(ham.job_id) + '_' + str(time_step)) time_step += delta else: for position, forces, cell, energy in zip(ham['output/generic/positions'][start:end:delta], ham['output/generic/forces'][start:end:delta], ham['output/generic/cells'][start:end:delta], ham['output/generic/dft/energy_free'][start:end:delta]): indices_lst.append([species_dict[el] for el in ham['input/structure/indices']]) position_lst.append(position) forces_lst.append(forces) cell_lst.append(cell) energy_lst.append(energy) track_lst.append(str(ham.job_id) + '_' + str(time_step)) time_step += delta elif ham.__name__ in ['Lammps', 'LammpsInt2', 'LammpsMlip']: for position, forces, cell, energy, stresses, volume in zip(ham['output/generic/positions'][start:end:delta], ham['output/generic/forces'][start:end:delta], ham['output/generic/cells'][start:end:delta], ham['output/generic/energy_pot'][start:end:delta], ham['output/generic/pressures'][start:end:delta], ham['output/generic/volume'][start:end:delta]): indices_lst.append([species_dict[el] for el in ham['input/structure/indices']]) position_lst.append(position) forces_lst.append(forces) cell_lst.append(cell) energy_lst.append(energy) stress_lst.append(self.stress_tensor_components(stresses * volume)) track_lst.append(str(ham.job_id) + '_' + str(time_step)) time_step += delta else: for position, forces, cell, energy, stresses, volume in zip(ham['output/generic/positions'][start:end:delta], ham['output/generic/forces'][start:end:delta], ham['output/generic/cells'][start:end:delta], ham['output/generic/energy_pot'][start:end:delta], ham['output/generic/pressures'][start:end:delta], ham['output/generic/volume'][start:end:delta]): indices_lst.append([species_dict[el] for el in ham['input/structure/indices']]) position_lst.append(position) forces_lst.append(forces) cell_lst.append(cell) energy_lst.append(energy) stress_lst.append(self.stress_tensor_components(stresses * volume)) track_lst.append(str(ham.job_id) + '_' + str(time_step)) time_step += delta write_cfg(file_name=file_name, indices_lst=indices_lst, position_lst=position_lst, cell_lst=cell_lst, forces_lst=forces_lst, energy_lst=energy_lst, track_lst=track_lst, stress_lst=stress_lst) return list(all_species) def _write_test_set(self, file_name='testing.cfg', cwd=None): return self._write_configurations(file_name=file_name, cwd=cwd, respect_step=False) def _write_training_set(self, file_name='training.cfg', cwd=None): self._write_configurations(file_name=file_name, cwd=cwd, respect_step=True) @staticmethod def _job_dict_lst(job_dict): job_id_lst, time_step_start_lst, time_step_end_lst, time_step_delta_lst = [], [], [], [] for key, value in job_dict.items(): job_id_lst.append(key) time_step_start_lst.append(value['time_step_start']) time_step_end_lst.append(value['time_step_end']) time_step_delta_lst.append(value['time_step_delta']) return job_id_lst, time_step_start_lst, time_step_end_lst, time_step_delta_lst @staticmethod def _find_potential(potential_name): for resource_path in s.resource_paths: if os.path.exists(os.path.join(resource_path, 'mlip', 'potentials', 'templates')): resource_path = os.path.join(resource_path, 'mlip', 'potentials', 'templates') if 'potentials' in resource_path and \ os.path.exists(os.path.join(resource_path, potential_name)): return os.path.join(resource_path, potential_name) raise ValueError('Potential not found!') class MlipParameter(GenericParameters): def __init__(self, separator_char=' ', comment_char='#', table_name="mlip_inp"): super(MlipParameter, self).__init__(separator_char=separator_char, comment_char=comment_char, table_name=table_name) def load_default(self, file_content=None): if file_content is None: file_content = '''\ potential 16g.mtp filepath auto energy-weight 1 force-weight 0.01 stress-weight 0.001 iteration 1000 min_dist 2.0 max_dist 5.0 ''' self.load_string(file_content) class CommandLine(GenericParameters): def __init__(self, input_file_name=None, **qwargs): super(CommandLine, self).__init__(input_file_name=input_file_name, table_name="cmd", comment_char="#", val_only=True) def load_default(self, file_content=None): if file_content is None: file_content = '''\ $MLP_COMMAND_PARALLEL train --energy-weight=energy_auto --force-weight=force_auto --stress-weight=stress_auto --max-iter=iteration_auto start.mtp training.cfg > training.log ''' self.load_string(file_content) def activate_postprocessing(self, file_content=None): if file_content is None: file_content = '''\ $MLP_COMMAND_PARALLEL train --energy-weight=energy_auto --force-weight=force_auto --stress-weight=stress_auto --max-iter=iteration_auto start.mtp training.cfg > training.log $MLP_COMMAND_SERIAL calc-grade Trained.mtp_ training.cfg testing.cfg grades.cfg --mvs-filename=state.mvs > grading.log $MLP_COMMAND_SERIAL calc-errors Trained.mtp_ training.cfg > training.errors $MLP_COMMAND_SERIAL calc-errors Trained.mtp_ testing.cfg > testing.errors $MLP_COMMAND_SERIAL calc-efs Trained.mtp_ training.cfg training_efs.cfg $MLP_COMMAND_SERIAL calc-efs Trained.mtp_ testing.cfg testing_efs.cfg $MLP_COMMAND_SERIAL select-add Trained.mtp_ training.cfg testing.cfg diff.cfg > select.log cp training.cfg training_new.cfg cat diff.cfg >> training_new.cfg ''' self.load_string(file_content) def write_cfg(file_name, indices_lst, position_lst, cell_lst, forces_lst=None, energy_lst=None, track_lst=None, stress_lst=None): if stress_lst is None or len(stress_lst) == 0: stress_lst = [None] * len(position_lst) if forces_lst is None or len(forces_lst) == 0: forces_lst = [None] * len(position_lst) if track_lst is None or len(track_lst) == 0: track_lst = [None] * len(position_lst) if energy_lst is None or len(energy_lst) == 0: energy_lst = [None] * len(position_lst) cfg_lst = [] for indices, position, forces, cell, energy, stress, track_str in zip( indices_lst, position_lst, forces_lst, cell_lst, energy_lst, stress_lst, track_lst ): cfg_object = Cfg() cfg_object.pos = position cfg_object.lat = cell cfg_object.types = indices cfg_object.energy = energy cfg_object.forces = forces cfg_object.stresses = stress if track_str is not None: cfg_object.desc = 'pyiron\t' + track_str cfg_lst.append(cfg_object) savecfgs(filename=file_name, cfgs=cfg_lst, desc=None) def read_cgfs(file_name): cgfs_lst = loadcfgs(filename=file_name, max_cfgs=None) cell, positions, forces, stress, energy, indicies, grades, jobids, timesteps = [], [], [], [], [], [], [], [], [] for cgf in cgfs_lst: if cgf.pos is not None: positions.append(cgf.pos) if cgf.lat is not None: cell.append(cgf.lat) if cgf.types is not None: indicies.append(cgf.types) if cgf.energy is not None: energy.append(cgf.energy) if cgf.forces is not None: forces.append(cgf.forces) if cgf.stresses is not None: stress.append([ [cgf.stresses[0], cgf.stresses[5], cgf.stresses[4]], [cgf.stresses[5], cgf.stresses[1], cgf.stresses[3]], [cgf.stresses[4], cgf.stresses[3], cgf.stresses[2]] ]) if cgf.grade is not None: grades.append(cgf.grade) if cgf.desc is not None: job_id, timestep = cgf.desc.split('_') jobids.append(int(job_id)) timesteps.append(int(timestep)) return [np.array(cell), np.array(positions), np.array(forces), np.array(stress), np.array(energy), np.array(indicies), np.array(grades), np.array(jobids), np.array(timesteps)]
[ "pandas.DataFrame", "pyiron_contrib.atomistics.mlip.cfgs.Cfg", "pyiron_base.Executable", "os.path.join", "os.path.basename", "os.path.exists", "pyiron_contrib.atomistics.mlip.cfgs.loadcfgs", "pandas.itertuples", "posixpath.join", "numpy.array", "pyiron_contrib.atomistics.mlip.cfgs.savecfgs", "...
[((943, 953), 'pyiron_base.Settings', 'Settings', ([], {}), '()\n', (951, 953), False, 'from pyiron_base import Settings, GenericParameters, GenericJob, Executable, FlattenedStorage\n'), ((26579, 26632), 'pyiron_contrib.atomistics.mlip.cfgs.savecfgs', 'savecfgs', ([], {'filename': 'file_name', 'cfgs': 'cfg_lst', 'desc': 'None'}), '(filename=file_name, cfgs=cfg_lst, desc=None)\n', (26587, 26632), False, 'from pyiron_contrib.atomistics.mlip.cfgs import savecfgs, loadcfgs, Cfg\n'), ((26676, 26719), 'pyiron_contrib.atomistics.mlip.cfgs.loadcfgs', 'loadcfgs', ([], {'filename': 'file_name', 'max_cfgs': 'None'}), '(filename=file_name, max_cfgs=None)\n', (26684, 26719), False, 'from pyiron_contrib.atomistics.mlip.cfgs import savecfgs, loadcfgs, Cfg\n'), ((1411, 1425), 'pyiron_contrib.atomistics.mlip.potential.MtpPotential', 'MtpPotential', ([], {}), '()\n', (1423, 1425), False, 'from pyiron_contrib.atomistics.mlip.potential import MtpPotential\n'), ((2148, 2287), 'pandas.DataFrame', 'pd.DataFrame', (["{'Job id': job_id_lst, 'Start config': time_step_start_lst, 'End config':\n time_step_end_lst, 'Step': time_step_delta_lst}"], {}), "({'Job id': job_id_lst, 'Start config': time_step_start_lst,\n 'End config': time_step_end_lst, 'Step': time_step_delta_lst})\n", (2160, 2287), True, 'import pandas as pd\n'), ((2431, 2483), 'os.path.join', 'os.path.join', (['self.working_directory', '"""Trained.mtp_"""'], {}), "(self.working_directory, 'Trained.mtp_')\n", (2443, 2483), False, 'import os\n'), ((2501, 2550), 'os.path.join', 'os.path.join', (['self.working_directory', '"""state.mvs"""'], {}), "(self.working_directory, 'state.mvs')\n", (2513, 2550), False, 'import os\n'), ((6343, 6391), 'os.path.join', 'os.path.join', (['self.working_directory', '"""diff.cfg"""'], {}), "(self.working_directory, 'diff.cfg')\n", (6355, 6391), False, 'import os\n'), ((6403, 6428), 'os.path.exists', 'os.path.exists', (['file_name'], {}), '(file_name)\n', (6417, 6428), False, 'import os\n'), ((6611, 6663), 'os.path.join', 'os.path.join', (['self.working_directory', '"""selected.cfg"""'], {}), "(self.working_directory, 'selected.cfg')\n", (6623, 6663), False, 'import os\n'), ((6675, 6700), 'os.path.exists', 'os.path.exists', (['file_name'], {}), '(file_name)\n', (6689, 6700), False, 'import os\n'), ((6915, 6965), 'os.path.join', 'os.path.join', (['self.working_directory', '"""grades.cfg"""'], {}), "(self.working_directory, 'grades.cfg')\n", (6927, 6965), False, 'import os\n'), ((6977, 7002), 'os.path.exists', 'os.path.exists', (['file_name'], {}), '(file_name)\n', (6991, 7002), False, 'import os\n'), ((7307, 7325), 'pyiron_base.FlattenedStorage', 'FlattenedStorage', ([], {}), '()\n', (7323, 7325), False, 'from pyiron_base import Settings, GenericParameters, GenericJob, Executable, FlattenedStorage\n'), ((7965, 7983), 'pyiron_base.FlattenedStorage', 'FlattenedStorage', ([], {}), '()\n', (7981, 7983), False, 'from pyiron_base import Settings, GenericParameters, GenericJob, Executable, FlattenedStorage\n'), ((26241, 26246), 'pyiron_contrib.atomistics.mlip.cfgs.Cfg', 'Cfg', ([], {}), '()\n', (26244, 26246), False, 'from pyiron_contrib.atomistics.mlip.cfgs import savecfgs, loadcfgs, Cfg\n'), ((27753, 27767), 'numpy.array', 'np.array', (['cell'], {}), '(cell)\n', (27761, 27767), True, 'import numpy as np\n'), ((27769, 27788), 'numpy.array', 'np.array', (['positions'], {}), '(positions)\n', (27777, 27788), True, 'import numpy as np\n'), ((27790, 27806), 'numpy.array', 'np.array', (['forces'], {}), '(forces)\n', (27798, 27806), True, 'import numpy as np\n'), ((27808, 27824), 'numpy.array', 'np.array', (['stress'], {}), '(stress)\n', (27816, 27824), True, 'import numpy as np\n'), ((27826, 27842), 'numpy.array', 'np.array', (['energy'], {}), '(energy)\n', (27834, 27842), True, 'import numpy as np\n'), ((27856, 27874), 'numpy.array', 'np.array', (['indicies'], {}), '(indicies)\n', (27864, 27874), True, 'import numpy as np\n'), ((27876, 27892), 'numpy.array', 'np.array', (['grades'], {}), '(grades)\n', (27884, 27892), True, 'import numpy as np\n'), ((27894, 27910), 'numpy.array', 'np.array', (['jobids'], {}), '(jobids)\n', (27902, 27910), True, 'import numpy as np\n'), ((27912, 27931), 'numpy.array', 'np.array', (['timesteps'], {}), '(timesteps)\n', (27920, 27931), True, 'import numpy as np\n'), ((2562, 2581), 'os.path.exists', 'os.path.exists', (['pot'], {}), '(pot)\n', (2576, 2581), False, 'import os\n'), ((2586, 2608), 'os.path.exists', 'os.path.exists', (['states'], {}), '(states)\n', (2600, 2608), False, 'import os\n'), ((7227, 7279), 'os.path.join', 'os.path.join', (['self.working_directory', '"""Trained.mtp_"""'], {}), "(self.working_directory, 'Trained.mtp_')\n", (7239, 7279), False, 'import os\n'), ((7700, 7756), 'os.path.join', 'os.path.join', (['self.working_directory', '"""training_efs.cfg"""'], {}), "(self.working_directory, 'training_efs.cfg')\n", (7712, 7756), False, 'import os\n'), ((8354, 8409), 'os.path.join', 'os.path.join', (['self.working_directory', '"""testing_efs.cfg"""'], {}), "(self.working_directory, 'testing_efs.cfg')\n", (8366, 8409), False, 'import os\n'), ((13484, 13514), 'posixpath.join', 'posixpath.join', (['cwd', 'file_name'], {}), '(cwd, file_name)\n', (13498, 13514), False, 'import posixpath\n'), ((14497, 14607), 'numpy.array', 'np.array', (['[stresses[0][0], stresses[1][1], stresses[2][2], stresses[1][2], stresses[0\n ][1], stresses[0][2]]'], {}), '([stresses[0][0], stresses[1][1], stresses[2][2], stresses[1][2],\n stresses[0][1], stresses[0][2]])\n', (14505, 14607), True, 'import numpy as np\n'), ((14790, 14820), 'posixpath.join', 'posixpath.join', (['cwd', 'file_name'], {}), '(cwd, file_name)\n', (14804, 14820), False, 'import posixpath\n'), ((1855, 1925), 'pyiron_base.Executable', 'Executable', ([], {'codename': 'self.__name__', 'path_binary_codes': 's.resource_paths'}), '(codename=self.__name__, path_binary_codes=s.resource_paths)\n', (1865, 1925), False, 'from pyiron_base import Settings, GenericParameters, GenericJob, Executable, FlattenedStorage\n'), ((4869, 4888), 'os.path.basename', 'os.path.basename', (['f'], {}), '(f)\n', (4885, 4888), False, 'import os\n'), ((22840, 22902), 'os.path.join', 'os.path.join', (['resource_path', '"""mlip"""', '"""potentials"""', '"""templates"""'], {}), "(resource_path, 'mlip', 'potentials', 'templates')\n", (22852, 22902), False, 'import os\n'), ((22937, 22999), 'os.path.join', 'os.path.join', (['resource_path', '"""mlip"""', '"""potentials"""', '"""templates"""'], {}), "(resource_path, 'mlip', 'potentials', 'templates')\n", (22949, 22999), False, 'import os\n'), ((23155, 23198), 'os.path.join', 'os.path.join', (['resource_path', 'potential_name'], {}), '(resource_path, potential_name)\n', (23167, 23198), False, 'import os\n'), ((15832, 15852), 'pyiron_atomistics.ase_to_pyiron', 'ase_to_pyiron', (['atoms'], {}), '(atoms)\n', (15845, 15852), False, 'from pyiron_atomistics import ase_to_pyiron\n'), ((23086, 23129), 'os.path.join', 'os.path.join', (['resource_path', 'potential_name'], {}), '(resource_path, potential_name)\n', (23098, 23129), False, 'import os\n'), ((15681, 15707), 'pandas.itertuples', 'pd.itertuples', ([], {'index': '(False)'}), '(index=False)\n', (15694, 15707), True, 'import pandas as pd\n')]
import numpy as np from torch.utils.data import Dataset from fasttext import load_model import os import numpy as np import torch import h5py import pickle import re import utils from collections import Counter from transformers import BertTokenizer SENTENCE_SPLIT_REGEX = re.compile(r"(\W+)") class InputFeatures(object): """A single set of features of data.""" def __init__(self, input_ids, input_mask, segment_ids): self.input_ids = input_ids self.input_mask = input_mask self.segment_ids = segment_ids def convert_sents_to_features(sents, max_seq_length, tokenizer): """Loads a data file into a list of `InputBatch`s.""" features = [] for (i, sent) in enumerate(sents): tokens_a = tokenizer.tokenize(sent.strip()) # Account for [CLS] and [SEP] with "- 2" if len(tokens_a) > max_seq_length - 2: tokens_a = tokens_a[:(max_seq_length - 2)] # Keep segment id which allows loading BERT-weights. tokens = ["[CLS]"] + tokens_a + ["[SEP]"] segment_ids = [0] * len(tokens) input_ids = tokenizer.convert_tokens_to_ids(tokens) # The mask has 1 for real tokens and 0 for padding tokens. Only real # tokens are attended to. input_mask = [1] * len(input_ids) # Zero-pad up to the sequence length. padding = [0] * (max_seq_length - len(input_ids)) input_ids += padding input_mask += padding segment_ids += padding assert len(input_ids) == max_seq_length assert len(input_mask) == max_seq_length assert len(segment_ids) == max_seq_length features.append( InputFeatures(input_ids=input_ids, input_mask=input_mask, segment_ids=segment_ids)) return features def word_tokenize(word): word = word.lower() word = word.replace(",", "").replace("?", "").replace("'s", " 's") return word.strip() # 处理句子 def tokenize(sentence, regex=SENTENCE_SPLIT_REGEX, keep=["'s"], remove=[",", "?"]): sentence = sentence.lower() for token in keep: sentence = sentence.replace(token, " " + token) for token in remove: sentence = sentence.replace(token, "") tokens = regex.split(sentence) tokens = [t.strip() for t in tokens if len(t.strip()) > 0] return tokens # vocabution class Dictionary(): def __init__(self): super(Dictionary, self).__init__() self.id_word = [] self.word_id = {} with open('../data/vocabs/vocabulary_100k.txt','r') as file: f = file.readlines() for i in range(len(f)): self.id_word.append(word_tokenize(f[i])) for i in range(len(self.id_word)): self.word_id[self.id_word[i]] = i def __len__(self): return len(self.id_word) def get_index_by_word(self, word): return self.word_id[word] @property def padding_index(self): return len(self.id_word) def get_question_sequence(self, question_tokens, max_length = 14): question_sequence = [] for k in question_tokens: question_sequence.append(self.word_id.get(k, self.padding_index)) question_sequence = question_sequence[:max_length] if len(question_sequence) < max_length: padding = [self.padding_index] * (max_length - len(question_sequence)) question_sequence += padding utils.assert_eq(len(question_sequence), max_length) return question_sequence def create_glove_embedding_init(self, glove_file = '../pythia/.vector_cache/glove.6B.300d.txt', pre=False, pre_dir=None): if pre: weights = np.load(open(pre_dir, 'rb'), allow_pickle=True) else: word2emb = {} with open(glove_file, 'r') as f: entries = f.readlines() emb_dim = len(entries[0].split(' ')) - 1 print('embedding dim is %d' % emb_dim) weights = np.zeros((len(self.id_word), emb_dim), dtype=np.float32) for entry in entries: vals = entry.split(' ') word = vals[0] vals = list(map(float, vals[1:])) word2emb[word] = np.array(vals) # word embedding count = 0 for idx, word in enumerate(self.id_word): if word not in word2emb: updates = 0 for w in word.split(' '): if w not in word2emb: continue weights[idx] += word2emb[w] updates += 1 if updates == 0: count+= 1 continue weights[idx] = word2emb[word] print("%d 不在glove中"%count) np.save('../data/vocabs/embedding_weight.npy', weights) print("save success!") self.embedding_dim = weights.shape[1] return weights class Answer(object): def __init__(self, answer_dir = '../data/vocabs/answer_index.pkl', pre = False, copy = True): super(Answer,self).__init__() self.answer_dir = answer_dir if pre: self.index2answer, self.answer2index = pickle.load(open('../data/vocabs/answer_index.pkl','rb')) else: self.index2answer = [] self.answer2index = {} self.answer_vocab('../data/vocabs/textvqa_more_than_8_unsorted.txt') self.max_num = 50 self.candidate_answer_num = self.max_num + (self.length if copy else 0) self.noexisting_answer = 0 ## 加载答案文档 def answer_vocab(self, answer_vocab_dir, ): with open(answer_vocab_dir, 'r') as file: answers = file.readlines() for i in range(len(answers)): w = word_tokenize(answers[i]) self.index2answer.append(w) self.answer2index[w] = i pickle.dump((self.index2answer, self.answer2index), open(self.answer_dir,'wb')) @property def length(self): return len(self.index2answer) ''' answer source: no existing : 00 = 0 classification : 01 = 1 ocr : 10 = 2 ocr and classification : 11 = 3 ''' def process_question_answer(self, answers, tokens = None): a = {} for i in range(len(answers)): w = word_tokenize(answers[i]) a[w] = a.get(w,0) + 1 # print(a) answer_source = {} answer_scores = torch.zeros(self.candidate_answer_num ,dtype = torch.float) for key in a: a[key] = min(1,a[key]/3) index = self.answer2index.get(key, None) if index != None: answer_scores[index] = a[key] answer_source[key] = answer_source.get(key,0) + 1 if tokens != None: token_scores = torch.zeros(self.max_num, dtype=torch.float) for i, t in enumerate(tokens[:self.max_num]): if t in a: token_scores[i] = a[t] answer_source[t] = answer_source.get(t, 0) + 2 answer_scores[-self.max_num:] = token_scores if answer_scores.sum() == 0: # answer_scores[0] = 1 # 去掉unknown 这个标签,保证类平衡 self.noexisting_answer += 1 return answer_scores, answer_source def get_answer(self, index, token=None): if index>self.length: return token[index-self.length] else: return self.index2answer[index] def get_ocr_bb(ocr_tokens, ocr_info): ocr_bb = [] for ot in ocr_tokens: for oi in ocr_info: if oi["word"]== ot: ocr_bb.append(get_bb(oi["bounding_box"])) return ocr_bb def get_bb(bb): return [bb['top_left_x'], bb['top_left_y'], bb['top_left_x']+bb["width"], bb['top_left_y']++bb["height"]] # 整理数据集的每一项 def _load_dataset(name, dataroot = '../data/imdb/textvqa_0.5/'): """Load entries """ question_path = os.path.join( dataroot, 'imdb_textvqa_%s.npy' % name) question_data = np.load(open(question_path, "rb"), allow_pickle=True)[1:] # delete the sample with empty ocr l = len(question_data) print("Total %d %s samples."%(l,name)) # if name == "train": # i = 0 # while i < l: # if question_data[i]["ocr_info"]==[]: # question_data = np.delete(question_data,i) # l = len(question_data) # else: # i += 1 print("Use %d %s samples."%(len(question_data), name)) questions = sorted(question_data, key=lambda x: x['question_id']) entries = [] for question in questions: tokens = question['ocr_tokens'] ocr_bb = get_ocr_bb(tokens, question['ocr_info']) for i,w in enumerate(tokens): tokens[i] = word_tokenize(w) entries.append({ 'question_id' : question['question_id'], 'image_id' : question['image_id'], 'question' : question['question'], 'ocr_tokens' : tokens, 'ocr_bb' : ocr_bb, 'answer' : (question['valid_answers'] if name!='test' else None) }) return entries # 数据集 class TextVQA(Dataset): def __init__(self, dataset, dictionary): super(TextVQA, self).__init__() assert dataset in ['train', 'val','test'] self.name = dataset self.dictionary = dictionary # load image feature file image_feature_dir = '../data/open_images/detectron_fix_100/fc6/' if dataset == "val" or dataset == "train": h5_path = image_feature_dir + 'trainval.hdf5' imageid2index = image_feature_dir+'trainval_imageid2index.pkl' else: h5_path = image_feature_dir + 'test.hdf5' imageid2index = image_feature_dir+'test_imageid2index.pkl' self.img2index = pickle.load(open(imageid2index,'rb')) with h5py.File(h5_path, 'r') as hf: self.image_features = np.array(hf.get('image_features')) self.image_features_spatials = np.array(hf.get('spatial_features')) # load context data data_dir = '../data/imdb/textvqa_0.5/' context_feature_file = data_dir + "context_embeddding.hdf5" context_imageid2index = data_dir + "context_imageid2index.pkl" imageid2contextnum = data_dir + "imageid2contextnum.pkl" self.c_imageid_i = pickle.load(open(context_imageid2index,'rb')) self.c_imageid_num = pickle.load(open(imageid2contextnum,'rb')) with h5py.File(context_feature_file, 'r') as hf: self.c_features = np.array(hf.get('context_embedding')) self.tokenizer = BertTokenizer.from_pretrained('bert-base-uncased',do_lower_case=True) self.answer_process = Answer(pre = False) self.entries = _load_dataset(dataset) # self.tokenize() self.tensorize() print("no existing answer",self.answer_process.noexisting_answer) def tokenize(self): """Tokenizes the questions. This will add q_token in each entry of the dataset. -1 represent nil, and should be treated as padding_idx in embedding """ for entry in self.entries: entry['q_token'] = self.dictionary.get_question_sequence(entry['question']) def tensorize(self): self.image_features = torch.from_numpy(self.image_features) self.image_features_spatials = torch.from_numpy(self.image_features_spatials) self.c_features = torch.from_numpy(self.c_features) for entry in self.entries: train_features = convert_sents_to_features([entry['question']] ,15 , self.tokenizer) input_ids = torch.tensor(train_features[0].input_ids, dtype=torch.long) input_mask = torch.tensor(train_features[0].input_mask, dtype=torch.long) segment_ids = torch.tensor(train_features[0].segment_ids, dtype=torch.long) question = [input_ids, input_mask, segment_ids] entry['q_token'] = question ocr_bb = entry['ocr_bb'] if ocr_bb != []: entry['ocr_bb'] = torch.from_numpy(np.array(ocr_bb)) answer = entry['answer'] if None != answer: entry['answer_label'], entry["answer_source"] = self.answer_process.process_question_answer(answer, entry['ocr_tokens']) else : entry['answer_label'] = None def __getitem__(self, index): image_id = self.entries[index]['image_id'] c_feature = self.c_features[self.c_imageid_i[image_id]: self.c_imageid_i[image_id]+ self.c_imageid_num[image_id]] c_feature = c_feature[:50] context_feature = torch.zeros((50, c_feature.size(1)), dtype = torch.float) context_feature[:c_feature.size(0)] = c_feature ocr_bb_feature = torch.zeros((50, 4), dtype = torch.float) ocr_bb = self.entries[index]['ocr_bb'] if not isinstance(ocr_bb,list): ocr_bb_feature[:ocr_bb.size(0)] = ocr_bb[:50] img_feature = self.image_features[self.img2index[image_id]] bbox = self.image_features_spatials[self.img2index[image_id]][:,:4] question = self.entries[index]['q_token'] question_id = self.entries[index]['question_id'] answer = self.entries[index]['answer_label'] tokens = self.entries[index]['ocr_tokens'] # order_vectors = torch.eye(context_feature.size(0)) # order_vectors[len(tokens):] = 0 sample = { "question_id" : question_id, "input_ids" : question[0], "token_type_ids" : question[2], "attention_mask" : question[1], "img_feature" : img_feature, "bbox": bbox, "context_feature" : context_feature, "ocrbbox": ocr_bb_feature, "tokens" : len(tokens), } if answer is not None: sample["answer"] = answer return sample def __len__(self): return len(self.entries) def get_tokens_by_qId(self, q_Id): for i in range(len(self.entries)): if self.entries[i]["question_id"] == q_Id: return self.entries[i]['ocr_tokens'] def get_answer_by_qId(self, q_Id): if self.name=="test": return None, None for i in range(len(self.entries)): if self.entries[i]["question_id"] == q_Id: answers = self.entries[i]["answer"] a = {} for i in range(len(answers)): w = word_tokenize(answers[i]) a[w] = a.get(w,0) + 1 return a, self.entries[i]["answer_source"]
[ "h5py.File", "numpy.save", "re.compile", "transformers.BertTokenizer.from_pretrained", "numpy.array", "torch.zeros", "os.path.join", "torch.tensor", "torch.from_numpy" ]
[((274, 294), 're.compile', 're.compile', (['"""(\\\\W+)"""'], {}), "('(\\\\W+)')\n", (284, 294), False, 'import re\n'), ((8184, 8236), 'os.path.join', 'os.path.join', (['dataroot', "('imdb_textvqa_%s.npy' % name)"], {}), "(dataroot, 'imdb_textvqa_%s.npy' % name)\n", (8196, 8236), False, 'import os\n'), ((6658, 6715), 'torch.zeros', 'torch.zeros', (['self.candidate_answer_num'], {'dtype': 'torch.float'}), '(self.candidate_answer_num, dtype=torch.float)\n', (6669, 6715), False, 'import torch\n'), ((10975, 11045), 'transformers.BertTokenizer.from_pretrained', 'BertTokenizer.from_pretrained', (['"""bert-base-uncased"""'], {'do_lower_case': '(True)'}), "('bert-base-uncased', do_lower_case=True)\n", (11004, 11045), False, 'from transformers import BertTokenizer\n'), ((11680, 11717), 'torch.from_numpy', 'torch.from_numpy', (['self.image_features'], {}), '(self.image_features)\n', (11696, 11717), False, 'import torch\n'), ((11757, 11803), 'torch.from_numpy', 'torch.from_numpy', (['self.image_features_spatials'], {}), '(self.image_features_spatials)\n', (11773, 11803), False, 'import torch\n'), ((11830, 11863), 'torch.from_numpy', 'torch.from_numpy', (['self.c_features'], {}), '(self.c_features)\n', (11846, 11863), False, 'import torch\n'), ((13245, 13284), 'torch.zeros', 'torch.zeros', (['(50, 4)'], {'dtype': 'torch.float'}), '((50, 4), dtype=torch.float)\n', (13256, 13284), False, 'import torch\n'), ((4935, 4990), 'numpy.save', 'np.save', (['"""../data/vocabs/embedding_weight.npy"""', 'weights'], {}), "('../data/vocabs/embedding_weight.npy', weights)\n", (4942, 4990), True, 'import numpy as np\n'), ((7036, 7080), 'torch.zeros', 'torch.zeros', (['self.max_num'], {'dtype': 'torch.float'}), '(self.max_num, dtype=torch.float)\n', (7047, 7080), False, 'import torch\n'), ((10194, 10217), 'h5py.File', 'h5py.File', (['h5_path', '"""r"""'], {}), "(h5_path, 'r')\n", (10203, 10217), False, 'import h5py\n'), ((10829, 10865), 'h5py.File', 'h5py.File', (['context_feature_file', '"""r"""'], {}), "(context_feature_file, 'r')\n", (10838, 10865), False, 'import h5py\n'), ((12029, 12088), 'torch.tensor', 'torch.tensor', (['train_features[0].input_ids'], {'dtype': 'torch.long'}), '(train_features[0].input_ids, dtype=torch.long)\n', (12041, 12088), False, 'import torch\n'), ((12114, 12174), 'torch.tensor', 'torch.tensor', (['train_features[0].input_mask'], {'dtype': 'torch.long'}), '(train_features[0].input_mask, dtype=torch.long)\n', (12126, 12174), False, 'import torch\n'), ((12201, 12262), 'torch.tensor', 'torch.tensor', (['train_features[0].segment_ids'], {'dtype': 'torch.long'}), '(train_features[0].segment_ids, dtype=torch.long)\n', (12213, 12262), False, 'import torch\n'), ((4337, 4351), 'numpy.array', 'np.array', (['vals'], {}), '(vals)\n', (4345, 4351), True, 'import numpy as np\n'), ((12493, 12509), 'numpy.array', 'np.array', (['ocr_bb'], {}), '(ocr_bb)\n', (12501, 12509), True, 'import numpy as np\n')]
#!/usr/bin/env python # encoding: utf-8 """ @Author: yangwenhao @Contact: <EMAIL> @Software: PyCharm @File: 4.5_ImplementMultiClassSVM.py @Time: 2019/1/6 下午5:39 @Overview: Use SVMs to categorize multiple classes instead of two. """ import numpy as np import matplotlib.pyplot as plt from sklearn import datasets from tensorflow.python.framework import ops import tensorflow as tf sess = tf.Session() # Load the iris data, extract the sepal length and petal width, and separated the x and y values for each class. iris = datasets.load_iris() x_vals = np.array([[x[0], x[3]] for x in iris.data]) y_vals1 = np.array([1 if y==0 else -1 for y in iris.target]) y_vals2 = np.array([1 if y==1 else -1 for y in iris.target]) y_vals3 = np.array([1 if y==2 else -1 for y in iris.target]) y_vals = np.array([y_vals1, y_vals2, y_vals3]) class1_x = [x[0] for i,x in enumerate(x_vals) if iris.target[i]==0] class1_y = [x[1] for i,x in enumerate(x_vals) if iris.target[i]==0] class2_x = [x[0] for i,x in enumerate(x_vals) if iris.target[i]==1] class2_y = [x[1] for i,x in enumerate(x_vals) if iris.target[i]==1] class3_x = [x[0] for i,x in enumerate(x_vals) if iris.target[i]==2] class3_y = [x[1] for i,x in enumerate(x_vals) if iris.target[i]==2] # In this recipe, the dimensions will change, because we will have three classifiers # instead of one. And we also make use of matix broadcasting and reshaing techniques # to calculate all three SVMs at once. learning_rate = 0.01 batch_size = 50 iterations = 100 x_data = tf.placeholder(shape=[None, 2], dtype=tf.float32) y_target = tf.placeholder(shape=[3, None], dtype=tf.float32) prediction_grid = tf.placeholder(shape=[None, 2], dtype=tf.float32) b = tf.Variable(tf.random_normal(shape=[3, batch_size])) # Create the Gaussion kernel gamma = tf.constant(-10.0) dist = tf.reduce_sum(tf.square(x_data), 1) dist = tf.reshape(dist, [-1, 1]) sq_dists = tf.add(tf.subtract(dist, tf.multiply(2., tf.matmul(x_data, tf.transpose(x_data)))), tf.transpose(dist)) my_kernel = tf.exp(tf.multiply(gamma, tf.abs(sq_dists))) # We will do batch matrix multiplication and end up with three-dimensional matrices. # The data and target matrices are not set up for this. We create a function to expand # such matrices, reshape the matrix into a transpose, and then call TensorFlow's batch_ # matmul across the extra dimension. def reshape_matmul(mat): v1 = tf.expand_dims(mat, 1) v2 = tf.reshape(v1, [3, batch_size, 1]) return(tf.matmul(v2, v1)) # Then we compute the dual loss function as follows: model_output = tf.matmul(b, my_kernel) first_term = tf.reduce_sum(b) b_vec_cross = tf.matmul(tf.transpose(b), b) y_target_cross = reshape_matmul(y_target) second_term = tf.reduce_sum(tf.multiply(my_kernel, tf.multiply(b_vec_cross, y_target_cross)), [1, 2]) loss = tf.reduce_sum(tf.negative(tf.subtract(first_term, second_term))) # Create prediction kernel. Notice that we hace to be careful with the reduce_sum function # and not reduce across all three SVM predictions. So we need to tell Tensorflow not to # sum everything up with a second index argument. rA = tf.reshape(tf.reduce_sum(tf.square(x_data), 1), [-1, 1]) rB = tf.reshape(tf.reduce_sum(tf.square(prediction_grid), 1), [-1, 1]) pred_sq_dist = tf.add(tf.subtract(rA, tf.multiply(2., tf.matmul(x_data, tf.transpose(prediction_grid)))), tf.transpose(rB)) pred_kernel = tf.exp(tf.multiply(gamma, tf.abs(pred_sq_dist))) # A big change in predictions is that the predictions are not the sign() of the output. # Since we are implementing a one versus all stategy, the prediction is the classifier that # has the largest output. We use TensorFlow's built in argmax() function. prediction_output = tf.matmul(tf.multiply(y_target, b), pred_kernel) prediction = tf.argmax(prediction_output - tf.expand_dims(tf.reduce_mean(prediction_output, 1), 1), 0) accuracy = tf.reduce_mean(tf.cast(tf.equal(prediction, tf.argmax(y_target, 0)), tf.float32)) # Optimizer my_opt = tf.train.GradientDescentOptimizer(learning_rate) train_step = my_opt.minimize(loss) init = tf.global_variables_initializer() sess.run(init) # Training loop loss_ves = [] batch_accuracy = [] for i in range(iterations): rand_index = np.random.choice(len(x_vals), size=batch_size) rand_x = x_vals[rand_index] rand_y = y_vals[:, rand_index] sess.run(train_step, feed_dict={x_data: rand_x, y_target: rand_y}) temp_loss = sess.run(loss, feed_dict={x_data: rand_x, y_target: rand_y}) loss_ves.append(temp_loss) acc_temp = sess.run(accuracy, feed_dict={x_data: rand_x, y_target: rand_y, prediction_grid:rand_x}) batch_accuracy.append(acc_temp) x_min, x_max = x_vals[:, 0].min() - 1, x_vals[:, 0].max() + 1 y_min, y_max = x_vals[:, 1].min() - 1, x_vals[:, 1].max() + 1 xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.02), np.arange(y_min, y_max, 0.02)) grid_points = np.c_[xx.ravel(), yy.ravel()] grid_predictions = sess.run(prediction, feed_dict={x_data: rand_x, y_target: rand_y, prediction_grid: grid_points}) grid_predictions = grid_predictions.reshape(xx.shape) # Plot the result plt.figure(figsize=(10.8, 7.2)) grid = plt.GridSpec(2, 3, wspace=0.5, hspace=0.5) plt.subplot(grid[0:2, 0:2]) plt.contourf(xx, yy, grid_predictions, cmap=plt.cm.Paired, alpha=0.8) plt.plot(class1_x, class1_y, 'ro', label='I. setosa') plt.plot(class2_x, class2_y, 'kx', label='I. versicolor') plt.plot(class3_x, class3_y, 'gv', label='I. virginica') plt.title('Gaussian SVM Results on Iris Data') plt.xlabel('Pedal Length') plt.ylabel('Sepal Width') plt.legend(loc='lower right') plt.ylim([-0.5, 3.0]) plt.xlim([3.5, 8.5]) plt.subplot(grid[0, 2]) plt.plot(batch_accuracy, 'k-', label='Accuracy') plt.title('Batch Accuracy') plt.xlabel('Generation') plt.ylabel('Accuracy') plt.legend(loc='lower right') plt.subplot(grid[1, 2]) plt.plot(loss_ves, 'k-') plt.title('Loss per Generation') plt.xlabel('Generation') plt.ylabel('Loss') plt.show()
[ "matplotlib.pyplot.title", "sklearn.datasets.load_iris", "tensorflow.reduce_sum", "tensorflow.reshape", "tensorflow.matmul", "matplotlib.pyplot.figure", "tensorflow.multiply", "matplotlib.pyplot.contourf", "numpy.arange", "tensorflow.abs", "tensorflow.subtract", "tensorflow.placeholder", "ma...
[((388, 400), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (398, 400), True, 'import tensorflow as tf\n'), ((522, 542), 'sklearn.datasets.load_iris', 'datasets.load_iris', ([], {}), '()\n', (540, 542), False, 'from sklearn import datasets\n'), ((552, 595), 'numpy.array', 'np.array', (['[[x[0], x[3]] for x in iris.data]'], {}), '([[x[0], x[3]] for x in iris.data])\n', (560, 595), True, 'import numpy as np\n'), ((606, 660), 'numpy.array', 'np.array', (['[(1 if y == 0 else -1) for y in iris.target]'], {}), '([(1 if y == 0 else -1) for y in iris.target])\n', (614, 660), True, 'import numpy as np\n'), ((667, 721), 'numpy.array', 'np.array', (['[(1 if y == 1 else -1) for y in iris.target]'], {}), '([(1 if y == 1 else -1) for y in iris.target])\n', (675, 721), True, 'import numpy as np\n'), ((728, 782), 'numpy.array', 'np.array', (['[(1 if y == 2 else -1) for y in iris.target]'], {}), '([(1 if y == 2 else -1) for y in iris.target])\n', (736, 782), True, 'import numpy as np\n'), ((788, 825), 'numpy.array', 'np.array', (['[y_vals1, y_vals2, y_vals3]'], {}), '([y_vals1, y_vals2, y_vals3])\n', (796, 825), True, 'import numpy as np\n'), ((1510, 1559), 'tensorflow.placeholder', 'tf.placeholder', ([], {'shape': '[None, 2]', 'dtype': 'tf.float32'}), '(shape=[None, 2], dtype=tf.float32)\n', (1524, 1559), True, 'import tensorflow as tf\n'), ((1571, 1620), 'tensorflow.placeholder', 'tf.placeholder', ([], {'shape': '[3, None]', 'dtype': 'tf.float32'}), '(shape=[3, None], dtype=tf.float32)\n', (1585, 1620), True, 'import tensorflow as tf\n'), ((1639, 1688), 'tensorflow.placeholder', 'tf.placeholder', ([], {'shape': '[None, 2]', 'dtype': 'tf.float32'}), '(shape=[None, 2], dtype=tf.float32)\n', (1653, 1688), True, 'import tensorflow as tf\n'), ((1784, 1802), 'tensorflow.constant', 'tf.constant', (['(-10.0)'], {}), '(-10.0)\n', (1795, 1802), True, 'import tensorflow as tf\n'), ((1853, 1878), 'tensorflow.reshape', 'tf.reshape', (['dist', '[-1, 1]'], {}), '(dist, [-1, 1])\n', (1863, 1878), True, 'import tensorflow as tf\n'), ((2549, 2572), 'tensorflow.matmul', 'tf.matmul', (['b', 'my_kernel'], {}), '(b, my_kernel)\n', (2558, 2572), True, 'import tensorflow as tf\n'), ((2586, 2602), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['b'], {}), '(b)\n', (2599, 2602), True, 'import tensorflow as tf\n'), ((3957, 4005), 'tensorflow.train.GradientDescentOptimizer', 'tf.train.GradientDescentOptimizer', (['learning_rate'], {}), '(learning_rate)\n', (3990, 4005), True, 'import tensorflow as tf\n'), ((4049, 4082), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (4080, 4082), True, 'import tensorflow as tf\n'), ((5071, 5102), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(10.8, 7.2)'}), '(figsize=(10.8, 7.2))\n', (5081, 5102), True, 'import matplotlib.pyplot as plt\n'), ((5110, 5152), 'matplotlib.pyplot.GridSpec', 'plt.GridSpec', (['(2)', '(3)'], {'wspace': '(0.5)', 'hspace': '(0.5)'}), '(2, 3, wspace=0.5, hspace=0.5)\n', (5122, 5152), True, 'import matplotlib.pyplot as plt\n'), ((5154, 5181), 'matplotlib.pyplot.subplot', 'plt.subplot', (['grid[0:2, 0:2]'], {}), '(grid[0:2, 0:2])\n', (5165, 5181), True, 'import matplotlib.pyplot as plt\n'), ((5182, 5251), 'matplotlib.pyplot.contourf', 'plt.contourf', (['xx', 'yy', 'grid_predictions'], {'cmap': 'plt.cm.Paired', 'alpha': '(0.8)'}), '(xx, yy, grid_predictions, cmap=plt.cm.Paired, alpha=0.8)\n', (5194, 5251), True, 'import matplotlib.pyplot as plt\n'), ((5252, 5305), 'matplotlib.pyplot.plot', 'plt.plot', (['class1_x', 'class1_y', '"""ro"""'], {'label': '"""I. setosa"""'}), "(class1_x, class1_y, 'ro', label='I. setosa')\n", (5260, 5305), True, 'import matplotlib.pyplot as plt\n'), ((5306, 5363), 'matplotlib.pyplot.plot', 'plt.plot', (['class2_x', 'class2_y', '"""kx"""'], {'label': '"""I. versicolor"""'}), "(class2_x, class2_y, 'kx', label='I. versicolor')\n", (5314, 5363), True, 'import matplotlib.pyplot as plt\n'), ((5364, 5420), 'matplotlib.pyplot.plot', 'plt.plot', (['class3_x', 'class3_y', '"""gv"""'], {'label': '"""I. virginica"""'}), "(class3_x, class3_y, 'gv', label='I. virginica')\n", (5372, 5420), True, 'import matplotlib.pyplot as plt\n'), ((5421, 5467), 'matplotlib.pyplot.title', 'plt.title', (['"""Gaussian SVM Results on Iris Data"""'], {}), "('Gaussian SVM Results on Iris Data')\n", (5430, 5467), True, 'import matplotlib.pyplot as plt\n'), ((5468, 5494), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Pedal Length"""'], {}), "('Pedal Length')\n", (5478, 5494), True, 'import matplotlib.pyplot as plt\n'), ((5495, 5520), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Sepal Width"""'], {}), "('Sepal Width')\n", (5505, 5520), True, 'import matplotlib.pyplot as plt\n'), ((5521, 5550), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""lower right"""'}), "(loc='lower right')\n", (5531, 5550), True, 'import matplotlib.pyplot as plt\n'), ((5551, 5572), 'matplotlib.pyplot.ylim', 'plt.ylim', (['[-0.5, 3.0]'], {}), '([-0.5, 3.0])\n', (5559, 5572), True, 'import matplotlib.pyplot as plt\n'), ((5573, 5593), 'matplotlib.pyplot.xlim', 'plt.xlim', (['[3.5, 8.5]'], {}), '([3.5, 8.5])\n', (5581, 5593), True, 'import matplotlib.pyplot as plt\n'), ((5595, 5618), 'matplotlib.pyplot.subplot', 'plt.subplot', (['grid[0, 2]'], {}), '(grid[0, 2])\n', (5606, 5618), True, 'import matplotlib.pyplot as plt\n'), ((5619, 5667), 'matplotlib.pyplot.plot', 'plt.plot', (['batch_accuracy', '"""k-"""'], {'label': '"""Accuracy"""'}), "(batch_accuracy, 'k-', label='Accuracy')\n", (5627, 5667), True, 'import matplotlib.pyplot as plt\n'), ((5668, 5695), 'matplotlib.pyplot.title', 'plt.title', (['"""Batch Accuracy"""'], {}), "('Batch Accuracy')\n", (5677, 5695), True, 'import matplotlib.pyplot as plt\n'), ((5696, 5720), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Generation"""'], {}), "('Generation')\n", (5706, 5720), True, 'import matplotlib.pyplot as plt\n'), ((5721, 5743), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Accuracy"""'], {}), "('Accuracy')\n", (5731, 5743), True, 'import matplotlib.pyplot as plt\n'), ((5744, 5773), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""lower right"""'}), "(loc='lower right')\n", (5754, 5773), True, 'import matplotlib.pyplot as plt\n'), ((5775, 5798), 'matplotlib.pyplot.subplot', 'plt.subplot', (['grid[1, 2]'], {}), '(grid[1, 2])\n', (5786, 5798), True, 'import matplotlib.pyplot as plt\n'), ((5799, 5823), 'matplotlib.pyplot.plot', 'plt.plot', (['loss_ves', '"""k-"""'], {}), "(loss_ves, 'k-')\n", (5807, 5823), True, 'import matplotlib.pyplot as plt\n'), ((5824, 5856), 'matplotlib.pyplot.title', 'plt.title', (['"""Loss per Generation"""'], {}), "('Loss per Generation')\n", (5833, 5856), True, 'import matplotlib.pyplot as plt\n'), ((5857, 5881), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Generation"""'], {}), "('Generation')\n", (5867, 5881), True, 'import matplotlib.pyplot as plt\n'), ((5882, 5900), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Loss"""'], {}), "('Loss')\n", (5892, 5900), True, 'import matplotlib.pyplot as plt\n'), ((5901, 5911), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (5909, 5911), True, 'import matplotlib.pyplot as plt\n'), ((1705, 1744), 'tensorflow.random_normal', 'tf.random_normal', ([], {'shape': '[3, batch_size]'}), '(shape=[3, batch_size])\n', (1721, 1744), True, 'import tensorflow as tf\n'), ((1824, 1841), 'tensorflow.square', 'tf.square', (['x_data'], {}), '(x_data)\n', (1833, 1841), True, 'import tensorflow as tf\n'), ((1974, 1992), 'tensorflow.transpose', 'tf.transpose', (['dist'], {}), '(dist)\n', (1986, 1992), True, 'import tensorflow as tf\n'), ((2383, 2405), 'tensorflow.expand_dims', 'tf.expand_dims', (['mat', '(1)'], {}), '(mat, 1)\n', (2397, 2405), True, 'import tensorflow as tf\n'), ((2415, 2449), 'tensorflow.reshape', 'tf.reshape', (['v1', '[3, batch_size, 1]'], {}), '(v1, [3, batch_size, 1])\n', (2425, 2449), True, 'import tensorflow as tf\n'), ((2461, 2478), 'tensorflow.matmul', 'tf.matmul', (['v2', 'v1'], {}), '(v2, v1)\n', (2470, 2478), True, 'import tensorflow as tf\n'), ((2627, 2642), 'tensorflow.transpose', 'tf.transpose', (['b'], {}), '(b)\n', (2639, 2642), True, 'import tensorflow as tf\n'), ((3334, 3350), 'tensorflow.transpose', 'tf.transpose', (['rB'], {}), '(rB)\n', (3346, 3350), True, 'import tensorflow as tf\n'), ((3700, 3724), 'tensorflow.multiply', 'tf.multiply', (['y_target', 'b'], {}), '(y_target, b)\n', (3711, 3724), True, 'import tensorflow as tf\n'), ((4776, 4805), 'numpy.arange', 'np.arange', (['x_min', 'x_max', '(0.02)'], {}), '(x_min, x_max, 0.02)\n', (4785, 4805), True, 'import numpy as np\n'), ((4807, 4836), 'numpy.arange', 'np.arange', (['y_min', 'y_max', '(0.02)'], {}), '(y_min, y_max, 0.02)\n', (4816, 4836), True, 'import numpy as np\n'), ((2032, 2048), 'tensorflow.abs', 'tf.abs', (['sq_dists'], {}), '(sq_dists)\n', (2038, 2048), True, 'import tensorflow as tf\n'), ((2741, 2781), 'tensorflow.multiply', 'tf.multiply', (['b_vec_cross', 'y_target_cross'], {}), '(b_vec_cross, y_target_cross)\n', (2752, 2781), True, 'import tensorflow as tf\n'), ((2825, 2861), 'tensorflow.subtract', 'tf.subtract', (['first_term', 'second_term'], {}), '(first_term, second_term)\n', (2836, 2861), True, 'import tensorflow as tf\n'), ((3125, 3142), 'tensorflow.square', 'tf.square', (['x_data'], {}), '(x_data)\n', (3134, 3142), True, 'import tensorflow as tf\n'), ((3187, 3213), 'tensorflow.square', 'tf.square', (['prediction_grid'], {}), '(prediction_grid)\n', (3196, 3213), True, 'import tensorflow as tf\n'), ((3392, 3412), 'tensorflow.abs', 'tf.abs', (['pred_sq_dist'], {}), '(pred_sq_dist)\n', (3398, 3412), True, 'import tensorflow as tf\n'), ((3797, 3833), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['prediction_output', '(1)'], {}), '(prediction_output, 1)\n', (3811, 3833), True, 'import tensorflow as tf\n'), ((3897, 3919), 'tensorflow.argmax', 'tf.argmax', (['y_target', '(0)'], {}), '(y_target, 0)\n', (3906, 3919), True, 'import tensorflow as tf\n'), ((1949, 1969), 'tensorflow.transpose', 'tf.transpose', (['x_data'], {}), '(x_data)\n', (1961, 1969), True, 'import tensorflow as tf\n'), ((3300, 3329), 'tensorflow.transpose', 'tf.transpose', (['prediction_grid'], {}), '(prediction_grid)\n', (3312, 3329), True, 'import tensorflow as tf\n')]
# coding: utf-8 # #def ceti_exp( # GHZ_inner, GHZ_outer, tau_awakening, tau_survive, D_max, t_max #): ##{{{ # # import ceti_tools as ct # # random.seed(420) # np.random.seed(420) # # # lista de CETIs alguna vez activas # CETIs = dict() # # # lista de CETIs actualmente activas # CHATs = [] # CHATs_idx = [] # # # inicializacion del tiempo: scalar # t_now = 0 # # inicializacion del ID: index # ID = 0 # # # lista de tiempos de eventos futuros: ordered list # # [time, ID_emit, ID_receive, case] # t_forthcoming = ct.OrderedList() # # # estructura de arbol para buscar vecinos # try: # del tree # except NameError: # pass # # # INITIALIZATION # # Simulation starts when the first CETI appears: # next_event = [0., 0, None, 1] # t_forthcoming.add(next_event) # # # SIMULATION LOOP OVER TIME # while (t_now < t_max): # # t_now, ID_emit, ID_hear, case = t_forthcoming.head.getData() # # if case == 1: # # # print('desaparece CETI con id:%d' % ID_emit) # ID_new = ID_emit # ID_next = ID_new + 1 # t_new_hola = t_now # # # sortear el lugar donde aparece dentro de la GHZ # r = np.sqrt(random.random()*GHZ_outer**2 + GHZ_inner**2) # o = random.random()*2.*np.pi # x = r * np.cos(o) # X position on the galactic plane # y = r * np.sin(o) # Y position on the galactic plane # # # sortear el tiempo de actividad # t_new_active = np.random.exponential(tau_survive, 1)[0] # t_new_chau = t_new_hola + t_new_active # # # agregar el tiempo de desaparición a la lista de tiempos # next_event = [t_new_chau, ID_new, None, 2] # t_forthcoming.add(next_event) # # # agregar la CETI a la lista histórica # CETIs[ID_new] = list() # CETIs[ID_new].append( # (ID_new, ID_new, x, y, t_new_hola, t_new_chau)) # # # sortear el tiempo de aparición de la próxima CETI # t_next_awakening = np.random.exponential(tau_awakening, 1)[0] # t_next_awakening = t_new_hola + t_next_awakening # if t_next_awakening < t_max: # next_event = [t_next_awakening, ID_next, None, 1] # t_forthcoming.add(next_event) # # if len(CHATs_idx) > 0: # # # if there are other CETIs, compute contacts: # # encontrar todas (los IDs de) las CETIs dentro del radio D_max # query_point = [x, y] # idx = tree.query_ball_point(query_point, r=D_max) # # # traverse all CETIs within reach # for k in idx: # # ID_old = CHATs_idx[k] # # Dx = np.sqrt( # ((np.array(query_point) - # np.array(CETIs[ID_old][0][2:4]))**2).sum() # ) # # t_old_hola, t_old_chau = CETIs[ID_old][0][4:6] # # # check if contact is possible # new_can_see_old = ( # (Dx < D_max) & # (t_new_hola < t_old_chau + Dx) & # (t_new_chau > t_old_hola + Dx)) # # if new_can_see_old: # (·) new sees old # # # :start (type 3 event) # t_new_see_old_start = max(t_old_hola + Dx, t_new_hola) # next_event = [t_new_see_old_start, ID_new, ID_old, 3] # t_forthcoming.add(next_event) # # # :end (type 4 event) # t_new_see_old_end = min(t_old_chau + Dx, t_new_chau) # next_event = [t_new_see_old_end, ID_new, ID_old, 4] # t_forthcoming.add(next_event) # # contact = (ID_new, ID_old, # CETIs[ID_old][0][2], CETIs[ID_old][0][3], # t_new_see_old_start, t_new_see_old_end) # CETIs[ID_new].append(contact) # # # check if contact is possible # old_can_see_new = ( # (Dx < D_max) & (t_new_hola+Dx > t_old_hola) & # (t_new_hola+Dx < t_old_chau)) # # if old_can_see_new: # (·) old sees new # # # :start (type 3 event) # t_old_see_new_start = t_new_hola + Dx # next_event = [t_old_see_new_start, ID_old, ID_new, 3] # t_forthcoming.add(next_event) # # # :end (type 4 event) # t_old_see_new_end = min(t_new_chau+Dx, t_old_chau) # next_event = [t_old_see_new_end, ID_old, ID_new, 4] # t_forthcoming.add(next_event) # # contact = (ID_old, ID_new, # CETIs[ID_new][0][2], CETIs[ID_new][0][3], # t_old_see_new_start, t_old_see_new_end) # CETIs[ID_old].append(contact) # # # agregar la CETI a la lista de posiciones de CETIs activas (CHATs) # CHATs.append([x, y]) # CHATs_idx.append(ID_new) # # # rehacer el árbol # tree = sp.cKDTree(data=CHATs) # # if case == 2: # ID_bye = ID_emit # # # eliminar la CETI a la lista de CETIs activas # # [ID, x, y, t_new_hola, t_new_chau] # try: # id_loc = CHATs_idx.index(ID_bye) # del CHATs[id_loc] # del CHATs_idx[id_loc] # # except TypeError: # pass # # # rehacer el árbol # if len(CHATs) > 0: # tree = sp.cKDTree(data=CHATs) # # if case == 3: pass # if case == 4: pass # # # eliminar el tiempo actual # t_forthcoming.remove_first() # # salir si no queda nada para hacer: # if t_forthcoming.size() < 1: # break # t_forthcoming.show() # # return(CETIs) ##}}} # import ceti_exp import numpy as np import random import pandas as pd from scipy import spatial as sp import time import sys import pickle import ceti_tools as ct # para recargar el modulo si se hacen modificaciones: from importlib import reload ct = reload(ct) # para guardar la salida from io import StringIO # DEBUGING # import pdb; pdb.set_trace() # CASES: # 1 - awakening # 2 - doomsday # 3 - contact # 4 - blackout random.seed(420) np.random.seed(420) message = "PRESS%ENTER%TO%CONTINUE" message = "~~~~~~~~~~~~~~~~~~~~~~~" message = "\n"+message*3+"\n" message = "" state = ['awakening','doomsday','contact ','blackout'] # FIXED AND SIMULATION VARIABLES # {{{ # PARAMETERS ::: # radio interno de la zona galactica habitable, años luz GHZ_inner = 1000.0 # radio interno de la zona galactica habitable, años luz GHZ_outer = 5000.0 # tiempo medio, en años, que hay que esperar para que # aparezca otra CETI en la galaxia tau_awakening = 500. # Tiempo medio, en años, durante el cual una CETI esta activa tau_survive = 1000. # Maxima distancia, en años luz, a la cual una CETI puede # enviar o recibir mensajes D_max = 3000. # maximo tiempo para simular t_max = 5000. # flag to set interactive session interactive = True # }}} # {{{ # VARIABLES ::: # lista de CETIs alguna vez activas: dictionary CETIs = dict() # lista de CETIs actualmente activas: ndarray CHATs = [] CHATs_idx = [] # inicializacion del tiempo: scalar t_now = 0 # inicializacion del ID: index ID = 0 # lista de tiempos de eventos futuros: ordered list # [time, ID_emit, ID_receive, case] t_forthcoming = ct.OrderedList() # estructura de arbol para buscar vecinos try: del tree except NameError: pass # INITIALIZATION # Simulation starts when the first CETI appears: next_event = [0., 0, None, 1] t_forthcoming.add(next_event) if not interactive: old_stdout = sys.stdout result = StringIO() sys.stdout = result # SIMULATION LOOP OVER TIME while (t_now < t_max): t_now, ID_emit, ID_hear, case = t_forthcoming.head.getData() if interactive: wait = input(message) print('<<< t = %f >>> %10s of %3d' % (t_now, state[case-1], ID_emit)) #print('[ case:%d | id:%d ] <<< t = %f >>>' % (case, ID_emit, t_now)) #print(' active CETIs', CHATs_idx) print(CHATs_idx) #t_forthcoming.show() # sys.stdout.write("\rTime: %f (max=%f)\n" % (t_now, t_max)) # sys.stdout.flush() # print('tiempo: %9.3f | ID_emit: %5d|CASE %1d'%(t_now,ID_emit,case)) if case == 1: # ------------------------------------- # NEW CETI # ------------------------------------- # {{{ # print('desaparece CETI con id:%d' % ID_emit) ID_new = ID_emit ID_next = ID_new + 1 t_new_hola = t_now # sortear el lugar donde aparece dentro de la GHZ r = np.sqrt(random.random()*GHZ_outer**2 + GHZ_inner**2) o = random.random()*2.*np.pi x = r * np.cos(o) # X position on the galactic plane y = r * np.sin(o) # Y position on the galactic plane #print('posiciones para el ID %5d :::: %8.3f %8.3f' % (ID_new, x, y)) # sortear el tiempo de actividad t_new_active = np.random.exponential(tau_survive, 1)[0] t_new_chau = t_new_hola + t_new_active #print('tiempos para el ID %2d :::: %8.3f %8.3f' % (ID_new, t_new_active, t_new_chau)) # agregar el tiempo de desaparición a la lista de tiempos next_event = [t_new_chau, ID_new, None, 2] t_forthcoming.add(next_event) # agregar la CETI a la lista histórica CETIs[ID_new] = list() CETIs[ID_new].append( (ID_new, ID_new, x, y, t_new_hola, t_new_chau)) # sortear el tiempo de aparición de la próxima CETI t_next_awakening = np.random.exponential(tau_awakening, 1)[0] t_next_awakening = t_new_hola + t_next_awakening if t_next_awakening < t_max: next_event = [t_next_awakening, ID_next, None, 1] t_forthcoming.add(next_event) if len(CHATs_idx) > 0: #print('entering loop to compute contacts') # if there are other CETIs, compute contacts: # encontrar todas (los IDs de) las CETIs dentro del radio D_max query_point = [x, y] idx = tree.query_ball_point(query_point, r=D_max) # traverse all CETIs within reach for k in idx: #print(k) ID_old = CHATs_idx[k] Dx = np.sqrt( ((np.array(query_point) - np.array(CETIs[ID_old][0][2:4]))**2).sum() ) t_old_hola, t_old_chau = CETIs[ID_old][0][4:6] # check if contact is possible new_can_see_old = ( (Dx < D_max) & (t_new_hola < t_old_chau + Dx) & (t_new_chau > t_old_hola + Dx)) if new_can_see_old: # (·) new sees old # :start (type 3 event) t_new_see_old_start = max(t_old_hola + Dx, t_new_hola) next_event = [t_new_see_old_start, ID_new, ID_old, 3] t_forthcoming.add(next_event) # :end (type 4 event) t_new_see_old_end = min(t_old_chau + Dx, t_new_chau) next_event = [t_new_see_old_end, ID_new, ID_old, 4] t_forthcoming.add(next_event) contact = (ID_new, ID_old, CETIs[ID_old][0][2], CETIs[ID_old][0][3], t_new_see_old_start, t_new_see_old_end) CETIs[ID_new].append(contact) # check if contact is possible old_can_see_new = ( (Dx < D_max) & (t_new_hola+Dx > t_old_hola) & (t_new_hola+Dx < t_old_chau)) if old_can_see_new: # (·) old sees new # :start (type 3 event) t_old_see_new_start = t_new_hola + Dx next_event = [t_old_see_new_start, ID_old, ID_new, 3] t_forthcoming.add(next_event) # :end (type 4 event) t_old_see_new_end = min(t_new_chau+Dx, t_old_chau) next_event = [t_old_see_new_end, ID_old, ID_new, 4] t_forthcoming.add(next_event) contact = (ID_old, ID_new, CETIs[ID_new][0][2], CETIs[ID_new][0][3], t_old_see_new_start, t_old_see_new_end) CETIs[ID_old].append(contact) # agregar la CETI a la lista de posiciones de CETIs activas (CHATs) CHATs.append([x, y]) CHATs_idx.append(ID_new) # rehacer el árbol tree = sp.cKDTree(data=CHATs) # }}} if case == 2: # ------------------------------------- # END CETI # ------------------------------------- # {{{ # print('desaparece CETI con id:%d' % ID_emit) ID_bye = ID_emit # eliminar la CETI a la lista de CETIs activas # [ID, x, y, t_new_hola, t_new_chau] try: id_loc = CHATs_idx.index(ID_bye) del CHATs[id_loc] del CHATs_idx[id_loc] except TypeError: pass # rehacer el árbol if len(CHATs) > 0: tree = sp.cKDTree(data=CHATs) # }}} if case == 3: # ------------------------------------- # NEW CONTACT # ------------------------------------- # {{{ pass # print('primer contacto entre %d y %d' % (ID_emit, ID_hear)) # }}} if case == 4: # ------------------------------------- # END CONTACT # ------------------------------------- # {{{ pass # print('ultimo contacto entre %d y %d' % (ID_emit, ID_hear)) # }}} # eliminar el tiempo actual t_forthcoming.remove_first() # salir si no queda nada para hacer: if t_forthcoming.size() < 1: break t_forthcoming.show() print(CHATs_idx) print('\n\n') ct.ShowCETIs(CETIs) if not interactive: sys.stdout = old_stdout result_string = result.getvalue() i = input('experiment code: ').zfill(3) fname = 'experiment_' + i + '.dat' savef = open(fname,'w') savef.write(result_string) savef.close() # El experimento consiste es correr interactivamente hasta que se # corrobora que anda bien. Luego puse la funcion en un modulo, la # llamo con la misma semilla y anda igual # #fCETIs = ceti_exp.ceti_exp( # GHZ_inner, GHZ_outer, tau_awakening, tau_survive, D_max, t_max #) #ct.ShowCETIs(fCETIs)
[ "ceti_tools.ShowCETIs", "io.StringIO", "numpy.random.seed", "ceti_tools.OrderedList", "numpy.random.exponential", "random.random", "importlib.reload", "numpy.sin", "random.seed", "numpy.array", "numpy.cos", "scipy.spatial.cKDTree" ]
[((6661, 6671), 'importlib.reload', 'reload', (['ct'], {}), '(ct)\n', (6667, 6671), False, 'from importlib import reload\n'), ((6835, 6851), 'random.seed', 'random.seed', (['(420)'], {}), '(420)\n', (6846, 6851), False, 'import random\n'), ((6852, 6871), 'numpy.random.seed', 'np.random.seed', (['(420)'], {}), '(420)\n', (6866, 6871), True, 'import numpy as np\n'), ((8008, 8024), 'ceti_tools.OrderedList', 'ct.OrderedList', ([], {}), '()\n', (8022, 8024), True, 'import ceti_tools as ct\n'), ((14720, 14739), 'ceti_tools.ShowCETIs', 'ct.ShowCETIs', (['CETIs'], {}), '(CETIs)\n', (14732, 14739), True, 'import ceti_tools as ct\n'), ((8303, 8313), 'io.StringIO', 'StringIO', ([], {}), '()\n', (8311, 8313), False, 'from io import StringIO\n'), ((13357, 13379), 'scipy.spatial.cKDTree', 'sp.cKDTree', ([], {'data': 'CHATs'}), '(data=CHATs)\n', (13367, 13379), True, 'from scipy import spatial as sp\n'), ((9371, 9380), 'numpy.cos', 'np.cos', (['o'], {}), '(o)\n', (9377, 9380), True, 'import numpy as np\n'), ((9433, 9442), 'numpy.sin', 'np.sin', (['o'], {}), '(o)\n', (9439, 9442), True, 'import numpy as np\n'), ((9624, 9661), 'numpy.random.exponential', 'np.random.exponential', (['tau_survive', '(1)'], {}), '(tau_survive, 1)\n', (9645, 9661), True, 'import numpy as np\n'), ((10222, 10261), 'numpy.random.exponential', 'np.random.exponential', (['tau_awakening', '(1)'], {}), '(tau_awakening, 1)\n', (10243, 10261), True, 'import numpy as np\n'), ((13965, 13987), 'scipy.spatial.cKDTree', 'sp.cKDTree', ([], {'data': 'CHATs'}), '(data=CHATs)\n', (13975, 13987), True, 'from scipy import spatial as sp\n'), ((9330, 9345), 'random.random', 'random.random', ([], {}), '()\n', (9343, 9345), False, 'import random\n'), ((9273, 9288), 'random.random', 'random.random', ([], {}), '()\n', (9286, 9288), False, 'import random\n'), ((10982, 11003), 'numpy.array', 'np.array', (['query_point'], {}), '(query_point)\n', (10990, 11003), True, 'import numpy as np\n'), ((11035, 11066), 'numpy.array', 'np.array', (['CETIs[ID_old][0][2:4]'], {}), '(CETIs[ID_old][0][2:4])\n', (11043, 11066), True, 'import numpy as np\n')]
import os import json import numpy as np from uninas.optimization.benchmarks.mini.tabular import MiniNASTabularBenchmark, explore, plot from uninas.optimization.benchmarks.mini.result import MiniResult from uninas.optimization.hpo.uninas.values import DiscreteValues, ValueSpace from uninas.utils.paths import replace_standard_paths, name_task_config, find_all_files from uninas.utils.parsing.tensorboard_ import find_tb_files, read_event_files from uninas.utils.misc import split from uninas.utils.torch.standalone import get_dataset_from_json, get_network from uninas.register import Register from uninas.builder import Builder @Register.benchmark_set(mini=True, tabular=True) class MiniNASParsedTabularBenchmark(MiniNASTabularBenchmark): """ go through a directory of training save-dirs, parsing the results of each single training run and its used architecture assumptions: - all networks are created as RetrainFromSearchUninasNetwork, so that their genes can be easily read """ @classmethod def make_from_single_dir(cls, path: str, space_name: str, arch_index: int) -> MiniResult: """ creating a mini result by parsing a training process """ # find gene and dataset in the task config task_configs = find_all_files(path, extension=name_task_config) assert len(task_configs) == 1 with open(task_configs[0]) as config_file: config = json.load(config_file) gene = config.get('{cls_network}.gene') gene = split(gene, int) data_set = get_dataset_from_json(task_configs[0], fake=True) data_set_name = data_set.__class__.__name__ # find loss and acc in the tensorboard files tb_files = find_tb_files(path) assert len(tb_files) > 0 events = read_event_files(tb_files) loss_train = events.get("train/loss", None) loss_test = events.get("test/loss", None) assert (loss_train is not None) and (loss_test is not None) accuracy_train = events.get("train/accuracy/1", None) accuracy_test = events.get("test/accuracy/1", None) assert (accuracy_train is not None) and (accuracy_test is not None) # figure out params and flops by building the network net_config_path = Builder.find_net_config_path(path) network = get_network(net_config_path, data_set.get_data_shape(), data_set.get_label_shape()) # figure out latency at some point pass # return result average_last = 5 return MiniResult( arch_index=arch_index, arch_str="%s(%s)" % (space_name, ", ".join([str(g) for g in gene])), arch_tuple=tuple(gene), params={data_set_name: network.get_num_parameters()}, flops={data_set_name: network.profile_macs()}, latency={data_set_name: -1}, loss={data_set_name: { 'train': np.mean([v.value for v in loss_train[-average_last:]]), 'test': np.mean([v.value for v in loss_test[-average_last:]]), }}, acc1={data_set_name: { 'train': np.mean([v.value for v in accuracy_train[-average_last:]]), 'test': np.mean([v.value for v in accuracy_test[-average_last:]]), }}, ) @classmethod def make_from_dirs(cls, path: str, space_name: str, value_space: ValueSpace): """ creating a mini bench dataset by parsing multiple training processes """ results = [] merged_results = {} arch_to_idx = {} tuple_to_str = {} tuple_to_idx = {} # find all results task_configs = find_all_files(path, extension=name_task_config) assert len(task_configs) > 0 for i, cfg_path in enumerate(sorted(task_configs)): dir_name = os.path.dirname(cfg_path) r = cls.make_from_single_dir(dir_name, space_name, arch_index=i) if r is None: continue assert tuple_to_str.get(r.arch_tuple) is None,\ "can not yet merge duplicate architecture results: %s, in %s" % (r.arch_tuple, dir_name) results.append(r) # merge duplicates len_before = len(results) results = MiniResult.merge_result_list(results) print("merging: had %d before, merged down to %d" % (len_before, len(results))) # build lookup tables for i, r in enumerate(results): r.arch_index = i merged_results[i] = r arch_to_idx[r.arch_str] = i tuple_to_idx[r.arch_tuple] = i tuple_to_str[r.arch_tuple] = r.arch_str # build bench set data_sets = list(merged_results.get(0).params.keys()) return MiniNASParsedTabularBenchmark( default_data_set=data_sets[0], default_result_type='test', bench_name="%s on %s" % (space_name, data_sets[0]), bench_description="parsed empirical results", value_space=value_space, results=merged_results, arch_to_idx=arch_to_idx, tuple_to_str=tuple_to_str, tuple_to_idx=tuple_to_idx) def create_fairnas(path: str) -> MiniNASParsedTabularBenchmark: space_name = "fairnas" value_space = ValueSpace(*[DiscreteValues.interval(0, 6) for _ in range(19)]) return MiniNASParsedTabularBenchmark.make_from_dirs(path, space_name, value_space) def create_bench201(path: str) -> MiniNASParsedTabularBenchmark: space_name = "bench201" value_space = ValueSpace(*[DiscreteValues.interval(0, 5) for _ in range(6)]) return MiniNASParsedTabularBenchmark.make_from_dirs(path, space_name, value_space) def sample_architectures(mini: MiniNASParsedTabularBenchmark, n=10): """ sample some random architectures to train """ for i in range(n): print(i, '\t\t', mini.get_value_space().random_sample()) if __name__ == '__main__': Builder() # path_ = replace_standard_paths('{path_data}/bench/sin/bench201_n5c16_1.pt') # mini_ = create_bench201("{path_cluster}/full/test_s3_bench/Cifar100Data/bench201_n5c16/") # path_ = replace_standard_paths('{path_data}/bench/sin/bench201_n4c64_1.pt') # mini_ = create_bench201("{path_cluster}/full/test_s3_bench/Cifar100Data/bench201_n4c64/") # path_ = replace_standard_paths('{path_data}/bench/sin/SIN_fairnas_small_only1.pt') # mini_ = create_fairnas("{path_cluster}/full/s3sin/SubImagenetMV100Data/fairnas/1/") path_ = replace_standard_paths('{path_data}/bench/sin/SIN_fairnas_v0.1.pt') # mini_ = create_fairnas("{path_cluster}/full/s3sin/SubImagenetMV100Data/fairnas/") mini_ = MiniNASParsedTabularBenchmark.load(path_) sample_architectures(mini_) explore(mini_) plot(mini_, ['flops', 'acc1'], [False, True], add_pareto=True) """ # average acc of the top 10 networks mini_.set_default_result_type("test") accs = [] for r in mini_.get_all_sorted(["acc1"], maximize=[True]): accs.append(r.get_acc1()) print(sum(accs[:10]) / 10) """ mini_.save(path_)
[ "uninas.utils.parsing.tensorboard_.find_tb_files", "json.load", "uninas.optimization.benchmarks.mini.tabular.plot", "uninas.optimization.benchmarks.mini.result.MiniResult.merge_result_list", "os.path.dirname", "uninas.builder.Builder", "uninas.utils.paths.replace_standard_paths", "uninas.utils.torch.s...
[((633, 680), 'uninas.register.Register.benchmark_set', 'Register.benchmark_set', ([], {'mini': '(True)', 'tabular': '(True)'}), '(mini=True, tabular=True)\n', (655, 680), False, 'from uninas.register import Register\n'), ((5978, 5987), 'uninas.builder.Builder', 'Builder', ([], {}), '()\n', (5985, 5987), False, 'from uninas.builder import Builder\n'), ((6539, 6606), 'uninas.utils.paths.replace_standard_paths', 'replace_standard_paths', (['"""{path_data}/bench/sin/SIN_fairnas_v0.1.pt"""'], {}), "('{path_data}/bench/sin/SIN_fairnas_v0.1.pt')\n", (6561, 6606), False, 'from uninas.utils.paths import replace_standard_paths, name_task_config, find_all_files\n'), ((6788, 6802), 'uninas.optimization.benchmarks.mini.tabular.explore', 'explore', (['mini_'], {}), '(mini_)\n', (6795, 6802), False, 'from uninas.optimization.benchmarks.mini.tabular import MiniNASTabularBenchmark, explore, plot\n'), ((6807, 6869), 'uninas.optimization.benchmarks.mini.tabular.plot', 'plot', (['mini_', "['flops', 'acc1']", '[False, True]'], {'add_pareto': '(True)'}), "(mini_, ['flops', 'acc1'], [False, True], add_pareto=True)\n", (6811, 6869), False, 'from uninas.optimization.benchmarks.mini.tabular import MiniNASTabularBenchmark, explore, plot\n'), ((1286, 1334), 'uninas.utils.paths.find_all_files', 'find_all_files', (['path'], {'extension': 'name_task_config'}), '(path, extension=name_task_config)\n', (1300, 1334), False, 'from uninas.utils.paths import replace_standard_paths, name_task_config, find_all_files\n'), ((1760, 1779), 'uninas.utils.parsing.tensorboard_.find_tb_files', 'find_tb_files', (['path'], {}), '(path)\n', (1773, 1779), False, 'from uninas.utils.parsing.tensorboard_ import find_tb_files, read_event_files\n'), ((1830, 1856), 'uninas.utils.parsing.tensorboard_.read_event_files', 'read_event_files', (['tb_files'], {}), '(tb_files)\n', (1846, 1856), False, 'from uninas.utils.parsing.tensorboard_ import find_tb_files, read_event_files\n'), ((2315, 2349), 'uninas.builder.Builder.find_net_config_path', 'Builder.find_net_config_path', (['path'], {}), '(path)\n', (2343, 2349), False, 'from uninas.builder import Builder\n'), ((3722, 3770), 'uninas.utils.paths.find_all_files', 'find_all_files', (['path'], {'extension': 'name_task_config'}), '(path, extension=name_task_config)\n', (3736, 3770), False, 'from uninas.utils.paths import replace_standard_paths, name_task_config, find_all_files\n'), ((4320, 4357), 'uninas.optimization.benchmarks.mini.result.MiniResult.merge_result_list', 'MiniResult.merge_result_list', (['results'], {}), '(results)\n', (4348, 4357), False, 'from uninas.optimization.benchmarks.mini.result import MiniResult\n'), ((1446, 1468), 'json.load', 'json.load', (['config_file'], {}), '(config_file)\n', (1455, 1468), False, 'import json\n'), ((1540, 1556), 'uninas.utils.misc.split', 'split', (['gene', 'int'], {}), '(gene, int)\n', (1545, 1556), False, 'from uninas.utils.misc import split\n'), ((1581, 1630), 'uninas.utils.torch.standalone.get_dataset_from_json', 'get_dataset_from_json', (['task_configs[0]'], {'fake': '(True)'}), '(task_configs[0], fake=True)\n', (1602, 1630), False, 'from uninas.utils.torch.standalone import get_dataset_from_json, get_network\n'), ((3891, 3916), 'os.path.dirname', 'os.path.dirname', (['cfg_path'], {}), '(cfg_path)\n', (3906, 3916), False, 'import os\n'), ((5331, 5360), 'uninas.optimization.hpo.uninas.values.DiscreteValues.interval', 'DiscreteValues.interval', (['(0)', '(6)'], {}), '(0, 6)\n', (5354, 5360), False, 'from uninas.optimization.hpo.uninas.values import DiscreteValues, ValueSpace\n'), ((5595, 5624), 'uninas.optimization.hpo.uninas.values.DiscreteValues.interval', 'DiscreteValues.interval', (['(0)', '(5)'], {}), '(0, 5)\n', (5618, 5624), False, 'from uninas.optimization.hpo.uninas.values import DiscreteValues, ValueSpace\n'), ((2964, 3018), 'numpy.mean', 'np.mean', (['[v.value for v in loss_train[-average_last:]]'], {}), '([v.value for v in loss_train[-average_last:]])\n', (2971, 3018), True, 'import numpy as np\n'), ((3044, 3097), 'numpy.mean', 'np.mean', (['[v.value for v in loss_test[-average_last:]]'], {}), '([v.value for v in loss_test[-average_last:]])\n', (3051, 3097), True, 'import numpy as np\n'), ((3175, 3233), 'numpy.mean', 'np.mean', (['[v.value for v in accuracy_train[-average_last:]]'], {}), '([v.value for v in accuracy_train[-average_last:]])\n', (3182, 3233), True, 'import numpy as np\n'), ((3259, 3316), 'numpy.mean', 'np.mean', (['[v.value for v in accuracy_test[-average_last:]]'], {}), '([v.value for v in accuracy_test[-average_last:]])\n', (3266, 3316), True, 'import numpy as np\n')]
""" File: _advance.py Author: <NAME> GitHub: https://github.com/PanyiDong/ Mathematics Department, University of Illinois at Urbana-Champaign (UIUC) Project: My_AutoML Latest Version: 0.2.0 Relative Path: /My_AutoML/_feature_selection/_advance.py File Created: Tuesday, 5th April 2022 11:36:15 pm Author: <NAME> (<EMAIL>) ----- Last Modified: Friday, 29th April 2022 10:27:54 am Modified By: <NAME> (<EMAIL>) ----- MIT License Copyright (c) 2022 - 2022, <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from inspect import isclass from typing import Callable from itertools import combinations from collections import Counter from My_AutoML._utils._base import has_method import warnings import numpy as np import pandas as pd import itertools from My_AutoML._utils import ( minloc, maxloc, True_index, Pearson_Corr, MI, t_score, ANOVA, random_index, ) from My_AutoML._utils._optimize import ( get_estimator, get_metrics, ) class FeatureFilter: """ Use certain criteria to score each feature and select most relevent ones Parameters ---------- criteria: use what criteria to score features, default = 'Pearson' supported {'Pearson', 'MI'} 'Pearson': Pearson Correlation Coefficient 'MI': 'Mutual Information' n_components: threshold to retain features, default = None will be set to n_features n_prop: float, default = None proprotion of features to select, if None, no limit n_components have higher priority than n_prop """ def __init__( self, criteria="Pearson", n_components=None, n_prop=None, ): self.criteria = criteria self.n_components = n_components self.n_prop = n_prop self._fitted = False def fit(self, X, y=None): # check whether y is empty if isinstance(y, pd.DataFrame): _empty = y.isnull().all().all() elif isinstance(y, pd.Series): _empty = y.isnull().all() elif isinstance(y, np.ndarray): _empty = np.all(np.isnan(y)) else: _empty = y == None if _empty: raise ValueError("Must have response!") if self.criteria == "Pearson": self._score = Pearson_Corr(X, y) elif self.criteria == "MI": self._score = MI(X, y) self._fitted = True return self def transform(self, X): # check whether n_components/n_prop is valid if self.n_components is None and self.n_prop is None: self.n_components = X.shape[1] elif self.n_components is not None: self.n_components = min(self.n_components, X.shape[1]) # make sure selected features is at least 1 elif self.n_prop is not None: self.n_components = max(1, int(self.n_prop * X.shape[1])) _columns = np.argsort(self._score)[: self.n_components] return X.iloc[:, _columns] # FeatureWrapper # Exhaustive search for optimal feature combination # Sequential Feature Selection (SFS) # Sequential Backward Selection (SBS) # Sequential Floating Forward Selection (SFFS) # Adapative Sequential Forward Floating Selection (ASFFS) class ASFFS: """ Adaptive Sequential Forward Floating Selection (ASFFS) Mostly, ASFFS performs the same as Sequential Floating Forward Selection (SFFS), where only one feature is considered as a time. But, when the selected features are coming close to the predefined maximum, a adaptive generalization limit will be activated, and more than one features can be considered at one time. The idea is to consider the correlation between features. [1] [1] <NAME>., <NAME>., <NAME>. and <NAME>., 1999. Adaptive floating search methods in feature selection. Pattern recognition letters, 20(11-13), pp.1157-1163. Parameters ---------- d: maximum features retained, default = None will be calculated as max(max(20, n), 0.5 * n) Delta: dynamic of maximum number of features, default = 0 d + Delta features will be retained b: range for adaptive generalization limit to activate, default = None will be calculated as max(5, 0.05 * n) r_max: maximum of generalization limit, default = 5 maximum features to be considered as one step model: the model used to evaluate the objective function, default = 'linear' supproted ('Linear', 'Lasso', 'Ridge') objective: the objective function of significance of the features, default = 'MSE' supported {'MSE', 'MAE'} """ def __init__( self, n_components=None, Delta=0, b=None, r_max=5, model="Linear", objective="MSE", ): self.n_components = n_components self.Delta = Delta self.b = b self.r_max = r_max self.model = model self.objective = objective self._fitted = False def generalization_limit(self, k, d, b): if np.abs(k - d) < b: r = self.r_max elif np.abs(k - d) < self.r_max + b: r = self.r_max + b - np.abs(k - d) else: r = 1 return r def _Forward_Objective(self, selected, unselected, o, X, y): _subset = list(itertools.combinations(unselected, o)) _comb_subset = [ selected + list(item) for item in _subset ] # concat selected features with new features _objective_list = [] if self.model == "Linear": from sklearn.linear_model import LinearRegression _model = LinearRegression() elif self.model == "Lasso": from sklearn.linear_model import Lasso _model = Lasso() elif self.model == "Ridge": from sklearn.linear_model import Ridge _model = Ridge() else: raise ValueError("Not recognizing model!") if self.objective == "MSE": from sklearn.metrics import mean_squared_error _obj = mean_squared_error elif self.objective == "MAE": from sklearn.metrics import mean_absolute_error _obj = mean_absolute_error for _set in _comb_subset: _model.fit(X[_set], y) _predict = _model.predict(X[_set]) _objective_list.append( 1 / _obj(y, _predict) ) # the goal is to maximize the objective function return ( _subset[maxloc(_objective_list)], _objective_list[maxloc(_objective_list)], ) def _Backward_Objective(self, selected, o, X, y): _subset = list(itertools.combinations(selected, o)) _comb_subset = [ [_full for _full in selected if _full not in item] for item in _subset ] # remove new features from selected features _objective_list = [] if self.model == "Linear": from sklearn.linear_model import LinearRegression _model = LinearRegression() elif self.model == "Lasso": from sklearn.linear_model import Lasso _model = Lasso() elif self.model == "Ridge": from sklearn.linear_model import Ridge _model = Ridge() else: raise ValueError("Not recognizing model!") if self.objective == "MSE": from sklearn.metrics import mean_squared_error _obj = mean_squared_error elif self.objective == "MAE": from sklearn.metrics import mean_absolute_error _obj = mean_absolute_error for _set in _comb_subset: _model.fit(X[_set], y) _predict = _model.predict(X[_set]) _objective_list.append( 1 / _obj(y, _predict) ) # the goal is to maximize the objective function return ( _subset[maxloc(_objective_list)], _objective_list[maxloc(_objective_list)], ) def fit(self, X, y): n, p = X.shape features = list(X.columns) if self.n_components == None: _n_components = min(max(20, p), int(0.5 * p)) else: _n_components = self.n_components if self.b == None: _b = min(5, int(0.05 * p)) _k = 0 self.J_max = [ 0 for _ in range(p + 1) ] # mark the most significant objective function value self._subset_max = [ [] for _ in range(p + 1) ] # mark the best performing subset features _unselected = features.copy() _selected = ( [] ) # selected feature stored here, not selected will be stored in features while True: # Forward Phase _r = self.generalization_limit(_k, _n_components, _b) _o = 1 while ( _o <= _r and len(_unselected) >= 1 ): # not reasonable to add feature when all selected _new_feature, _max_obj = self._Forward_Objective( _selected, _unselected, _o, X, y ) if _max_obj > self.J_max[_k + _o]: self.J_max[_k + _o] = _max_obj.copy() _k += _o for ( _f ) in ( _new_feature ): # add new features and remove these features from the pool _selected.append(_f) for _f in _new_feature: _unselected.remove(_f) self._subset_max[_k] = _selected.copy() break else: if _o < _r: _o += 1 else: _k += 1 # the marked in J_max and _subset_max are considered as best for _k features _selected = self._subset_max[ _k ].copy() # read stored best subset _unselected = features.copy() for _f in _selected: _unselected.remove(_f) break # Termination Condition if _k >= _n_components + self.Delta: break # Backward Phase _r = self.generalization_limit(_k, _n_components, _b) _o = 1 while ( _o <= _r and _o < _k ): # not reasonable to remove when only _o feature selected _new_feature, _max_obj = self._Backward_Objective(_selected, _o, X, y) if _max_obj > self.J_max[_k - _o]: self.J_max[_k - _o] = _max_obj.copy() _k -= _o for ( _f ) in ( _new_feature ): # add new features and remove these features from the pool _unselected.append(_f) for _f in _new_feature: _selected.remove(_f) self._subset_max[_k] = _selected.copy() _o = 1 # return to the start of backward phase, make sure the best subset is selected else: if _o < _r: _o += 1 else: break self.selected_ = _selected self._fitted = True return self def transform(self, X): return X.loc[:, self.selected_] # Genetic Algorithm (GA) class GeneticAlgorithm: """ Use Genetic Algorithm (GA) to select best subset features [1] Procedure: (1) Train a feature pool where every individual is trained on predefined methods, result is pool of binary lists where 1 for feature selected, 0 for not selected (2) Use Genetic Algorithm to generate a new selection binary list (a) Selection: Roulette wheel selection, use fitness function to randomly select one individual (b) Crossover: Single-point Crossover operator, create child selection list from parents list (c) Mutation: Mutate the selection of n bits by certain percentage [1] <NAME>., <NAME>., <NAME>. and <NAME>., 2008. A genetic algorithm-based method for feature subset selection. Soft Computing, 12(2), pp.111-120. Parameters ---------- n_components: Number of features to retain, default = 20 n_prop: float, default = None proprotion of features to select, if None, no limit n_components have higher priority than n_prop n_generations: Number of looping generation for GA, default = 10 feature_selection: Feature selection methods to generate a pool of selections, default = 'auto' support ('auto', 'random', 'Entropy', 't_statistics', 'SVM_RFE') n_initial: Number of random feature selection rules to initialize, default = 10 fitness_func: Fitness function, default None deafult will set as w * Accuracy + (1 - w) / regularization, all functions must be maximization optimization fitness_fit: Model to fit selection and calculate accuracy for fitness, default = 'SVM' support ('Linear', 'Logistic', 'Random Forest', 'SVM') fitness_weight: Default fitness function weight for accuracy, default = 0.9 n_pair: Number of pairs of new selection rules to generate, default = 5 ga_selection: How to perform selection in GA, default = 'Roulette Wheel' support ('Roulette Wheel', 'Rank', 'Steady State', 'Tournament', 'Elitism', 'Boltzmann') p_crossover: Probability to perform crossover, default = 1 ga_crossover: How to perform crossover in GA, default = 'Single-point' support ('Single-point', 'Two-point', 'Uniform') crossover_n: Place of crossover points to perform, default = None deafult will set to p / 4 for single-point crossover p_mutation: Probability to perform mutation (flip bit in selection list), default = 0.001 mutation_n: Number of mutation points to perform, default = None default will set to p / 10 seed = 1 """ def __init__( self, n_components=None, n_prop=None, n_generations=10, feature_selection="random", n_initial=10, fitness_func=None, fitness_fit="SVM", fitness_weight=0.9, n_pair=5, ga_selection="Roulette Wheel", p_crossover=1, ga_crossover="Single-point", crossover_n=None, p_mutation=0.001, mutation_n=None, seed=1, ): self.n_components = n_components self.n_prop = n_prop self.n_generations = n_generations self.feature_selection = feature_selection self.n_initial = n_initial self.fitness_func = fitness_func self.fitness_fit = fitness_fit self.fitness_weight = fitness_weight self.n_pair = n_pair self.ga_selection = ga_selection self.p_crossover = p_crossover self.ga_crossover = ga_crossover self.crossover_n = crossover_n self.p_mutation = p_mutation self.mutation_n = mutation_n self.seed = seed self._auto_sel = { "Entropy": self._entropy, "t_statistics": self._t_statistics, "SVM_RFE": self._SVM_RFE, } self._fitted = False def _random(self, X, y, n): # randomly select n features from X _, p = X.shape if n > p: raise ValueError( "Selected features can not be larger than dataset limit {}, get {}.".format( p, n ) ) _index = random_index(n, p) _selected = [0 for _ in range(p)] # default all as 0 for i in range(n): # select n_components as selected _selected[_index[i]] = 1 return _selected def _entropy(self, X, y, n): # call Mutual Information from FeatureFilter _score = MI(X, y) # select highest scored features _score_sort = np.flip(np.argsort(_score)) _selected = [0 for _ in range(len(_score_sort))] # default all as 0 for i in range(n): # select n_components as selected _selected[_score_sort[i]] = 1 return _selected def _t_statistics(self, X, y, n): # for 2 group dataset, use t-statistics; otherwise, use ANOVA if len(np.unique(y)) == 2: _score = t_score(X, y) elif len(np.unique(y)) > 2: _score = ANOVA(X, y) else: raise ValueError("Only support for more than 2 groups, get only 1 group!") # select lowest scored features _score_sort = np.argsort(_score) _selected = [0 for _ in range(len(_score_sort))] # default all as 0 for i in range(n): # select n_components as selected _selected[_score_sort[i]] = 1 return _selected def _SVM_RFE(self, X, y, n): from sklearn.feature_selection import RFE from sklearn.svm import SVC # using sklearn RFE to recursively remove one feature using SVR, until n_components left _estimator = SVC(kernel="linear") _selector = RFE(_estimator, n_features_to_select=n, step=1) _selector = _selector.fit(X.values, y.values.ravel()) _selected = ( _selector.support_.tolist() ) # retunr the mask list of feature selection _selected = [int(item) for item in _selected] return _selected def _cal_fitness(self, X, y, selection): from sklearn.metrics import mean_squared_error if not self.fitness_func: # fit selected features and calcualte accuracy score if self.fitness_fit == "Linear": from sklearn.linear_model import LinearRegression model = LinearRegression() elif self.fitness_fit == "Logistic": from sklearn.linear_model import LogisticRegression model = LogisticRegression() elif self.fitness_fit == "Random Forest": from sklearn.ensemble import RandomForestRegressor model = RandomForestRegressor() elif self.fitness_fit == "SVM": # select by y using SVC and SVR if len(pd.unique(y.values.ravel())) <= 30: from sklearn.svm import SVC model = SVC() else: from sklearn.svm import SVR model = SVR() else: raise ValueError( 'Only support ["Linear", "Logistic", "Random Forest", "SVM"], get {}'.format( self.fitness_fit ) ) # if none of the features are selected, use mean as prediction if (np.array(selection) == 0).all(): y_pred = [np.mean(y) for _ in range(len(y))] # otherwise, use selected features to fit a model and predict else: model.fit(X.iloc[:, True_index(selection)].values, y.values.ravel()) y_pred = model.predict(X.iloc[:, True_index(selection)]) _accuracy_score = mean_squared_error(y, y_pred) return self.fitness_weight * _accuracy_score + ( 1 - self.fitness_weight ) / sum(selection) else: return self.fitness_func(X, y, selection) def _GeneticAlgorithm(self, X, y, selection_pool): n, p = X.shape # calculate the fitness of all feature selection in the pool try: # self._fitness from None value to np.array, type change _fitness_empty = not self._fitness except ValueError: _fitness_empty = not self._fitness.any() if ( _fitness_empty ): # first round of calculating fitness for all feature selections self._fitness = [] for _seletion in selection_pool: self._fitness.append(self._cal_fitness(X, y, _seletion)) # normalize the fitness self._fitness = np.array(self._fitness) self._sum_fitness = sum(self._fitness) self._fitness /= self._sum_fitness else: self._fitness *= self._sum_fitness for i in range(2 * self.n_pair): self._fitness = np.append( self._fitness, self._cal_fitness(X, y, selection_pool[-(i + 1)]) ) # only need to calculate the newly added ones self._sum_fitness += self._fitness[-1] # normalize the fitness self._fitness /= self._sum_fitness # Selection if self.ga_selection == "Roulette Wheel": # select two individuals from selection pool based on probability (self._fitness) # insert into selection_pool (last two), will be the placeholder for offsprings for _ in range(2 * self.n_pair): selection_pool.append( selection_pool[ np.random.choice(len(self._fitness), 1, p=self._fitness)[0] ] ) # Crossover, generate offsprings if ( np.random.rand() < self.p_crossover ): # only certain probability of executing crossover if self.ga_crossover == "Single-point": if not self.crossover_n: self.crossover_n = int( p / 4 ) # default crossover point is first quarter point else: if self.crossover_n > p: raise ValueError( "Place of cross points must be smaller than p = {}, get {}.".format( p, self.crossover_n ) ) self.crossover_n == int(self.crossover_n) for i in range(self.n_pair): _tmp1 = selection_pool[-(2 * i + 2)] _tmp2 = selection_pool[-(2 * i + 1)] selection_pool[-(2 * i + 2)] = ( _tmp2[: self.crossover_n] + _tmp1[self.crossover_n :] ) # exchange first crossover_n bits from parents selection_pool[-(2 * i + 1)] = ( _tmp1[: self.crossover_n] + _tmp2[self.crossover_n :] ) # Mutation for i in range(2 * self.n_pair): # for two offsprings if ( np.random.rand() < self.p_mutation ): # only certain probability of executing mutation if not self.mutation_n: self.mutation_n = int( p / 10 ) # default number of mutation point is first quarter point else: if self.mutation_n > p: raise ValueError( "Number of mutation points must be smaller than p = {}, get {}.".format( p, self.mutation_n ) ) self.mutation_n == int(self.mutation_n) _mutation_index = random_index( self.mutation_n, p, seed=None ) # randomly select mutation points selection_pool[-(i + 1)] = [ selection_pool[-(i + 1)][j] if j not in _mutation_index else 1 - selection_pool[-(i + 1)][j] for j in range(p) ] # flip mutation points (0 to 1, 1 to 0) return selection_pool def _early_stopping( self, ): # only the difference between the best 10 selection rules are smaller than 0.001 will early stop if len(self._fitness) < 10: return False else: _performance_order = np.flip( np.argsort(self._fitness) ) # select performance from highest to lowest if ( self._fitness[_performance_order[0]] - self._fitness[_performance_order[9]] < 0.001 ): return True else: return False def fit(self, X, y): np.random.seed(self.seed) # set random seed n, p = X.shape # check whether n_components/n_prop is valid if self.n_components is None and self.n_prop is None: self.n_components = X.shape[1] elif self.n_components is not None: self.n_components = min(self.n_components, p) # make sure selected features is at least 1 elif self.n_prop is not None: self.n_components = max(1, int(self.n_prop * p)) if self.n_components == p: warnings.warn("All features selected, no selection performed!") self.selection_ = [1 for _ in range(self.n_components)] return self self.n_generations = int(self.n_generations) # both probability of crossover and mutation must within range [0, 1] self.p_crossover = float(self.p_crossover) if self.p_crossover > 1 or self.p_crossover < 0: raise ValueError( "Probability of crossover must in [0, 1], get {}.".format( self.p_crossover ) ) self.p_mutation = float(self.p_mutation) if self.p_mutation > 1 or self.p_mutation < 0: raise ValueError( "Probability of mutation must in [0, 1], get {}.".format( self.p_mutation ) ) # select feature selection methods # if auto, all default methods will be used; if not, use predefined one if self.feature_selection == "auto": self._feature_sel_methods = self._auto_sel elif self.feature_selection == "random": self.n_initial = int(self.n_initial) self._feature_sel_methods = {} for i in range( self.n_initial ): # get n_initial random feature selection rule self._feature_sel_methods["random_" + str(i + 1)] = self._random else: self.feature_selection = ( [self.feature_selection] if not isinstance(self.feature_selection, list) else self.feature_selection ) self._feature_sel_methods = {} # check if all methods are available for _method in self.feature_selection: if _method not in [*self._auto_sel]: raise ValueError( "Not recognizing feature selection methods, only support {}, get {}.".format( [*self._auto_sel], _method ) ) self._feature_sel_methods[_method] = self._auto_sel[_method] self._fit(X, y) self._fitted = True return self def _fit(self, X, y): # generate the feature selection pool using _sel_methods = [*self._feature_sel_methods] _sel_pool = [] # store all selection rules self._fitness = None # store the fitness of every individual # keep diversity for the pool, selection rule can have different number of features retained _iter = max(1, int(np.log2(self.n_components))) for i in range(_iter): n = 2 ** (i + 1) for _method in _sel_methods: _sel_pool.append(self._feature_sel_methods[_method](X, y, n)) # loop through generations to run Genetic algorithm and Induction algorithm for _ in range(self.n_generations): _sel_pool = self._GeneticAlgorithm(X, y, _sel_pool) if self._early_stopping(): break self.selection_ = _sel_pool[ np.flip(np.argsort(self._fitness))[0] ] # selected features, {1, 0} list return self def transform(self, X): # check for all/no feature removed cases if self.selection_.count(self.selection_[0]) == len(self.selection_): if self.selection_[0] == 0: warnings.warn("All features removed.") elif self.selection_[1] == 1: warnings.warn("No feature removed.") else: raise ValueError("Not recognizing the selection list!") return X.iloc[:, True_index(self.selection_)] # CHCGA # Exhaustive search is practically impossible to implement in a reasonable time, # so it's not included in the package, but it can be used. # class ExhaustiveFS: # """ # Exhaustive Feature Selection # Parameters # ---------- # estimator: str or sklearn estimator, default = "Lasso" # estimator must have fit/predict methods # criteria: str or sklearn metric, default = "accuracy" # """ # def __init__( # self, # estimator="Lasso", # criteria="neg_accuracy", # ): # self.estimator = estimator # self.criteria = criteria # self._fitted = False # def fit(self, X, y): # # make sure estimator is recognized # if self.estimator == "Lasso": # from sklearn.linear_model import Lasso # self.estimator = Lasso() # elif self.estimator == "Ridge": # from sklearn.linear_model import Ridge # self.estimator = Ridge() # elif isclass(type(self.estimator)): # # if estimator is recognized as a class # # make sure it has fit/predict methods # if not has_method(self.estimator, "fit") or not has_method( # self.estimator, "predict" # ): # raise ValueError("Estimator must have fit/predict methods!") # else: # raise AttributeError("Unrecognized estimator!") # # check whether criteria is valid # if self.criteria == "neg_accuracy": # from My_AutoML._utils._stat import neg_accuracy # self.criteria = neg_accuracy # elif self.criteria == "MSE": # from sklearn.metrics import mean_squared_error # self.criteria = mean_squared_error # elif isinstance(self.criteria, Callable): # # if callable, pass # pass # else: # raise ValueError("Unrecognized criteria!") # # get all combinations of features # all_comb = [] # for i in range(1, X.shape[1] + 1): # for item in list(combinations(list(range(X.shape[1])), i)): # all_comb.append(list(item)) # all_comb = np.array(all_comb).flatten() # flatten 2D to 1D # # initialize results # results = [] # for comb in all_comb: # self.estimator.fit(X.iloc[:, comb], y) # results.append(self.criteria(y, self.estimator.predict(X.iloc[:, comb]))) # self.selected_features = all_comb[np.argmin(results)] # self._fitted = True # return self # def transform(self, X): # return X[:, self.selected_features] class SFS: """ Use Sequential Forward Selection/SFS to select subset of features. Parameters ---------- estimators: str or estimator, default = "Lasso" string for some pre-defined estimator, or a estimator contains fit/predict methods n_components: int, default = None limit maximum number of features to select, if None, no limit n_prop: float, default = None proprotion of features to select, if None, no limit n_components have higher priority than n_prop criteria: str, default = "accuracy" criteria used to select features, can be "accuracy" """ def __init__( self, estimator="Lasso", n_components=None, n_prop=None, criteria="neg_accuracy", ): self.estimator = estimator self.n_components = n_components self.n_prop = n_prop self.criteria = criteria self._fitted = False def select_feature(self, X, y, estimator, selected_features, unselected_features): # select one feature as step, get all possible combinations test_item = list(combinations(unselected_features, 1)) # concat new test_comb with selected_features test_comb = [list(item) + selected_features for item in test_item] # initialize test results results = [] for _comb in test_comb: # fit estimator estimator.fit(X.iloc[:, _comb], y) # get test results test_results = self.criteria(y, estimator.predict(X.iloc[:, _comb])) # append test results results.append(test_results) return ( results[minloc(results)], test_item[minloc(results)][0], ) # use 0 to select item instead of tuple def fit(self, X, y=None): # check whether y is empty # for SFS, y is required to train a model if isinstance(y, pd.DataFrame): _empty = y.isnull().all().all() elif isinstance(y, pd.Series): _empty = y.isnull().all() elif isinstance(y, np.ndarray): _empty = np.all(np.isnan(y)) else: _empty = y == None # if empty, raise error if _empty: raise ValueError("Must have response!") # make sure estimator is recognized estimator = get_estimator(self.estimator) # check whether n_components/n_prop is valid if self.n_components is None and self.n_prop is None: self.n_components = X.shape[1] elif self.n_components is not None: self.n_components = min(self.n_components, X.shape[1]) # make sure selected features is at least 1 elif self.n_prop is not None: self.n_components = max(1, int(self.n_prop * X.shape[1])) # check whether criteria is valid self.criteria = get_metrics(self.criteria) # initialize selected/unselected features selected_features = [] optimal_loss = np.inf unselected_features = list(range(X.shape[1])) # iterate until n_components are selected for _ in range(self.n_components): # get the current optimal loss and feature loss, new_feature = self.select_feature( X, y, estimator, selected_features, unselected_features ) if loss > optimal_loss: # if no better combination is found, stop break else: optimal_loss = loss selected_features.append(new_feature) unselected_features.remove(new_feature) # record selected features self.selected_features = selected_features self._fitted = True return self def transform(self, X): return X.iloc[:, self.selected_features] class mRMR: """ mRMR [1] minimal-redundancy-maximal-relevance as criteria for filter-based feature selection [1] <NAME>., <NAME>., & <NAME>. (2005). Feature selection based on mutual information criteria of max-dependency, max-relevance, and min-redundancy. IEEE Transactions on pattern analysis and machine intelligence, 27(8), 1226-1238. Parameters ---------- n_components: int, default = None number of components to select, if None, no limit n_prop: float, default = None proprotion of features to select, if None, no limit n_components have higher priority than n_prop """ def __init__( self, n_components=None, n_prop=None, ): self.n_components = n_components self.n_prop = n_prop self._fitted = False def select_feature(self, X, y, selected_features, unselected_features): # select one feature as step, get all possible combinations test_item = list(combinations(unselected_features, 1)) # initialize test results results = [] for _comb in test_item: dependency = MI(X.iloc[:, _comb[0]], y) if len(selected_features) > 0: redundancy = np.mean( [ MI(X.iloc[:, item], X.iloc[:, _comb[0]]) for item in selected_features ] ) # append test results results.append(dependency - redundancy) # at initial, no selected feature, so no redundancy else: results.append(dependency) return test_item[maxloc(results)][0] # use 0 to select item instead of tuple def fit(self, X, y=None): # check whether n_components/n_prop is valid if self.n_components is None and self.n_prop is None: self.n_components = X.shape[1] elif self.n_components is not None: self.n_components = min(self.n_components, X.shape[1]) # make sure selected features is at least 1 elif self.n_prop is not None: self.n_components = max(1, int(self.n_prop * X.shape[1])) # initialize selected/unselected features selected_features = [] unselected_features = list(range(X.shape[1])) for _ in range(self.n_components): # get the current optimal loss and feature new_feature = self.select_feature( X, y, selected_features, unselected_features ) selected_features.append(new_feature) unselected_features.remove(new_feature) # record selected features self.select_features = selected_features self._fitted = True return self def transform(self, X): return X.iloc[:, self.select_features] class CBFS: """ CBFS Copula-based Feature Selection [1] [1] <NAME>., <NAME>., <NAME>., <NAME>., & <NAME>. (2021). Stable feature selection using copula based mutual information. Pattern Recognition, 112, 107697. Parameters ---------- copula: str, default = "empirical" what type of copula to use for feature selection n_components: int, default = None number of components to select, if None, no limit n_prop: float, default = None proprotion of features to select, if None, no limit n_components have higher priority than n_prop """ def __init__( self, copula="empirical", n_components=None, n_prop=None, ): self.copula = copula self.n_components = n_components self.n_prop = n_prop self._fitted = False def Empirical_Copula(self, data): # make sure it's a dataframe if not isinstance(data, pd.DataFrame): try: data = pd.DataFrame(data) except: raise ValueError( "data must be a pandas DataFrame or convertable to one!" ) p = [] for idx in data.index: p.append((data <= data.iloc[idx, :]).all(axis=1).sum() / data.shape[0]) return p def select_feature(self, X, y, selected_features, unselected_features): # select one feature as step, get all possible combinations test_item = list(combinations(unselected_features, 1)) # concat new test_comb with selected_features test_comb = [list(item) + selected_features for item in test_item] # initialize test results results = [] for col, comb in zip(test_item, test_comb): # at initial, no selected feature, so no redundancy if len(selected_features) == 0: if self.copula == "empirical": p_dependent = self.Empirical_Copula( pd.concat([X.iloc[:, col[0]], y], axis=1) ) # calculate dependency based on empirical copula entropy_dependent = np.sum( [-item * np.log2(item) for item in Counter(p_dependent).values()] ) # append test results results.append(entropy_dependent) else: if self.copula == "empirical": p_dependent = self.Empirical_Copula( pd.concat([X.iloc[:, col[0]], y], axis=1) ) p_redundant = self.Empirical_Copula(X.iloc[:, comb]) # calculate dependency based on empirical copula entropy_dependent = np.sum( [-item * np.log2(item) for item in Counter(p_dependent).values()] ) # calculate redundancy based on empirical copula entropy_redundant = np.sum( [-item * np.log2(item) for item in Counter(p_redundant).values()] ) # append test results results.append(entropy_dependent - entropy_redundant) return ( results[maxloc(results)], test_item[maxloc(results)][0], ) # use 0 to select item instead of tuple def fit(self, X, y=None): # check whether n_components/n_prop is valid if self.n_components is None and self.n_prop is None: self.n_components = X.shape[1] elif self.n_components is not None: self.n_components = min(self.n_components, X.shape[1]) elif self.n_prop is not None: self.n_components = max(1, int(self.n_prop * X.shape[1])) # initialize selected/unselected features selected_features = [] optimal_loss = -np.inf unselected_features = list(range(X.shape[1])) # iterate until n_components are selected for _ in range(self.n_components): # get the current optimal loss and feature loss, new_feature = self.select_feature( X, y, selected_features, unselected_features ) if loss < optimal_loss: # if no better combination is found, stop break else: optimal_loss = loss selected_features.append(new_feature) unselected_features.remove(new_feature) # record selected features self.selected_features = selected_features self._fitted = True return self def transform(self, X): return X.iloc[:, self.selected_features]
[ "numpy.random.seed", "numpy.abs", "sklearn.feature_selection.RFE", "My_AutoML._utils.t_score", "numpy.isnan", "numpy.argsort", "numpy.mean", "sklearn.svm.SVC", "My_AutoML._utils._optimize.get_metrics", "numpy.unique", "My_AutoML._utils.minloc", "pandas.DataFrame", "My_AutoML._utils.Pearson_C...
[((16755, 16773), 'My_AutoML._utils.random_index', 'random_index', (['n', 'p'], {}), '(n, p)\n', (16767, 16773), False, 'from My_AutoML._utils import minloc, maxloc, True_index, Pearson_Corr, MI, t_score, ANOVA, random_index\n'), ((17067, 17075), 'My_AutoML._utils.MI', 'MI', (['X', 'y'], {}), '(X, y)\n', (17069, 17075), False, 'from My_AutoML._utils import minloc, maxloc, True_index, Pearson_Corr, MI, t_score, ANOVA, random_index\n'), ((17789, 17807), 'numpy.argsort', 'np.argsort', (['_score'], {}), '(_score)\n', (17799, 17807), True, 'import numpy as np\n'), ((18256, 18276), 'sklearn.svm.SVC', 'SVC', ([], {'kernel': '"""linear"""'}), "(kernel='linear')\n", (18259, 18276), False, 'from sklearn.svm import SVC\n'), ((18297, 18344), 'sklearn.feature_selection.RFE', 'RFE', (['_estimator'], {'n_features_to_select': 'n', 'step': '(1)'}), '(_estimator, n_features_to_select=n, step=1)\n', (18300, 18344), False, 'from sklearn.feature_selection import RFE\n'), ((25472, 25497), 'numpy.random.seed', 'np.random.seed', (['self.seed'], {}), '(self.seed)\n', (25486, 25497), True, 'import numpy as np\n'), ((34755, 34784), 'My_AutoML._utils._optimize.get_estimator', 'get_estimator', (['self.estimator'], {}), '(self.estimator)\n', (34768, 34784), False, 'from My_AutoML._utils._optimize import get_estimator, get_metrics\n'), ((35282, 35308), 'My_AutoML._utils._optimize.get_metrics', 'get_metrics', (['self.criteria'], {}), '(self.criteria)\n', (35293, 35308), False, 'from My_AutoML._utils._optimize import get_estimator, get_metrics\n'), ((3261, 3279), 'My_AutoML._utils.Pearson_Corr', 'Pearson_Corr', (['X', 'y'], {}), '(X, y)\n', (3273, 3279), False, 'from My_AutoML._utils import minloc, maxloc, True_index, Pearson_Corr, MI, t_score, ANOVA, random_index\n'), ((3880, 3903), 'numpy.argsort', 'np.argsort', (['self._score'], {}), '(self._score)\n', (3890, 3903), True, 'import numpy as np\n'), ((5998, 6011), 'numpy.abs', 'np.abs', (['(k - d)'], {}), '(k - d)\n', (6004, 6011), True, 'import numpy as np\n'), ((6276, 6313), 'itertools.combinations', 'itertools.combinations', (['unselected', 'o'], {}), '(unselected, o)\n', (6298, 6313), False, 'import itertools\n'), ((6599, 6617), 'sklearn.linear_model.LinearRegression', 'LinearRegression', ([], {}), '()\n', (6615, 6617), False, 'from sklearn.linear_model import LinearRegression\n'), ((7656, 7691), 'itertools.combinations', 'itertools.combinations', (['selected', 'o'], {}), '(selected, o)\n', (7678, 7691), False, 'import itertools\n'), ((8006, 8024), 'sklearn.linear_model.LinearRegression', 'LinearRegression', ([], {}), '()\n', (8022, 8024), False, 'from sklearn.linear_model import LinearRegression\n'), ((17148, 17166), 'numpy.argsort', 'np.argsort', (['_score'], {}), '(_score)\n', (17158, 17166), True, 'import numpy as np\n'), ((17542, 17555), 'My_AutoML._utils.t_score', 't_score', (['X', 'y'], {}), '(X, y)\n', (17549, 17555), False, 'from My_AutoML._utils import minloc, maxloc, True_index, Pearson_Corr, MI, t_score, ANOVA, random_index\n'), ((20305, 20334), 'sklearn.metrics.mean_squared_error', 'mean_squared_error', (['y', 'y_pred'], {}), '(y, y_pred)\n', (20323, 20334), False, 'from sklearn.metrics import mean_squared_error\n'), ((21215, 21238), 'numpy.array', 'np.array', (['self._fitness'], {}), '(self._fitness)\n', (21223, 21238), True, 'import numpy as np\n'), ((22342, 22358), 'numpy.random.rand', 'np.random.rand', ([], {}), '()\n', (22356, 22358), True, 'import numpy as np\n'), ((25999, 26062), 'warnings.warn', 'warnings.warn', (['"""All features selected, no selection performed!"""'], {}), "('All features selected, no selection performed!')\n", (26012, 26062), False, 'import warnings\n'), ((33515, 33551), 'itertools.combinations', 'combinations', (['unselected_features', '(1)'], {}), '(unselected_features, 1)\n', (33527, 33551), False, 'from itertools import combinations\n'), ((37243, 37279), 'itertools.combinations', 'combinations', (['unselected_features', '(1)'], {}), '(unselected_features, 1)\n', (37255, 37279), False, 'from itertools import combinations\n'), ((37394, 37420), 'My_AutoML._utils.MI', 'MI', (['X.iloc[:, _comb[0]]', 'y'], {}), '(X.iloc[:, _comb[0]], y)\n', (37396, 37420), False, 'from My_AutoML._utils import minloc, maxloc, True_index, Pearson_Corr, MI, t_score, ANOVA, random_index\n'), ((40619, 40655), 'itertools.combinations', 'combinations', (['unselected_features', '(1)'], {}), '(unselected_features, 1)\n', (40631, 40655), False, 'from itertools import combinations\n'), ((3342, 3350), 'My_AutoML._utils.MI', 'MI', (['X', 'y'], {}), '(X, y)\n', (3344, 3350), False, 'from My_AutoML._utils import minloc, maxloc, True_index, Pearson_Corr, MI, t_score, ANOVA, random_index\n'), ((6057, 6070), 'numpy.abs', 'np.abs', (['(k - d)'], {}), '(k - d)\n', (6063, 6070), True, 'import numpy as np\n'), ((6727, 6734), 'sklearn.linear_model.Lasso', 'Lasso', ([], {}), '()\n', (6732, 6734), False, 'from sklearn.linear_model import Lasso\n'), ((7487, 7510), 'My_AutoML._utils.maxloc', 'maxloc', (['_objective_list'], {}), '(_objective_list)\n', (7493, 7510), False, 'from My_AutoML._utils import minloc, maxloc, True_index, Pearson_Corr, MI, t_score, ANOVA, random_index\n'), ((7541, 7564), 'My_AutoML._utils.maxloc', 'maxloc', (['_objective_list'], {}), '(_objective_list)\n', (7547, 7564), False, 'from My_AutoML._utils import minloc, maxloc, True_index, Pearson_Corr, MI, t_score, ANOVA, random_index\n'), ((8134, 8141), 'sklearn.linear_model.Lasso', 'Lasso', ([], {}), '()\n', (8139, 8141), False, 'from sklearn.linear_model import Lasso\n'), ((8894, 8917), 'My_AutoML._utils.maxloc', 'maxloc', (['_objective_list'], {}), '(_objective_list)\n', (8900, 8917), False, 'from My_AutoML._utils import minloc, maxloc, True_index, Pearson_Corr, MI, t_score, ANOVA, random_index\n'), ((8948, 8971), 'My_AutoML._utils.maxloc', 'maxloc', (['_objective_list'], {}), '(_objective_list)\n', (8954, 8971), False, 'from My_AutoML._utils import minloc, maxloc, True_index, Pearson_Corr, MI, t_score, ANOVA, random_index\n'), ((17501, 17513), 'numpy.unique', 'np.unique', (['y'], {}), '(y)\n', (17510, 17513), True, 'import numpy as np\n'), ((17613, 17624), 'My_AutoML._utils.ANOVA', 'ANOVA', (['X', 'y'], {}), '(X, y)\n', (17618, 17624), False, 'from My_AutoML._utils import minloc, maxloc, True_index, Pearson_Corr, MI, t_score, ANOVA, random_index\n'), ((18932, 18950), 'sklearn.linear_model.LinearRegression', 'LinearRegression', ([], {}), '()\n', (18948, 18950), False, 'from sklearn.linear_model import LinearRegression\n'), ((23685, 23701), 'numpy.random.rand', 'np.random.rand', ([], {}), '()\n', (23699, 23701), True, 'import numpy as np\n'), ((24391, 24434), 'My_AutoML._utils.random_index', 'random_index', (['self.mutation_n', 'p'], {'seed': 'None'}), '(self.mutation_n, p, seed=None)\n', (24403, 24434), False, 'from My_AutoML._utils import minloc, maxloc, True_index, Pearson_Corr, MI, t_score, ANOVA, random_index\n'), ((25113, 25138), 'numpy.argsort', 'np.argsort', (['self._fitness'], {}), '(self._fitness)\n', (25123, 25138), True, 'import numpy as np\n'), ((28605, 28631), 'numpy.log2', 'np.log2', (['self.n_components'], {}), '(self.n_components)\n', (28612, 28631), True, 'import numpy as np\n'), ((29434, 29472), 'warnings.warn', 'warnings.warn', (['"""All features removed."""'], {}), "('All features removed.')\n", (29447, 29472), False, 'import warnings\n'), ((29684, 29711), 'My_AutoML._utils.True_index', 'True_index', (['self.selection_'], {}), '(self.selection_)\n', (29694, 29711), False, 'from My_AutoML._utils import minloc, maxloc, True_index, Pearson_Corr, MI, t_score, ANOVA, random_index\n'), ((34070, 34085), 'My_AutoML._utils.minloc', 'minloc', (['results'], {}), '(results)\n', (34076, 34085), False, 'from My_AutoML._utils import minloc, maxloc, True_index, Pearson_Corr, MI, t_score, ANOVA, random_index\n'), ((37928, 37943), 'My_AutoML._utils.maxloc', 'maxloc', (['results'], {}), '(results)\n', (37934, 37943), False, 'from My_AutoML._utils import minloc, maxloc, True_index, Pearson_Corr, MI, t_score, ANOVA, random_index\n'), ((40131, 40149), 'pandas.DataFrame', 'pd.DataFrame', (['data'], {}), '(data)\n', (40143, 40149), True, 'import pandas as pd\n'), ((42351, 42366), 'My_AutoML._utils.maxloc', 'maxloc', (['results'], {}), '(results)\n', (42357, 42366), False, 'from My_AutoML._utils import minloc, maxloc, True_index, Pearson_Corr, MI, t_score, ANOVA, random_index\n'), ((6122, 6135), 'numpy.abs', 'np.abs', (['(k - d)'], {}), '(k - d)\n', (6128, 6135), True, 'import numpy as np\n'), ((6844, 6851), 'sklearn.linear_model.Ridge', 'Ridge', ([], {}), '()\n', (6849, 6851), False, 'from sklearn.linear_model import Ridge\n'), ((8251, 8258), 'sklearn.linear_model.Ridge', 'Ridge', ([], {}), '()\n', (8256, 8258), False, 'from sklearn.linear_model import Ridge\n'), ((17573, 17585), 'numpy.unique', 'np.unique', (['y'], {}), '(y)\n', (17582, 17585), True, 'import numpy as np\n'), ((19093, 19113), 'sklearn.linear_model.LogisticRegression', 'LogisticRegression', ([], {}), '()\n', (19111, 19113), False, 'from sklearn.linear_model import LogisticRegression\n'), ((19990, 20000), 'numpy.mean', 'np.mean', (['y'], {}), '(y)\n', (19997, 20000), True, 'import numpy as np\n'), ((29126, 29151), 'numpy.argsort', 'np.argsort', (['self._fitness'], {}), '(self._fitness)\n', (29136, 29151), True, 'import numpy as np\n'), ((29531, 29567), 'warnings.warn', 'warnings.warn', (['"""No feature removed."""'], {}), "('No feature removed.')\n", (29544, 29567), False, 'import warnings\n'), ((34110, 34125), 'My_AutoML._utils.minloc', 'minloc', (['results'], {}), '(results)\n', (34116, 34125), False, 'from My_AutoML._utils import minloc, maxloc, True_index, Pearson_Corr, MI, t_score, ANOVA, random_index\n'), ((42391, 42406), 'My_AutoML._utils.maxloc', 'maxloc', (['results'], {}), '(results)\n', (42397, 42406), False, 'from My_AutoML._utils import minloc, maxloc, True_index, Pearson_Corr, MI, t_score, ANOVA, random_index\n'), ((3065, 3076), 'numpy.isnan', 'np.isnan', (['y'], {}), '(y)\n', (3073, 3076), True, 'import numpy as np\n'), ((19260, 19283), 'sklearn.ensemble.RandomForestRegressor', 'RandomForestRegressor', ([], {}), '()\n', (19281, 19283), False, 'from sklearn.ensemble import RandomForestRegressor\n'), ((19931, 19950), 'numpy.array', 'np.array', (['selection'], {}), '(selection)\n', (19939, 19950), True, 'import numpy as np\n'), ((34528, 34539), 'numpy.isnan', 'np.isnan', (['y'], {}), '(y)\n', (34536, 34539), True, 'import numpy as np\n'), ((37548, 37588), 'My_AutoML._utils.MI', 'MI', (['X.iloc[:, item]', 'X.iloc[:, _comb[0]]'], {}), '(X.iloc[:, item], X.iloc[:, _comb[0]])\n', (37550, 37588), False, 'from My_AutoML._utils import minloc, maxloc, True_index, Pearson_Corr, MI, t_score, ANOVA, random_index\n'), ((41130, 41171), 'pandas.concat', 'pd.concat', (['[X.iloc[:, col[0]], y]'], {'axis': '(1)'}), '([X.iloc[:, col[0]], y], axis=1)\n', (41139, 41171), True, 'import pandas as pd\n'), ((41641, 41682), 'pandas.concat', 'pd.concat', (['[X.iloc[:, col[0]], y]'], {'axis': '(1)'}), '([X.iloc[:, col[0]], y], axis=1)\n', (41650, 41682), True, 'import pandas as pd\n'), ((20251, 20272), 'My_AutoML._utils.True_index', 'True_index', (['selection'], {}), '(selection)\n', (20261, 20272), False, 'from My_AutoML._utils import minloc, maxloc, True_index, Pearson_Corr, MI, t_score, ANOVA, random_index\n'), ((41332, 41345), 'numpy.log2', 'np.log2', (['item'], {}), '(item)\n', (41339, 41345), True, 'import numpy as np\n'), ((41917, 41930), 'numpy.log2', 'np.log2', (['item'], {}), '(item)\n', (41924, 41930), True, 'import numpy as np\n'), ((42130, 42143), 'numpy.log2', 'np.log2', (['item'], {}), '(item)\n', (42137, 42143), True, 'import numpy as np\n'), ((19497, 19502), 'sklearn.svm.SVC', 'SVC', ([], {}), '()\n', (19500, 19502), False, 'from sklearn.svm import SVC\n'), ((19602, 19607), 'sklearn.svm.SVR', 'SVR', ([], {}), '()\n', (19605, 19607), False, 'from sklearn.svm import SVR\n'), ((20153, 20174), 'My_AutoML._utils.True_index', 'True_index', (['selection'], {}), '(selection)\n', (20163, 20174), False, 'from My_AutoML._utils import minloc, maxloc, True_index, Pearson_Corr, MI, t_score, ANOVA, random_index\n'), ((41358, 41378), 'collections.Counter', 'Counter', (['p_dependent'], {}), '(p_dependent)\n', (41365, 41378), False, 'from collections import Counter\n'), ((41943, 41963), 'collections.Counter', 'Counter', (['p_dependent'], {}), '(p_dependent)\n', (41950, 41963), False, 'from collections import Counter\n'), ((42156, 42176), 'collections.Counter', 'Counter', (['p_redundant'], {}), '(p_redundant)\n', (42163, 42176), False, 'from collections import Counter\n')]
import copy import numpy as np # There is problem with handling nan and inf values # Ideally, we should use None but it cannot be sent through # the interface. Maybe we should adjust add_values() to handle not passing # the value to all the fields INVALID_PLACEHOLDER = 1e+100 class LoggingManager: def __init__(self, log_to_db, run_id, model, commit_frequency=1000, training_metrics=None, test_metrics=None): self.log_to_db = log_to_db self.run_id = run_id self.model = model self.commit_frequency = commit_frequency self.training_metrics = training_metrics self.test_metrics = test_metrics self.training_log_vec = [] self.test_log_vec = [] def items_to_str(self, vec): ret_vec = [] for v in vec: if type(v) == float and (np.isnan(v) or np.isinf(v)): ret_vec.append(str(INVALID_PLACEHOLDER)) else: ret_vec.append(str(v)) return ret_vec def commit_logs(self): if not self.log_to_db: return try: if self.training_metrics: self.training_metrics.add_values(self.training_log_vec) if self.test_metrics: self.test_metrics.add_values(self.test_log_vec) except: print("Failed commiting logs") self.training_log_vec = [] self.test_log_vec = [] def log_performance_metrics(self, split, epoch, timestep, error, running_error, acc, running_acc): if not self.log_to_db: return if split == 'training' and self.training_metrics is not None: if timestep % 10000 == 0: self.training_log_vec.append(self.items_to_str([self.run_id, epoch, timestep, error, running_error, acc, running_acc])) if split == 'test' and self.test_metrics is not None: self.test_log_vec.append(self.items_to_str([self.run_id, epoch, timestep, error, acc])) if split == 'test' or timestep % self.commit_frequency== 0: self.commit_logs()
[ "numpy.isinf", "numpy.isnan" ]
[((830, 841), 'numpy.isnan', 'np.isnan', (['v'], {}), '(v)\n', (838, 841), True, 'import numpy as np\n'), ((845, 856), 'numpy.isinf', 'np.isinf', (['v'], {}), '(v)\n', (853, 856), True, 'import numpy as np\n')]
import copy import numpy as np from scipy.spatial.distance import cdist import free_energy_clustering.GMM as GMM from sklearn.mixture import GaussianMixture import free_energy_clustering.cross_validation as CV import free_energy_clustering as FEC import matplotlib import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D class FreeEnergyClustering(object): def __init__(self, data, min_n_components=8, max_n_components=None, n_components_step=1, x_lims=None, temperature=300.0, n_grids=50, n_splits=1, shuffle_data=False, n_iterations=1, convergence_tol=1e-4, stack_landscapes=False, verbose=True, test_set_perc=0.0, data_weights=None): """ Class for computing free energy landscape in [kcal/mol]. - observed_data has dimensionality [N x d]. """ self.data_ = data self.shuffle_data = shuffle_data self.n_splits_ = n_splits self.n_iterations_ = n_iterations self.convergence_tol_ = convergence_tol self.stack_landscapes_ = stack_landscapes self.min_n_components = min_n_components self.max_n_components = max_n_components self.n_components_step = n_components_step self.FE_points_ = None self.FE_landscape_ = None self.coords_ = None self.min_FE_ = None self.cl_ = None # Clustering object self.labels_ = None self.core_labels_ = None self.cluster_centers_ = None self.pathways_ = None self.state_populations_ = None if x_lims is not None: self.x_lims_ = x_lims self.n_dims_ = len(self.x_lims_) else: if len(data.shape) > 1: self.x_lims_ = [] for i in range(data.shape[1]): self.x_lims_.append([data[:,i].min(),data[:,i].max()]) self.n_dims_ = len(self.x_lims_) else: self.x_lims_ = [[data.min(),data.max()]] self.n_dims_ = 1 self.temperature_ = temperature # [K] self.boltzmann_constant_ = 0.0019872041 # [kcal/(mol K)] self.density_est_ = None self.standard_error_FE_ = None self.nx_ = n_grids self.n_grids_ = [self.nx_]*self.n_dims_ self.test_set_perc_ = test_set_perc self.verbose_ = verbose self.data_weights_ = data_weights self.BICs_ = [] if data_weights is not None: use_data_weights = True # Convert data weights to the right format self.data_weights_ /= self.data_weights_.sum() self.data_weights_ *= self.data_weights_.shape[0] else: use_data_weights = False self.test_set_loglikelihood = None if verbose: print('*----------------Gaussian mixture model free energy estimator----------------*') print(' n_splits = '+str(n_splits)) print(' shuffle_data = ' + str(shuffle_data)) print(' n_iterations = ' + str(n_iterations)) print(' n_grids = ' + str(n_grids)) print(' covergence_tol = ' + str(convergence_tol)) print(' stack_landscapes = ' + str(stack_landscapes)) print(' x_lims (axes limits) = ' + str(self.x_lims_)) print(' temperature = ' + str(temperature)) print(' min_n_components = ' + str(min_n_components)) print(' max_n_components = ' + str(max_n_components)) print(' n_components_step = ' + str(n_components_step)) print(' Using weighted data: ' + str(use_data_weights)) print('*----------------------------------------------------------------------------*') return def _get_grid_coords(self): if self.n_dims_ < 4: x = [] self.n_grids_ = [] for i_dim in range(self.n_dims_): self.n_grids_.append(self.nx_) x.append(np.linspace(self.x_lims_[i_dim][0], self.x_lims_[i_dim][1], self.nx_)) if self.n_dims_ == 1: return x coords = np.meshgrid(*x) else: # Do not discretize print('Note: # features > 3 => density not evaluated on grid.') coords = None return coords def _density_landscape(self, density_est): """ Evaluate density model at the grid points. """ if self.coords_ is None: coords = self._get_grid_coords() else: coords = self.coords_ if self.n_dims_ == 1: densities = density_est.density(coords[0][:,np.newaxis]) return coords, densities if coords is not None: print('Density grid shape: '+str(self.n_grids_)) grid_points_flatten = [] for x in coords: grid_points_flatten.append(np.ravel(x)) points = np.asarray(grid_points_flatten).T densities = density_est.density(points) densities = np.reshape(densities, self.n_grids_) else: densities = density_est.density(self.data_) return coords, densities def _free_energy(self,density): density[density < 1e-8] = 1e-8 FE = -self.temperature_ * self.boltzmann_constant_ * np.log(density) return FE def standard_error(self, n_data_blocks=3): """ Estimating standard error. """ print('Estimating standard error.') n_points = self.data_.shape[0] n_data_points = int(n_points/n_data_blocks) free_energies = [] for i in range(n_data_blocks): if i != n_data_blocks-1: data = np.copy(self.data_[i*n_data_points:(i+1)*n_data_points]) else: data = np.copy(self.data_[i*n_data_points::]) if self.n_dims_ == 1: data = data[:,np.newaxis] _, density_model = self._fit_FE(data, set_density_model=False) _, density = self._density_landscape(density_model) free_energies.append(self._free_energy(density)) free_energies = np.asarray(free_energies) self.standard_error_FE_ = np.std(free_energies,axis=0)/np.sqrt(n_data_blocks-1) print('Standard error estimation done.') return self.standard_error_FE_ def _train_GMM(self, data, n_components, train_inds=None, val_inds=None, loglikelihood=0): """ Perform one training of GMM. :param data: :param n_components: :return: """ if train_inds is not None and val_inds is not None: training_data, validation_data = CV.get_train_validation_set(data, train_inds, val_inds) else: training_data = np.copy(data) validation_data = np.copy(data) if self.data_weights_ is None: gmm = GaussianMixture(n_components=n_components, tol=self.convergence_tol_) # Train model on the current training data gmm.fit(training_data) # Check log-likelihood of validation data loglikelihood += gmm.score(validation_data) else: gmm = GMM.GaussianMixture(n_components=n_components, convergence_tol=self.convergence_tol_,verbose=self.verbose_) training_data_weights = self.data_weights_ validation_data_weights = self.data_weights_ if train_inds is not None and val_inds is not None: if self.data_weights_ is not None: training_data_weights, validation_data_weights = CV.get_train_validation_set(self.data_weights_, train_inds, val_inds) # Train model on the current training data gmm.fit(training_data, data_weights=training_data_weights) # Check log-likelihood of validation data loglikelihood += gmm.loglikelihood(validation_data, data_weights=validation_data_weights) return gmm, loglikelihood def _fit_FE(self, data, set_density_model=True): """ Fit density to data points. :param data: [n_samples x n_dims] :return: free energy of points """ best_n_components = self.min_n_components # Extract test set from the dataset n_points_test = int(self.test_set_perc_*data.shape[0]) data_orig = np.copy(data) data_weights_orig = np.copy(self.data_weights_) if n_points_test > 0: test_data = data[-n_points_test::,:] data = np.copy(data[0:-n_points_test, :]) if self.data_weights_ is not None: self.data_weights_ = np.copy(self.data_weights_[0:-n_points_test,:]) else: test_data = np.zeros((0,self.n_dims_)) if self.stack_landscapes_: print('Estimating density with stacked GMMs.') else: print('Estimating density with GMM.') if self.data_weights_ is not None: print('Using weighted data to estimate GMM.') best_loglikelihood = -np.inf list_of_GMMs = [] list_of_validation_data = [] ICs = [] # Get indices of training and validation datasets if self.n_splits_ > 1: train_inds, val_inds = CV.split_train_validation(data, self.n_splits_, self.shuffle_data) # Determine number of components with k-fold cross-validation, # or store all estimated densities and then weight together. if self.max_n_components is not None: for n_components in range(self.min_n_components,self.max_n_components+1,self.n_components_step): if self.verbose_: print('# Components = '+str(n_components)) if self.n_splits_ > 1 and not(self.stack_landscapes_): loglikelihood = 0 for i_split in range(self.n_splits_): gmm, loglikelihood = self._train_GMM(data, n_components, train_inds[i_split], val_inds[i_split], loglikelihood) # Keep best model if loglikelihood > best_loglikelihood: best_loglikelihood = loglikelihood best_n_components = n_components else: best_loglikelihood = -np.inf for i_iter in range(self.n_iterations_): # Train GMM gmm, loglikelihood = self._train_GMM(data, n_components) # Compute average AIC/BIC over iterations if i_iter == 0: if self.stack_landscapes_: if self.data_weights_ is None: ICs.append(gmm.aic(data)) else: ICs.append(gmm.aic(data, self.data_weights_)) else: if self.data_weights_ is None: ICs.append(gmm.bic(data)) else: ICs.append(gmm.bic(data, self.data_weights_)) # Keep best model if loglikelihood > best_loglikelihood: best_loglikelihood = loglikelihood if i_iter == 0: list_of_GMMs.append(GMM.GaussianMixture(n_components=n_components)) if self.stack_landscapes_: ICs[-1] = gmm.aic(data) else: ICs[-1] = gmm.bic(data) list_of_GMMs[-1].weights_ = gmm.weights_ list_of_GMMs[-1].means_ = gmm.means_ list_of_GMMs[-1].covariances_ = gmm.covariances_ if self.stack_landscapes_: if self.max_n_components is None: gmm, _ = self._train_GMM(data, self.min_n_components) list_of_GMMs.append(gmm) ICs = np.asarray(ICs) model_weights = np.exp(-0.5 *(ICs-ICs.min())) model_weights /= model_weights.sum() # Fit mixture of density estimators using the validation data density_est = FEC.LandscapeStacker(data, list_of_validation_data, list_of_GMMs, n_splits=1, convergence_tol=self.convergence_tol_, n_iterations=self.n_iterations_, model_weights=model_weights) density = density_est.density(data_orig) if set_density_model: self.density_est_ = density_est else: # Estimate FE with best number of components (deduced from cross-validation) if self.n_splits_ > 1: print('Training final model with ' + str(best_n_components) + ' components.') best_loglikelihood = -np.inf density_est = GMM.GaussianMixture(n_components=best_n_components) # Fit multiple times to for i_iter in range(self.n_iterations_): gmm, loglikelihood = self._train_GMM(data, best_n_components) if loglikelihood > best_loglikelihood: best_loglikelihood = loglikelihood density_est.weights_ = gmm.weights_ density_est.means_ = gmm.means_ density_est.covariances_ = gmm.covariances_ else: ICs = np.asarray(ICs) self.BICs_ = np.copy(ICs) model_ind = ICs.argmin() gmm = list_of_GMMs[model_ind] best_n_components = gmm.weights_.shape[0] density_est = GMM.GaussianMixture(n_components=best_n_components) print('Identifying final model with ' + str(density_est.n_components_) + ' components.') density_est.weights_ = gmm.weights_ density_est.means_ = gmm.means_ density_est.covariances_ = gmm.covariances_ density = density_est.density(data_orig) if set_density_model: self.density_est_ = density_est if set_density_model: # Compute test set loglikelihood on the test set if test set exists if n_points_test > 0: self.test_set_loglikelihood = self.density_est_.loglikelihood(test_data) return self._free_energy(density) else: return self._free_energy(density), density_est def landscape(self): """ Computing free energy landscape with G(x) = -kT*log(p(x|T)) Returns the X,Y coordinate matrices (meshgrid) and their corresponding free energy. """ if len(self.data_.shape) == 1: FE_points = self._fit_FE(self.data_[:,np.newaxis]) else: FE_points = self._fit_FE(self.data_) print('Evaluating density in landscape') coords, density = self._density_landscape(self.density_est_) FE_landscape = self._free_energy(density) # Shift to zero self.min_FE_ = np.min(FE_landscape) FE_landscape = FE_landscape-self.min_FE_ FE_points = FE_points-self.min_FE_ self.FE_points_ = FE_points self.FE_landscape_ = FE_landscape self.coords_ = coords return coords, FE_landscape, FE_points def evaluate_free_energy(self,data): """ Evaluate the free energy of given data in the current free energy model. """ density = self.density_est_.density(data) free_energy = self._free_energy(density) if self.min_FE_ is not None: free_energy -= self.min_FE_ return free_energy def population_states(self, n_sampled_points=10000): """ Estimate the population of states (probability to be in a state) based on Mante-Carlo integration of the estimated density and state definitions. :param n_sampled_points: :return: """ if self.stack_landscapes_: state_populations = None print('TODO: Estimating population of states is not possible with stacked landscapes yet.') else: print('Sampling points from density.') # Sample points from estimated density points = self.density_est_.sample(n_sampled_points) # Assign cluster labels of sampled points cluster_labels = self.evaluate_clustering(points) print('Computing state populations.') # Monte-Carlo integration (histogramming) self.state_populations_, _ = np.histogram(cluster_labels, bins=int(self.labels_.max()+1), range=(self.labels_.min(),self.labels_.max()),density=False) #print(state_populations) self.state_populations_ = self.state_populations_/self.state_populations_.sum() return self.state_populations_ def evaluate_clustering(self, points, assign_transition_points=False): """ Assign cluster indices to points based on precomputed density model clustering. """ print('Assigning cluster labels based on precomputed density model clustering.') if self.cl_ is not None and self.cl_.clusterer_ is not None: labels = self.cl_.clusterer_.data_cluster_indices(cdist(points, self.cl_.clusterer_.grid_points_), self.cl_.clusterer_.grid_cluster_inds_) if assign_transition_points: labels = self.cl_.assign_transition_points(labels, points, self.density_est_) return labels def cluster(self, points, free_energies, eval_points=None, return_center_coords=False, assign_transition_points=False,use_FE_landscape=False, unravel_grid=True, transition_matrix=None): """ Cluster points according to estimated density. """ self.transition_matrix_ = transition_matrix print('Clustering free energy landscape...') self.cl_ = FEC.LandscapeClustering(self.stack_landscapes_,verbose=self.verbose_) if eval_points is not None and unravel_grid: tmp_points = [] for x in points: tmp_points.append(np.ravel(x)) points = np.asarray(tmp_points).T if len(points.shape) == 1: points = points[:,np.newaxis] if eval_points is not None: if len(eval_points.shape) == 1: eval_points = eval_points[:,np.newaxis] self.labels_, self.is_FE_min = self.cl_.cluster(self.density_est_, points, eval_points=eval_points, use_FE_landscape=use_FE_landscape, transition_matrix=self.transition_matrix_) self.core_labels_ = np.copy(self.labels_) if eval_points is not None: self.cluster_centers_ = self.cl_.get_cluster_representative(eval_points, self.labels_, free_energies) else: self.cluster_centers_ = self.cl_.get_cluster_representative(points, self.labels_, free_energies) if assign_transition_points: if eval_points is not None: self.labels_ = self.cl_.assign_transition_points(self.labels_, eval_points, self.density_est_) else: self.labels_ = self.cl_.assign_transition_points(self.labels_, points, self.density_est_) print('Done clustering.') if return_center_coords: return self.labels_, eval_points[self.cluster_centers_,:] else: return self.labels_, self.cluster_centers_ def pathways(self, states_from, states_to,n_points=10, convergence_tol=1e-1, step_size=1e-3, max_iter=100): """ Calculate minimum pathways between points (indices) in states_from and states_to. :param states_from: :param states_to: :param n_points: :param convergence_tol: :param step_size: :return: """ pathway_estimator = FEC.FreeEnergyPathways(self.density_est_, self.data_, self.temperature_, n_points=n_points, convergence_tol=convergence_tol, step_size=step_size, ensemble_of_GMMs=self.stack_landscapes_, max_iter=max_iter) self.pathways_ = [] for from_ind, to_ind in zip(states_from,states_to): self.pathways_.append(pathway_estimator.minimum_pathway(from_ind, to_ind)) return def visualize(self,title="Free energy landscape", fontsize=30, savefig=True, xlabel='x', ylabel='y', zlabel='z', vmax=7.5, n_contour_levels=15, show_data=False, figsize= [12, 10], filename='free_energy_landscape', dx=1, ax=None): if self.n_dims_ > 3: print('Plotting does not support > 3 dimensions') return # Set custom colormaps my_cmap = copy.copy(matplotlib.cm.get_cmap('jet')) my_cmap.set_over('white') my_cmap_cont = matplotlib.colors.ListedColormap(['black']) my_cmap_cont.set_over('white') plt.rcParams['figure.figsize'] = figsize if ax is None: fig = plt.figure() if self.n_dims_ < 3: ax = fig.add_subplot(1, 1, 1) else: ax = fig.add_subplot(111, projection='3d') ax.tick_params(labelsize=fontsize - 2) plt.tick_params(axis='both', which='major', labelsize=fontsize-4) for tick in ax.get_xticklabels(): tick.set_fontname("Serif") tick.set_fontweight('light') for tick in ax.get_yticklabels(): tick.set_fontname("Serif") tick.set_fontweight('light') # Plot free energy landscape FE_landscape = np.copy(self.FE_landscape_) FE_landscape[self.FE_landscape_ > vmax+0.5] = vmax+0.5 if self.n_dims_ == 2: ctf = ax.contourf(self.coords_[0], self.coords_[1], FE_landscape, n_contour_levels, cmap=my_cmap, vmin=0, vmax=vmax) cb=plt.colorbar(ctf, label='[kcal/mol]') text = cb.ax.yaxis.label font = matplotlib.font_manager.FontProperties(size=fontsize-3,family='serif',weight='light') text.set_font_properties(font) cb.ax.tick_params(labelsize=fontsize-2) for tick in cb.ax.get_yticklabels(): tick.set_fontname("Serif") tick.set_fontweight('light') ax.set_ylim([self.coords_[1].min(), self.coords_[1].max()]) ax.set_ylabel(ylabel, fontsize=fontsize - 2,fontname='serif',fontweight='light') elif self.n_dims_ == 1: if self.standard_error_FE_ is not None: ax.fill_between(self.coords_[0], FE_landscape - self.standard_error_FE_, FE_landscape + self.standard_error_FE_, color='k', alpha=0.2,zorder=2) ax.plot(self.coords_[0], FE_landscape, linewidth=3,color='k',zorder=1) ax.set_ylabel('Free energy [kcal/mol]',fontsize=fontsize-2,fontname='serif',fontweight='light') else: sc = ax.scatter(self.data_[::dx,0], self.data_[::dx,1], self.data_[::dx,2], s=30, c=self.FE_points_[::dx], alpha=0.8, cmap=my_cmap, vmin=0, vmax=vmax, edgecolor='k') ax.set_ylim([self.coords_[1].min(), self.coords_[1].max()]) ax.set_zlim([self.coords_[2].min(), self.coords_[2].max()]) cb=plt.colorbar(sc,label='[kcal/mol]') text = cb.ax.yaxis.label font = matplotlib.font_manager.FontProperties(size=fontsize-3,family='serif',weight='light') text.set_font_properties(font) cb.ax.tick_params(labelsize=fontsize-2) ax.set_ylabel(ylabel, fontsize=fontsize - 2,fontname='serif',fontweight='light') ax.set_zlabel(zlabel, fontsize=fontsize - 2,fontname='serif',fontweight='light') ax.set_xlim([self.coords_[0].min(), self.coords_[0].max()]) # Plot projected data points if show_data and self.n_dims_ < 3: # Plot projected data points if self.labels_ is not None: if self.n_dims_ > 1: transition_points=self.data_[self.labels_==0] core_points = self.data_[self.labels_ > 0] core_labels = self.labels_[self.labels_>0] ax.scatter(transition_points[::dx, 0], transition_points[::dx, 1], s=30, c=0.67*np.ones((transition_points[::dx].shape[0],3)),alpha=0.5) ax.scatter(core_points[::dx, 0], core_points[::dx, 1], s=80, c=core_labels[::dx], edgecolor='k', cmap=my_cmap, label='Intermediate state',alpha=0.8) else: ax.scatter(self.data_[self.labels_==0], self.FE_points_[self.labels_==0], s=30, c=[0.67, 0.67, 0.65],alpha=0.6,zorder=3) ax.scatter(self.data_[self.labels_>0], self.FE_points_[self.labels_>0], s=50, c=self.labels_[self.labels_>0], edgecolor='k', cmap=my_cmap, label='Intermediate state',alpha=0.8,zorder=4) if fontsize > 18: plt.legend(fontsize=fontsize-10,facecolor=[0.9,0.9,0.92]) else: plt.legend(fontsize=fontsize-4,facecolor=[0.9,0.9,0.92]) else: if self.n_dims_ > 1: ax.scatter(self.data_[:, 0], self.data_[:, 1], s=30, c=[0.67, 0.67, 0.65],alpha=0.5) else: ax.scatter(self.data_, self.FE_points_[:, 1], s=30, c=[0.67, 0.67, 0.65],alpha=0.5) # Plot minimum pathways between states if self.pathways_ is not None and self.n_dims_ > 1: set_pathway_label = True for p in self.pathways_: if set_pathway_label: ax.plot(p[:, 0], p[:, 1], color=[43.0/256.0,46.0/256.0,60.0/256.0], linewidth=5, marker='', label='Pathway') set_pathway_label = False else: ax.plot(p[:, 0], p[:, 1], color=[43.0/256.0,46.0/256.0,60.0/256.0], linewidth=5, marker='') if fontsize > 18: plt.legend(fontsize=fontsize-10,facecolor=[0.9,0.9,0.92]) else: plt.legend(fontsize=fontsize-4,facecolor=[0.9,0.9,0.92]) # Plot cluster centers in landscape if self.cluster_centers_ is not None: if self.n_dims_ > 1: ax.scatter(self.data_[self.cluster_centers_,0], self.data_[self.cluster_centers_,1], marker='s', s=120, linewidth=4, facecolor='',edgecolor='w', label='Cluster center') else: ax.scatter(self.data_[self.cluster_centers_], self.FE_points_[self.cluster_centers_], marker='s', s=120, linewidth=4, facecolor='',edgecolor='w', label='Cluster center',zorder=5) if fontsize > 18: plt.legend(fontsize=fontsize-10,facecolor=[0.9,0.9,0.92]) else: plt.legend(fontsize=fontsize-4,facecolor=[0.9,0.9,0.92]) ax.set_title(title, fontsize=fontsize,fontname='serif',fontweight='light') ax.set_xlabel(xlabel, fontsize=fontsize - 2,fontname='serif',fontweight='light') plt.rc('xtick', labelsize=fontsize-2) plt.rc('ytick', labelsize=fontsize-2) matplotlib.rc('font',family='Serif') if savefig: plt.savefig(filename + '.svg') plt.savefig(filename + '.eps') plt.savefig(filename + '.png') return
[ "matplotlib.rc", "matplotlib.cm.get_cmap", "numpy.ravel", "free_energy_clustering.cross_validation.split_train_validation", "sklearn.mixture.GaussianMixture", "numpy.ones", "matplotlib.pyplot.figure", "matplotlib.pyplot.tick_params", "free_energy_clustering.cross_validation.get_train_validation_set"...
[((6196, 6221), 'numpy.asarray', 'np.asarray', (['free_energies'], {}), '(free_energies)\n', (6206, 6221), True, 'import numpy as np\n'), ((8512, 8525), 'numpy.copy', 'np.copy', (['data'], {}), '(data)\n', (8519, 8525), True, 'import numpy as np\n'), ((8554, 8581), 'numpy.copy', 'np.copy', (['self.data_weights_'], {}), '(self.data_weights_)\n', (8561, 8581), True, 'import numpy as np\n'), ((15459, 15479), 'numpy.min', 'np.min', (['FE_landscape'], {}), '(FE_landscape)\n', (15465, 15479), True, 'import numpy as np\n'), ((18336, 18406), 'free_energy_clustering.LandscapeClustering', 'FEC.LandscapeClustering', (['self.stack_landscapes_'], {'verbose': 'self.verbose_'}), '(self.stack_landscapes_, verbose=self.verbose_)\n', (18359, 18406), True, 'import free_energy_clustering as FEC\n'), ((19042, 19063), 'numpy.copy', 'np.copy', (['self.labels_'], {}), '(self.labels_)\n', (19049, 19063), True, 'import numpy as np\n'), ((20267, 20480), 'free_energy_clustering.FreeEnergyPathways', 'FEC.FreeEnergyPathways', (['self.density_est_', 'self.data_', 'self.temperature_'], {'n_points': 'n_points', 'convergence_tol': 'convergence_tol', 'step_size': 'step_size', 'ensemble_of_GMMs': 'self.stack_landscapes_', 'max_iter': 'max_iter'}), '(self.density_est_, self.data_, self.temperature_,\n n_points=n_points, convergence_tol=convergence_tol, step_size=step_size,\n ensemble_of_GMMs=self.stack_landscapes_, max_iter=max_iter)\n', (20289, 20480), True, 'import free_energy_clustering as FEC\n'), ((21338, 21381), 'matplotlib.colors.ListedColormap', 'matplotlib.colors.ListedColormap', (["['black']"], {}), "(['black'])\n", (21370, 21381), False, 'import matplotlib\n'), ((21738, 21805), 'matplotlib.pyplot.tick_params', 'plt.tick_params', ([], {'axis': '"""both"""', 'which': '"""major"""', 'labelsize': '(fontsize - 4)'}), "(axis='both', which='major', labelsize=fontsize - 4)\n", (21753, 21805), True, 'import matplotlib.pyplot as plt\n'), ((22111, 22138), 'numpy.copy', 'np.copy', (['self.FE_landscape_'], {}), '(self.FE_landscape_)\n', (22118, 22138), True, 'import numpy as np\n'), ((27680, 27719), 'matplotlib.pyplot.rc', 'plt.rc', (['"""xtick"""'], {'labelsize': '(fontsize - 2)'}), "('xtick', labelsize=fontsize - 2)\n", (27686, 27719), True, 'import matplotlib.pyplot as plt\n'), ((27726, 27765), 'matplotlib.pyplot.rc', 'plt.rc', (['"""ytick"""'], {'labelsize': '(fontsize - 2)'}), "('ytick', labelsize=fontsize - 2)\n", (27732, 27765), True, 'import matplotlib.pyplot as plt\n'), ((27772, 27809), 'matplotlib.rc', 'matplotlib.rc', (['"""font"""'], {'family': '"""Serif"""'}), "('font', family='Serif')\n", (27785, 27809), False, 'import matplotlib\n'), ((4154, 4169), 'numpy.meshgrid', 'np.meshgrid', (['*x'], {}), '(*x)\n', (4165, 4169), True, 'import numpy as np\n'), ((5073, 5109), 'numpy.reshape', 'np.reshape', (['densities', 'self.n_grids_'], {}), '(densities, self.n_grids_)\n', (5083, 5109), True, 'import numpy as np\n'), ((5351, 5366), 'numpy.log', 'np.log', (['density'], {}), '(density)\n', (5357, 5366), True, 'import numpy as np\n'), ((6256, 6285), 'numpy.std', 'np.std', (['free_energies'], {'axis': '(0)'}), '(free_energies, axis=0)\n', (6262, 6285), True, 'import numpy as np\n'), ((6285, 6311), 'numpy.sqrt', 'np.sqrt', (['(n_data_blocks - 1)'], {}), '(n_data_blocks - 1)\n', (6292, 6311), True, 'import numpy as np\n'), ((6728, 6783), 'free_energy_clustering.cross_validation.get_train_validation_set', 'CV.get_train_validation_set', (['data', 'train_inds', 'val_inds'], {}), '(data, train_inds, val_inds)\n', (6755, 6783), True, 'import free_energy_clustering.cross_validation as CV\n'), ((6826, 6839), 'numpy.copy', 'np.copy', (['data'], {}), '(data)\n', (6833, 6839), True, 'import numpy as np\n'), ((6870, 6883), 'numpy.copy', 'np.copy', (['data'], {}), '(data)\n', (6877, 6883), True, 'import numpy as np\n'), ((6942, 7011), 'sklearn.mixture.GaussianMixture', 'GaussianMixture', ([], {'n_components': 'n_components', 'tol': 'self.convergence_tol_'}), '(n_components=n_components, tol=self.convergence_tol_)\n', (6957, 7011), False, 'from sklearn.mixture import GaussianMixture\n'), ((7246, 7359), 'free_energy_clustering.GMM.GaussianMixture', 'GMM.GaussianMixture', ([], {'n_components': 'n_components', 'convergence_tol': 'self.convergence_tol_', 'verbose': 'self.verbose_'}), '(n_components=n_components, convergence_tol=self.\n convergence_tol_, verbose=self.verbose_)\n', (7265, 7359), True, 'import free_energy_clustering.GMM as GMM\n'), ((8681, 8715), 'numpy.copy', 'np.copy', (['data[0:-n_points_test, :]'], {}), '(data[0:-n_points_test, :])\n', (8688, 8715), True, 'import numpy as np\n'), ((8886, 8913), 'numpy.zeros', 'np.zeros', (['(0, self.n_dims_)'], {}), '((0, self.n_dims_))\n', (8894, 8913), True, 'import numpy as np\n'), ((9417, 9483), 'free_energy_clustering.cross_validation.split_train_validation', 'CV.split_train_validation', (['data', 'self.n_splits_', 'self.shuffle_data'], {}), '(data, self.n_splits_, self.shuffle_data)\n', (9442, 9483), True, 'import free_energy_clustering.cross_validation as CV\n'), ((12270, 12285), 'numpy.asarray', 'np.asarray', (['ICs'], {}), '(ICs)\n', (12280, 12285), True, 'import numpy as np\n'), ((12494, 12682), 'free_energy_clustering.LandscapeStacker', 'FEC.LandscapeStacker', (['data', 'list_of_validation_data', 'list_of_GMMs'], {'n_splits': '(1)', 'convergence_tol': 'self.convergence_tol_', 'n_iterations': 'self.n_iterations_', 'model_weights': 'model_weights'}), '(data, list_of_validation_data, list_of_GMMs, n_splits=\n 1, convergence_tol=self.convergence_tol_, n_iterations=self.\n n_iterations_, model_weights=model_weights)\n', (12514, 12682), True, 'import free_energy_clustering as FEC\n'), ((21250, 21279), 'matplotlib.cm.get_cmap', 'matplotlib.cm.get_cmap', (['"""jet"""'], {}), "('jet')\n", (21272, 21279), False, 'import matplotlib\n'), ((21513, 21525), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (21523, 21525), True, 'import matplotlib.pyplot as plt\n'), ((22377, 22414), 'matplotlib.pyplot.colorbar', 'plt.colorbar', (['ctf'], {'label': '"""[kcal/mol]"""'}), "(ctf, label='[kcal/mol]')\n", (22389, 22414), True, 'import matplotlib.pyplot as plt\n'), ((22471, 22564), 'matplotlib.font_manager.FontProperties', 'matplotlib.font_manager.FontProperties', ([], {'size': '(fontsize - 3)', 'family': '"""serif"""', 'weight': '"""light"""'}), "(size=fontsize - 3, family='serif',\n weight='light')\n", (22509, 22564), False, 'import matplotlib\n'), ((27842, 27872), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(filename + '.svg')"], {}), "(filename + '.svg')\n", (27853, 27872), True, 'import matplotlib.pyplot as plt\n'), ((27885, 27915), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(filename + '.eps')"], {}), "(filename + '.eps')\n", (27896, 27915), True, 'import matplotlib.pyplot as plt\n'), ((27928, 27958), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(filename + '.png')"], {}), "(filename + '.png')\n", (27939, 27958), True, 'import matplotlib.pyplot as plt\n'), ((4963, 4994), 'numpy.asarray', 'np.asarray', (['grid_points_flatten'], {}), '(grid_points_flatten)\n', (4973, 4994), True, 'import numpy as np\n'), ((5756, 5818), 'numpy.copy', 'np.copy', (['self.data_[i * n_data_points:(i + 1) * n_data_points]'], {}), '(self.data_[i * n_data_points:(i + 1) * n_data_points])\n', (5763, 5818), True, 'import numpy as np\n'), ((5854, 5893), 'numpy.copy', 'np.copy', (['self.data_[i * n_data_points:]'], {}), '(self.data_[i * n_data_points:])\n', (5861, 5893), True, 'import numpy as np\n'), ((8800, 8848), 'numpy.copy', 'np.copy', (['self.data_weights_[0:-n_points_test, :]'], {}), '(self.data_weights_[0:-n_points_test, :])\n', (8807, 8848), True, 'import numpy as np\n'), ((13232, 13283), 'free_energy_clustering.GMM.GaussianMixture', 'GMM.GaussianMixture', ([], {'n_components': 'best_n_components'}), '(n_components=best_n_components)\n', (13251, 13283), True, 'import free_energy_clustering.GMM as GMM\n'), ((13807, 13822), 'numpy.asarray', 'np.asarray', (['ICs'], {}), '(ICs)\n', (13817, 13822), True, 'import numpy as np\n'), ((13852, 13864), 'numpy.copy', 'np.copy', (['ICs'], {}), '(ICs)\n', (13859, 13864), True, 'import numpy as np\n'), ((14040, 14091), 'free_energy_clustering.GMM.GaussianMixture', 'GMM.GaussianMixture', ([], {'n_components': 'best_n_components'}), '(n_components=best_n_components)\n', (14059, 14091), True, 'import free_energy_clustering.GMM as GMM\n'), ((17696, 17743), 'scipy.spatial.distance.cdist', 'cdist', (['points', 'self.cl_.clusterer_.grid_points_'], {}), '(points, self.cl_.clusterer_.grid_points_)\n', (17701, 17743), False, 'from scipy.spatial.distance import cdist\n'), ((18585, 18607), 'numpy.asarray', 'np.asarray', (['tmp_points'], {}), '(tmp_points)\n', (18595, 18607), True, 'import numpy as np\n'), ((23744, 23780), 'matplotlib.pyplot.colorbar', 'plt.colorbar', (['sc'], {'label': '"""[kcal/mol]"""'}), "(sc, label='[kcal/mol]')\n", (23756, 23780), True, 'import matplotlib.pyplot as plt\n'), ((23836, 23929), 'matplotlib.font_manager.FontProperties', 'matplotlib.font_manager.FontProperties', ([], {'size': '(fontsize - 3)', 'family': '"""serif"""', 'weight': '"""light"""'}), "(size=fontsize - 3, family='serif',\n weight='light')\n", (23874, 23929), False, 'import matplotlib\n'), ((4002, 4071), 'numpy.linspace', 'np.linspace', (['self.x_lims_[i_dim][0]', 'self.x_lims_[i_dim][1]', 'self.nx_'], {}), '(self.x_lims_[i_dim][0], self.x_lims_[i_dim][1], self.nx_)\n', (4013, 4071), True, 'import numpy as np\n'), ((4929, 4940), 'numpy.ravel', 'np.ravel', (['x'], {}), '(x)\n', (4937, 4940), True, 'import numpy as np\n'), ((7652, 7721), 'free_energy_clustering.cross_validation.get_train_validation_set', 'CV.get_train_validation_set', (['self.data_weights_', 'train_inds', 'val_inds'], {}), '(self.data_weights_, train_inds, val_inds)\n', (7679, 7721), True, 'import free_energy_clustering.cross_validation as CV\n'), ((18551, 18562), 'numpy.ravel', 'np.ravel', (['x'], {}), '(x)\n', (18559, 18562), True, 'import numpy as np\n'), ((25469, 25531), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'fontsize': '(fontsize - 10)', 'facecolor': '[0.9, 0.9, 0.92]'}), '(fontsize=fontsize - 10, facecolor=[0.9, 0.9, 0.92])\n', (25479, 25531), True, 'import matplotlib.pyplot as plt\n'), ((25569, 25630), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'fontsize': '(fontsize - 4)', 'facecolor': '[0.9, 0.9, 0.92]'}), '(fontsize=fontsize - 4, facecolor=[0.9, 0.9, 0.92])\n', (25579, 25630), True, 'import matplotlib.pyplot as plt\n'), ((26532, 26594), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'fontsize': '(fontsize - 10)', 'facecolor': '[0.9, 0.9, 0.92]'}), '(fontsize=fontsize - 10, facecolor=[0.9, 0.9, 0.92])\n', (26542, 26594), True, 'import matplotlib.pyplot as plt\n'), ((26632, 26693), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'fontsize': '(fontsize - 4)', 'facecolor': '[0.9, 0.9, 0.92]'}), '(fontsize=fontsize - 4, facecolor=[0.9, 0.9, 0.92])\n', (26642, 26693), True, 'import matplotlib.pyplot as plt\n'), ((27343, 27405), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'fontsize': '(fontsize - 10)', 'facecolor': '[0.9, 0.9, 0.92]'}), '(fontsize=fontsize - 10, facecolor=[0.9, 0.9, 0.92])\n', (27353, 27405), True, 'import matplotlib.pyplot as plt\n'), ((27443, 27504), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'fontsize': '(fontsize - 4)', 'facecolor': '[0.9, 0.9, 0.92]'}), '(fontsize=fontsize - 4, facecolor=[0.9, 0.9, 0.92])\n', (27453, 27504), True, 'import matplotlib.pyplot as plt\n'), ((24766, 24812), 'numpy.ones', 'np.ones', (['(transition_points[::dx].shape[0], 3)'], {}), '((transition_points[::dx].shape[0], 3))\n', (24773, 24812), True, 'import numpy as np\n'), ((11595, 11641), 'free_energy_clustering.GMM.GaussianMixture', 'GMM.GaussianMixture', ([], {'n_components': 'n_components'}), '(n_components=n_components)\n', (11614, 11641), True, 'import free_energy_clustering.GMM as GMM\n')]
from datetime import datetime import os import pickle import argparse import numpy as np import torch import torch.nn.functional as F import utils import models def get_args(): parser = argparse.ArgumentParser() utils.add_shared_args(parser) parser.add_argument('--rm-idx-path', type=str, default=None) parser.add_argument('--init-model-path', type=str, default=None) return parser.parse_args() def get_forget_idx(dataset, kill_num): kill_val = 0 if 'targets' in vars(dataset).keys(): labels = np.array(dataset.targets) elif 'labels' in vars(dataset).keys(): labels = np.array(dataset.labels) else: raise NotImplementedError randidx = np.random.permutation( np.where(labels==kill_val)[0] ) return randidx[:kill_num] def evaluate(model, loader, cpu): ''' average log predictive probability ''' loss = utils.AverageMeter() acc = utils.AverageMeter() n = len(loader.sampler.indices) model.eval() for x, y in loader: if not cpu: x, y = x.cuda(), y.cuda() with torch.no_grad(): _y = model(x) lo = - model.log_prior() + F.cross_entropy(_y,y) * n lo = lo.item() ac = (_y.argmax(dim=1) == y).sum().item() / len(y) loss.update(lo, len(y)) acc.update(ac, len(y)) return loss.average(), acc.average() def save_checkpoint(save_dir, save_name, log, model, optimizer): with open('{}/{}-log.pkl'.format(save_dir, save_name), 'wb') as f: pickle.dump(log, f) torch.save({ 'model_state_dict': model.state_dict(), 'optimizer_state_dict': optimizer.state_dict(), }, '{}/{}-model.pkl'.format(save_dir, save_name)) def adjust_learning_rate(optimizer, step, init_lr, lr_decay_rate, lr_decay_freq): lr = init_lr * ( lr_decay_rate ** (step // lr_decay_freq) ) for group in optimizer.param_groups: group['lr'] = lr def adjust_step_size(optimizer, step, sp_init, sp_decay_exp): sp_rate = step ** sp_decay_exp for group in optimizer.param_groups: group['lr'] = sp_init * sp_rate def main(args, logger): ''' retrieve lots of data ''' trainset, testset = utils.get_dataset(args.dataset) if args.rm_idx_path is not None: with open(args.rm_idx_path, 'rb') as f: forgetted_idx = pickle.load(f) else: forgetted_idx = get_forget_idx(trainset, args.ifs_kill_num) train_sampler = utils.DataSampler(trainset, args.batch_size) train_sampler.remove(forgetted_idx) train_loader = utils.DataLoader(trainset, args.batch_size) train_loader.remove(forgetted_idx) forgetted_train_loader = utils.DataLoader(trainset, args.batch_size) forgetted_train_loader.set_sampler_indices(forgetted_idx) test_loader = utils.DataLoader(testset, args.batch_size) ''' end of retrieving data ''' model = utils.get_mcmc_bnn_arch(args.arch, args.dataset, args.prior_sig) if args.init_model_path is not None: state_dict = torch.load(args.init_model_path, map_location=torch.device('cpu')) model.load_state_dict(state_dict['model_state_dict']) del state_dict args.lr /= len(train_sampler) args.sp_init /= len(train_sampler) optim_params = {'lr':args.lr, 'momentum':args.momentum, 'weight_decay':args.weight_decay, 'sghmc_alpha':args.sghmc_alpha} optimizer = utils.get_optim(model.parameters(), 'sgd', **optim_params) model.n = len(train_sampler) if not args.cpu: model.cuda() log = dict() log['user_time'] = 0 utils.add_log(log, 'forgetted_idx', forgetted_idx) sampling_steps = 0 for step in range(args.burn_in_steps): ''' adjust learning rate / step-size ''' if step < args.explore_steps: adjust_learning_rate(optimizer, step, args.lr, args.lr_decay_rate, args.lr_decay_freq) if step>=args.explore_steps: if sampling_steps == 0: optim_params['lr'] = args.sp_init optimizer = utils.get_optim(model.parameters(), args.optim, **optim_params) sampling_steps += 1 adjust_step_size(optimizer, sampling_steps, args.sp_init, args.sp_decay_exp) x, y = next(train_sampler) if not args.cpu: x, y = x.cuda(), y.cuda() start_time = datetime.now() model.train() ''' variational neural network ''' _y = model(x) lo = - model.log_prior() + F.cross_entropy(_y,y) * model.n optimizer.zero_grad() lo.backward() optimizer.step() loss = lo.item() acc = (_y.argmax(dim=1) == y).sum().item() / len(y) torch.cuda.synchronize() end_time = datetime.now() user_time = (end_time - start_time).total_seconds() log['user_time'] += user_time utils.add_log(log, 'burn_in_loss', loss) utils.add_log(log, 'burn_in_acc', acc) if (step+1) % args.eval_freq == 0: logger.info('burn-in step [{}/{}]:' .format(step+1, args.burn_in_steps)) logger.info('user time {:.3f} sec \t' 'cumulated user time {:.3f} mins' .format(user_time, log['user_time']/60) ) logger.info('burn-in loss {:.2e} \t' 'burn-in acc {:.2%}' .format(loss, acc) ) test_loss, test_acc = evaluate(model, test_loader, args.cpu) logger.info('test loss {:.2e} \t' 'test acc {:.2%}' .format(test_loss, test_acc) ) utils.add_log(log, 'test_loss', test_loss) utils.add_log(log, 'test_acc', test_acc) train_loss, train_acc = evaluate(model, train_loader, args.cpu) logger.info('(maybe remain) train loss {:.2e} \t' 'train acc {:.2%}' .format(train_loss, train_acc) ) utils.add_log(log, '(remain) train_loss', train_loss) utils.add_log(log, '(remain) train_acc', train_acc) fo_train_loss, fo_train_acc = evaluate(model, forgetted_train_loader, args.cpu) logger.info('forgetted train loss {:.2e} \t' 'train acc {:.2%}' .format(fo_train_loss, fo_train_acc) ) utils.add_log(log, 'forgetted_train_loss', fo_train_loss) utils.add_log(log, 'forgetted_train_acc', fo_train_acc) logger.info('') save_checkpoint(args.save_dir, '{}-fin'.format(args.save_name), log, model, optimizer) return if __name__ == '__main__': args = get_args() logger = utils.generic_init(args) try: main(args, logger) except Exception as e: logger.exception('Unexpected exception! %s', e)
[ "torch.cuda.synchronize", "pickle.dump", "argparse.ArgumentParser", "utils.AverageMeter", "utils.DataLoader", "utils.DataSampler", "torch.nn.functional.cross_entropy", "datetime.datetime.now", "numpy.where", "utils.add_log", "utils.get_mcmc_bnn_arch", "numpy.array", "pickle.load", "utils.g...
[((193, 218), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (216, 218), False, 'import argparse\n'), ((223, 252), 'utils.add_shared_args', 'utils.add_shared_args', (['parser'], {}), '(parser)\n', (244, 252), False, 'import utils\n'), ((887, 907), 'utils.AverageMeter', 'utils.AverageMeter', ([], {}), '()\n', (905, 907), False, 'import utils\n'), ((918, 938), 'utils.AverageMeter', 'utils.AverageMeter', ([], {}), '()\n', (936, 938), False, 'import utils\n'), ((2205, 2236), 'utils.get_dataset', 'utils.get_dataset', (['args.dataset'], {}), '(args.dataset)\n', (2222, 2236), False, 'import utils\n'), ((2465, 2509), 'utils.DataSampler', 'utils.DataSampler', (['trainset', 'args.batch_size'], {}), '(trainset, args.batch_size)\n', (2482, 2509), False, 'import utils\n'), ((2570, 2613), 'utils.DataLoader', 'utils.DataLoader', (['trainset', 'args.batch_size'], {}), '(trainset, args.batch_size)\n', (2586, 2613), False, 'import utils\n'), ((2683, 2726), 'utils.DataLoader', 'utils.DataLoader', (['trainset', 'args.batch_size'], {}), '(trainset, args.batch_size)\n', (2699, 2726), False, 'import utils\n'), ((2808, 2850), 'utils.DataLoader', 'utils.DataLoader', (['testset', 'args.batch_size'], {}), '(testset, args.batch_size)\n', (2824, 2850), False, 'import utils\n'), ((2899, 2963), 'utils.get_mcmc_bnn_arch', 'utils.get_mcmc_bnn_arch', (['args.arch', 'args.dataset', 'args.prior_sig'], {}), '(args.arch, args.dataset, args.prior_sig)\n', (2922, 2963), False, 'import utils\n'), ((3577, 3627), 'utils.add_log', 'utils.add_log', (['log', '"""forgetted_idx"""', 'forgetted_idx'], {}), "(log, 'forgetted_idx', forgetted_idx)\n", (3590, 3627), False, 'import utils\n'), ((6672, 6696), 'utils.generic_init', 'utils.generic_init', (['args'], {}), '(args)\n', (6690, 6696), False, 'import utils\n'), ((538, 563), 'numpy.array', 'np.array', (['dataset.targets'], {}), '(dataset.targets)\n', (546, 563), True, 'import numpy as np\n'), ((1528, 1547), 'pickle.dump', 'pickle.dump', (['log', 'f'], {}), '(log, f)\n', (1539, 1547), False, 'import pickle\n'), ((4326, 4340), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (4338, 4340), False, 'from datetime import datetime\n'), ((4667, 4691), 'torch.cuda.synchronize', 'torch.cuda.synchronize', ([], {}), '()\n', (4689, 4691), False, 'import torch\n'), ((4711, 4725), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (4723, 4725), False, 'from datetime import datetime\n'), ((4833, 4873), 'utils.add_log', 'utils.add_log', (['log', '"""burn_in_loss"""', 'loss'], {}), "(log, 'burn_in_loss', loss)\n", (4846, 4873), False, 'import utils\n'), ((4882, 4920), 'utils.add_log', 'utils.add_log', (['log', '"""burn_in_acc"""', 'acc'], {}), "(log, 'burn_in_acc', acc)\n", (4895, 4920), False, 'import utils\n'), ((624, 648), 'numpy.array', 'np.array', (['dataset.labels'], {}), '(dataset.labels)\n', (632, 648), True, 'import numpy as np\n'), ((731, 759), 'numpy.where', 'np.where', (['(labels == kill_val)'], {}), '(labels == kill_val)\n', (739, 759), True, 'import numpy as np\n'), ((1078, 1093), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (1091, 1093), False, 'import torch\n'), ((2351, 2365), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (2362, 2365), False, 'import pickle\n'), ((5616, 5658), 'utils.add_log', 'utils.add_log', (['log', '"""test_loss"""', 'test_loss'], {}), "(log, 'test_loss', test_loss)\n", (5629, 5658), False, 'import utils\n'), ((5671, 5711), 'utils.add_log', 'utils.add_log', (['log', '"""test_acc"""', 'test_acc'], {}), "(log, 'test_acc', test_acc)\n", (5684, 5711), False, 'import utils\n'), ((5963, 6016), 'utils.add_log', 'utils.add_log', (['log', '"""(remain) train_loss"""', 'train_loss'], {}), "(log, '(remain) train_loss', train_loss)\n", (5976, 6016), False, 'import utils\n'), ((6029, 6080), 'utils.add_log', 'utils.add_log', (['log', '"""(remain) train_acc"""', 'train_acc'], {}), "(log, '(remain) train_acc', train_acc)\n", (6042, 6080), False, 'import utils\n'), ((6349, 6406), 'utils.add_log', 'utils.add_log', (['log', '"""forgetted_train_loss"""', 'fo_train_loss'], {}), "(log, 'forgetted_train_loss', fo_train_loss)\n", (6362, 6406), False, 'import utils\n'), ((6419, 6474), 'utils.add_log', 'utils.add_log', (['log', '"""forgetted_train_acc"""', 'fo_train_acc'], {}), "(log, 'forgetted_train_acc', fo_train_acc)\n", (6432, 6474), False, 'import utils\n'), ((3073, 3092), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (3085, 3092), False, 'import torch\n'), ((4464, 4486), 'torch.nn.functional.cross_entropy', 'F.cross_entropy', (['_y', 'y'], {}), '(_y, y)\n', (4479, 4486), True, 'import torch.nn.functional as F\n'), ((1160, 1182), 'torch.nn.functional.cross_entropy', 'F.cross_entropy', (['_y', 'y'], {}), '(_y, y)\n', (1175, 1182), True, 'import torch.nn.functional as F\n')]
# coding=utf-8 from __future__ import unicode_literals import unittest from datetime import datetime import lore.encoders import numpy import pandas import lore class TestEquals(unittest.TestCase): def setUp(self): self.encoder = lore.encoders.Equals('left', 'right') def test_equality(self): data = pandas.DataFrame({ 'left': [None, 1, 2, 2], 'right': [None, None, 1, 2] }) self.encoder.fit(data) encoded = self.encoder.transform(data) self.assertEqual(list(encoded), [0., 0., 0., 1.]) def test_cardinality(self): self.assertEqual(2, self.encoder.cardinality()) class TestUniform(unittest.TestCase): def setUp(self): self.encoder = lore.encoders.Uniform('test') self.encoder.fit(pandas.DataFrame({'test': [3, 1, 2, 1, 4]})) def test_cardinality(self): self.assertRaises(ValueError, self.encoder.cardinality) def test_reverse_transform(self): a = [1, 2, 3] b = self.encoder.reverse_transform( self.encoder.transform(pandas.DataFrame({'test': a})) ).tolist() self.assertEqual(a, b) def test_high_outliers_are_capped(self): a = self.encoder.transform(pandas.DataFrame({'test': [100, 10000, float('inf')]})).tolist() self.assertEqual(a, [1, 1, 1]) def test_low_outliers_are_capped(self): a = self.encoder.transform(pandas.DataFrame({'test': [-100, -10000, -float('inf')]})).tolist() self.assertEqual(a, [0, 0, 0]) def test_handles_nans(self): self.encoder = lore.encoders.Uniform('test') self.encoder.fit(pandas.DataFrame({'test': [3, 1, 2, 1, 4, None]})) a = self.encoder.transform(pandas.DataFrame({'test': [None, float('nan')]})) self.assertEqual(a.tolist(), [0.0, 0.0]) class TestNorm(unittest.TestCase): def setUp(self): self.encoder = lore.encoders.Norm('test', dtype=numpy.float64) self.x = [3, 1, 2, 1, 4] self.mean = numpy.mean(self.x) self.std = numpy.std(self.x) self.encoder.fit(pandas.DataFrame({'test': self.x})) def test_mean_sd(self): a = numpy.arange(10) enc = lore.encoders.Norm('test', dtype=numpy.float64) data = pandas.DataFrame({'test': a}) enc.fit(data) b = enc.transform(data) self.assertAlmostEqual(numpy.mean(b), 0) self.assertAlmostEqual(numpy.std(b), 1) def test_cardinality(self): self.assertRaises(ValueError, self.encoder.cardinality) def test_reverse_transform(self): a = [1, 2, 3] b = self.encoder.reverse_transform( self.encoder.transform(pandas.DataFrame({'test': a})) ).tolist() self.assertEqual(a, b) def test_high_outliers_are_capped(self): a = self.encoder.transform(pandas.DataFrame({'test': [100, 10000, float('inf')]})).tolist() b = (([4, 4, 4] - self.mean) / self.std).tolist() self.assertEqual(a, b) def test_low_outliers_are_capped(self): a = self.encoder.transform(pandas.DataFrame({'test': [-100, -10000, -float('inf')]})).tolist() b = (([1, 1, 1] - self.mean) / self.std).tolist() self.assertEqual(a, b) def test_handles_nans(self): self.encoder = lore.encoders.Norm('test') self.encoder.fit(pandas.DataFrame({'test': [3, 1, 2, 1, 4, None]})) a = self.encoder.transform(pandas.DataFrame({'test': [None, float('nan')]})) self.assertEqual(a.tolist(), [0.0, 0.0]) def test_accidental_object_type_array_from_none(self): self.encoder = lore.encoders.Norm('test') self.encoder.fit(pandas.DataFrame({'test': [3, 1, 2, 1, 4]})) a = self.encoder.transform(pandas.DataFrame({'test': [None]})) self.assertEqual(a.tolist(), [0.0]) class TestDiscrete(unittest.TestCase): def setUp(self): self.encoder = lore.encoders.Discrete('test', bins=5) self.encoder.fit(pandas.DataFrame({'test': [0, 4]})) def test_cardinality(self): self.assertEqual(6, self.encoder.cardinality()) def test_bins(self): b = self.encoder.transform(pandas.DataFrame({'test': [0, 1, 2, 3, 4]})) self.assertEqual(b.tolist(), [0.0, 1.0, 2.0, 3.0, 4.0]) def test_bins_halved(self): b = self.encoder.transform(pandas.DataFrame({'test': [0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5]})) self.assertEqual(b.tolist(), [0.0, 0.0, 1.0, 1.0, 2.0, 2.0, 3.0, 3.0, 4.0, 4.0]) def test_limits(self): b = self.encoder.transform(pandas.DataFrame({'test': [float('nan'), -1, 0, 3, 7, float('inf')]})) self.assertEqual(b.tolist(), [5.0, 0.0, 0.0, 3.0, 4.0, 4.0]) def test_datetimes(self): self.encoder = lore.encoders.Discrete('test', bins=5) fit = [datetime(1, 1, 1), datetime(5, 5, 5)] self.encoder.fit(pandas.DataFrame({'test': fit})) test = [ datetime(1, 1, 1), datetime(2, 2, 2), datetime(3, 3, 3), datetime(4, 4, 4), datetime(5, 5, 5), ] b = self.encoder.transform(pandas.DataFrame({'test': test})) self.assertEqual(b.tolist(), [0.0, 1.0, 1.0, 3.0, 4.0]) class TestBoolean(unittest.TestCase): def setUp(self): self.encoder = lore.encoders.Boolean('test') def test_cardinality(self): self.assertEqual(self.encoder.cardinality(), 3) def test_handles_nans(self): a = self.encoder.transform(pandas.DataFrame({'test': [ 0, False, 123, True, float('nan'), None, float('inf') ]})) self.assertEqual(a.tolist(), [0, 0, 1, 1, 2, 2, 1]) class TestEnum(unittest.TestCase): def setUp(self): self.encoder = lore.encoders.Enum('test') self.encoder.fit(pandas.DataFrame({'test': [0, 1, 4]})) def test_cardinality(self): self.assertEqual(self.encoder.cardinality(), 7) def test_outliers_are_unfit(self): a = self.encoder.transform(pandas.DataFrame({'test': [100, -1]})).tolist() self.assertEqual(a, [self.encoder.unfit_value, self.encoder.unfit_value]) def test_handles_nans(self): self.encoder = lore.encoders.Enum('test') self.encoder.fit(pandas.DataFrame({'test': [3, 1, 2, 1, 4, None]})) a = self.encoder.transform(pandas.DataFrame({'test': [ None, float('nan'), 0, 4.0, 5, float('inf') ]})) self.assertEqual(a.tolist(), [ self.encoder.missing_value, self.encoder.missing_value, 0, 4, self.encoder.unfit_value, self.encoder.unfit_value ]) class TestQuantile(unittest.TestCase): def setUp(self): self.encoder = lore.encoders.Quantile('test', quantiles=5) self.encoder.fit(pandas.DataFrame({'test': [1, 2, 3, 4, 5, 6, 10, 20, 30, 40, 50, 100, 1000]})) def test_cardinality(self): self.assertEqual(self.encoder.cardinality(), 8) def test_unfit_data(self): a = self.encoder.transform(pandas.DataFrame({'test': [0, 1, 2, 3, 4, 5, 1110000, float('inf'), None, float('nan')]})).tolist() self.assertEqual(a, [5, 0, 0, 0, 1, 1, 6, 6, 7, 7]) def test_long_ties(self): self.encoder.fit(pandas.DataFrame({'test': [1, 1, 1, 1, 1, 1, 1, 1, 9, 10]})) self.assertEqual(self.encoder.cardinality(), 5) # 1, [9, 10] + lower, upper, missing a = self.encoder.transform(pandas.DataFrame({'test': range(0, 12)})) self.assertEqual(a.tolist(), [2, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 3]) def test_reverse_transform(self): a = self.encoder.transform(pandas.DataFrame({'test': [0, 1, 2, 3, 4, 5, 1110000, None, float('nan')]})) self.assertEqual(self.encoder.reverse_transform(a).tolist(), [ '<1', 1.0, 1.0, 1.0, 3.4000000000000004, 3.4000000000000004, '>1000', None, None ]) class TestUnique(unittest.TestCase): def setUp(self): self.encoder = lore.encoders.Unique('test') self.encoder.fit(pandas.DataFrame({'test': ['a', 'b', 'd', 'c', 'b']})) def test_cardinality(self): self.assertEqual(self.encoder.cardinality(), 7) def test_avoiding_0(self): data = pandas.DataFrame({'test': ['a', 'b', 'e', None]}) transform = self.encoder.transform(data) self.assertFalse(0 in transform) def test_minimum_occurrences(self): self.encoder = lore.encoders.Unique('test', minimum_occurrences=2) self.encoder.fit(pandas.DataFrame({'test': ['a', 'b', 'd', 'c', 'b']})) self.assertEqual(self.encoder.cardinality(), 4) b = self.encoder.reverse_transform( self.encoder.transform(pandas.DataFrame({'test': ['a', 'notafitlabel']})) ).tolist() self.assertEqual(['LONG_TAIL', 'LONG_TAIL'], b) def test_reverse_transform(self): a = ['a', 'b', 'c'] b = self.encoder.reverse_transform( self.encoder.transform(pandas.DataFrame({'test': a})) ).tolist() self.assertEqual(a, b) def test_handles_missing_labels(self): a = [None, float('nan')] b = self.encoder.reverse_transform( self.encoder.transform(pandas.DataFrame({'test': a})) ).tolist() self.assertEqual(['MISSING_VALUE', 'MISSING_VALUE'], b) self.assertEqual(self.encoder.cardinality(), 7) def test_handles_stratify(self): encoder = lore.encoders.Unique( 'test', stratify='user_id', minimum_occurrences=2) encoder.fit(pandas.DataFrame({ 'test': ['a', 'b', 'd', 'c', 'b', 'a'], 'user_id': [0, 1, 2, 3, 4, 0] })) self.assertEqual(encoder.cardinality(), 4) class TestOneHot(unittest.TestCase): @classmethod def setUpClass(cls): cls.encoder = lore.encoders.OneHot('test') cls.input_df = pandas.DataFrame({'test': [i for s in [[j]*j for j in range(1, 4)] for i in s]}) cls.test_df = pandas.DataFrame({'test': [i for s in [[j]*j for j in range(1, 5)] for i in s]}) cls.encoder.fit(cls.input_df) def test_onehot(self): output_df = self.encoder.transform(self.test_df) result_matrix = numpy.zeros((10, 3)) for j in range(result_matrix.shape[1]): for i in range(int(j*(j + 1)/2), int(j*(j+1)/2) + j + 1): result_matrix[i, j] = 1 self.assertEqual((output_df.values == result_matrix).all(), True) def test_compessed_one_hot(self): self.encoder = lore.encoders.OneHot('test', compressed=True, minimum_occurrences=2) self.encoder.fit(self.input_df) output_df = self.encoder.transform(self.test_df) result_matrix = numpy.zeros((10, 2)) for j in range(result_matrix.shape[1]): for i in range(int((j + 1)*(j + 2)/2), int((j + 1)*(j+2)/2) + j + 2): result_matrix[i, j] = 1 self.assertEqual((output_df.values == result_matrix).all(), True) class TestToken(unittest.TestCase): @classmethod def setUpClass(cls): cls.encoder = lore.encoders.Token('test', sequence_length=3) cls.encoder.fit(pandas.DataFrame({'test': ['apple, !orange! carrot']})) def test_cardinality(self): self.assertEqual(self.encoder.cardinality(), 6) def test_reverse_transform(self): a = ['apple orange carrot', 'carrot orange apple'] b = self.encoder.reverse_transform( self.encoder.transform(pandas.DataFrame({'test': a})) ).tolist() self.assertEqual(a, b) def test_unicode(self): a = ['漢 字'] b = self.encoder.reverse_transform( self.encoder.transform(pandas.DataFrame({'test': a})) ).tolist() self.assertEqual(b, ['LONG_TAIL LONG_TAIL MISSING_VALUE']) def test_handles_missing_labels(self): a = ['thisisnotavalidwordintheembeddings', float('nan'), None] b = self.encoder.reverse_transform( self.encoder.transform(pandas.DataFrame({'test': a})) ).tolist() self.assertEqual(['LONG_TAIL MISSING_VALUE MISSING_VALUE', 'MISSING_VALUE MISSING_VALUE MISSING_VALUE', 'MISSING_VALUE MISSING_VALUE MISSING_VALUE'], b) self.assertEqual(self.encoder.cardinality(), 6) class TestMiddleOut(unittest.TestCase): def test_simple(self): enc = lore.encoders.MiddleOut('test', depth=2) res = enc.transform(pandas.DataFrame({'test': numpy.arange(8) + 1})) self.assertEqual(res.tolist(), [0, 1, 2, 2, 2, 2, 3, 4]) self.assertEqual(enc.cardinality(), 5) def test_even(self): enc = lore.encoders.MiddleOut('test', depth=5) res = enc.transform(pandas.DataFrame({'test': numpy.arange(4) + 1})) self.assertEqual(res.tolist(), [0, 1, 9, 10]) self.assertEqual(enc.cardinality(), 11) def test_odd(self): enc = lore.encoders.MiddleOut('test', depth=5) res = enc.transform(pandas.DataFrame({'test': numpy.arange(5) + 1})) self.assertEqual(res.tolist(), [0, 1, 5, 9, 10]) self.assertEqual(enc.cardinality(), 11) class TestTwins(unittest.TestCase): def test_unique(self): encoder = lore.encoders.Unique('test', twin=True) df = pandas.DataFrame({'test': [1, 2, 3, 4, 5], 'test_twin': [4, 5, 6, 1, 2]}) encoder.fit(df) res = encoder.transform(df) self.assertEqual(res.tolist(), [2, 3, 4, 5, 6, 5, 6, 7, 2, 3]) self.assertEqual(encoder.cardinality(), 9) def test_token(self): encoder = lore.encoders.Token('product_name', sequence_length=3, twin=True) df = pandas.DataFrame({'product_name': ['organic orange juice', 'organic apple juice'], 'product_name_twin': ['healthy orange juice', 'naval orange juice']}) encoder.fit(df) res = encoder.transform(df['product_name']) self.assertEqual(res.reshape(-1).tolist(), [7,6,4,7,2,4]) self.assertEqual(encoder.cardinality(), 9) res = encoder.transform(df['product_name_twin']) self.assertEqual(res.reshape(-1).tolist(), [3, 6, 4, 5, 6, 4]) class TestNestedUnique(unittest.TestCase): @classmethod def setUpClass(cls): cls.encoder = lore.encoders.NestedUnique('test', sequence_length=3) cls.encoder.fit(pandas.DataFrame({'test': [['apple', 'orange', 'carrot']]})) def test_cardinality(self): self.assertEqual(self.encoder.cardinality(), 6) def test_reverse_transform(self): a = [['apple', 'orange', 'carrot'], ['carrot', 'orange', 'apple']] b = self.encoder.reverse_transform( self.encoder.transform(pandas.DataFrame({'test': a})) ).tolist() self.assertEqual(a, b) def test_handles_missing_labels(self): a = [['thisisnotavalidwordintheembeddings'], [float('nan')], None] b = self.encoder.reverse_transform( self.encoder.transform(pandas.DataFrame({'test': a})) ).tolist() self.assertEqual([['LONG_TAIL', 'MISSING_VALUE', 'MISSING_VALUE'], ['MISSING_VALUE', 'MISSING_VALUE', 'MISSING_VALUE'], ['MISSING_VALUE', 'MISSING_VALUE', 'MISSING_VALUE']], b) self.assertEqual(self.encoder.cardinality(), 6) class TestNestedNorm(unittest.TestCase): @classmethod def setUpClass(cls): cls.encoder = lore.encoders.NestedNorm('test', sequence_length=3) cls.encoder.fit(pandas.DataFrame({'test': [[1, 2, 3]]})) def test_reverse_transform(self): a = [[1, 2, 3], [3, 2, 1]] b = self.encoder.reverse_transform( self.encoder.transform(pandas.DataFrame({'test': a})) ).tolist() self.assertEqual(a, b) def test_handles_outliers_and_missing_labels(self): a = [[100], [-100], [float('nan')], None] b = self.encoder.reverse_transform( self.encoder.transform(pandas.DataFrame({'test': a})) ).tolist() self.assertEqual([[3.0, 2.0, 2.0], [1.0, 2.0, 2.0], [2.0, 2.0, 2.0], [2.0, 2.0, 2.0], ], b)
[ "lore.encoders.Norm", "numpy.mean", "numpy.arange", "lore.encoders.Enum", "pandas.DataFrame", "lore.encoders.Token", "numpy.std", "lore.encoders.Discrete", "lore.encoders.NestedUnique", "lore.encoders.NestedNorm", "lore.encoders.Uniform", "lore.encoders.MiddleOut", "datetime.datetime", "lo...
[((247, 284), 'lore.encoders.Equals', 'lore.encoders.Equals', (['"""left"""', '"""right"""'], {}), "('left', 'right')\n", (267, 284), False, 'import lore\n'), ((330, 402), 'pandas.DataFrame', 'pandas.DataFrame', (["{'left': [None, 1, 2, 2], 'right': [None, None, 1, 2]}"], {}), "({'left': [None, 1, 2, 2], 'right': [None, None, 1, 2]})\n", (346, 402), False, 'import pandas\n'), ((755, 784), 'lore.encoders.Uniform', 'lore.encoders.Uniform', (['"""test"""'], {}), "('test')\n", (776, 784), False, 'import lore\n'), ((1602, 1631), 'lore.encoders.Uniform', 'lore.encoders.Uniform', (['"""test"""'], {}), "('test')\n", (1623, 1631), False, 'import lore\n'), ((1923, 1970), 'lore.encoders.Norm', 'lore.encoders.Norm', (['"""test"""'], {'dtype': 'numpy.float64'}), "('test', dtype=numpy.float64)\n", (1941, 1970), False, 'import lore\n'), ((2024, 2042), 'numpy.mean', 'numpy.mean', (['self.x'], {}), '(self.x)\n', (2034, 2042), False, 'import numpy\n'), ((2062, 2079), 'numpy.std', 'numpy.std', (['self.x'], {}), '(self.x)\n', (2071, 2079), False, 'import numpy\n'), ((2182, 2198), 'numpy.arange', 'numpy.arange', (['(10)'], {}), '(10)\n', (2194, 2198), False, 'import numpy\n'), ((2213, 2260), 'lore.encoders.Norm', 'lore.encoders.Norm', (['"""test"""'], {'dtype': 'numpy.float64'}), "('test', dtype=numpy.float64)\n", (2231, 2260), False, 'import lore\n'), ((2276, 2305), 'pandas.DataFrame', 'pandas.DataFrame', (["{'test': a}"], {}), "({'test': a})\n", (2292, 2305), False, 'import pandas\n'), ((3304, 3330), 'lore.encoders.Norm', 'lore.encoders.Norm', (['"""test"""'], {}), "('test')\n", (3322, 3330), False, 'import lore\n'), ((3624, 3650), 'lore.encoders.Norm', 'lore.encoders.Norm', (['"""test"""'], {}), "('test')\n", (3642, 3650), False, 'import lore\n'), ((3921, 3959), 'lore.encoders.Discrete', 'lore.encoders.Discrete', (['"""test"""'], {'bins': '(5)'}), "('test', bins=5)\n", (3943, 3959), False, 'import lore\n'), ((4764, 4802), 'lore.encoders.Discrete', 'lore.encoders.Discrete', (['"""test"""'], {'bins': '(5)'}), "('test', bins=5)\n", (4786, 4802), False, 'import lore\n'), ((5313, 5342), 'lore.encoders.Boolean', 'lore.encoders.Boolean', (['"""test"""'], {}), "('test')\n", (5334, 5342), False, 'import lore\n'), ((5766, 5792), 'lore.encoders.Enum', 'lore.encoders.Enum', (['"""test"""'], {}), "('test')\n", (5784, 5792), False, 'import lore\n'), ((6224, 6250), 'lore.encoders.Enum', 'lore.encoders.Enum', (['"""test"""'], {}), "('test')\n", (6242, 6250), False, 'import lore\n'), ((6779, 6822), 'lore.encoders.Quantile', 'lore.encoders.Quantile', (['"""test"""'], {'quantiles': '(5)'}), "('test', quantiles=5)\n", (6801, 6822), False, 'import lore\n'), ((8127, 8155), 'lore.encoders.Unique', 'lore.encoders.Unique', (['"""test"""'], {}), "('test')\n", (8147, 8155), False, 'import lore\n'), ((8372, 8421), 'pandas.DataFrame', 'pandas.DataFrame', (["{'test': ['a', 'b', 'e', None]}"], {}), "({'test': ['a', 'b', 'e', None]})\n", (8388, 8421), False, 'import pandas\n'), ((8576, 8627), 'lore.encoders.Unique', 'lore.encoders.Unique', (['"""test"""'], {'minimum_occurrences': '(2)'}), "('test', minimum_occurrences=2)\n", (8596, 8627), False, 'import lore\n'), ((9578, 9649), 'lore.encoders.Unique', 'lore.encoders.Unique', (['"""test"""'], {'stratify': '"""user_id"""', 'minimum_occurrences': '(2)'}), "('test', stratify='user_id', minimum_occurrences=2)\n", (9598, 9649), False, 'import lore\n'), ((9962, 9990), 'lore.encoders.OneHot', 'lore.encoders.OneHot', (['"""test"""'], {}), "('test')\n", (9982, 9990), False, 'import lore\n'), ((10345, 10365), 'numpy.zeros', 'numpy.zeros', (['(10, 3)'], {}), '((10, 3))\n', (10356, 10365), False, 'import numpy\n'), ((10660, 10728), 'lore.encoders.OneHot', 'lore.encoders.OneHot', (['"""test"""'], {'compressed': '(True)', 'minimum_occurrences': '(2)'}), "('test', compressed=True, minimum_occurrences=2)\n", (10680, 10728), False, 'import lore\n'), ((10850, 10870), 'numpy.zeros', 'numpy.zeros', (['(10, 2)'], {}), '((10, 2))\n', (10861, 10870), False, 'import numpy\n'), ((11217, 11263), 'lore.encoders.Token', 'lore.encoders.Token', (['"""test"""'], {'sequence_length': '(3)'}), "('test', sequence_length=3)\n", (11236, 11263), False, 'import lore\n'), ((12540, 12580), 'lore.encoders.MiddleOut', 'lore.encoders.MiddleOut', (['"""test"""'], {'depth': '(2)'}), "('test', depth=2)\n", (12563, 12580), False, 'import lore\n'), ((12810, 12850), 'lore.encoders.MiddleOut', 'lore.encoders.MiddleOut', (['"""test"""'], {'depth': '(5)'}), "('test', depth=5)\n", (12833, 12850), False, 'import lore\n'), ((13069, 13109), 'lore.encoders.MiddleOut', 'lore.encoders.MiddleOut', (['"""test"""'], {'depth': '(5)'}), "('test', depth=5)\n", (13092, 13109), False, 'import lore\n'), ((13374, 13413), 'lore.encoders.Unique', 'lore.encoders.Unique', (['"""test"""'], {'twin': '(True)'}), "('test', twin=True)\n", (13394, 13413), False, 'import lore\n'), ((13427, 13500), 'pandas.DataFrame', 'pandas.DataFrame', (["{'test': [1, 2, 3, 4, 5], 'test_twin': [4, 5, 6, 1, 2]}"], {}), "({'test': [1, 2, 3, 4, 5], 'test_twin': [4, 5, 6, 1, 2]})\n", (13443, 13500), False, 'import pandas\n'), ((13728, 13793), 'lore.encoders.Token', 'lore.encoders.Token', (['"""product_name"""'], {'sequence_length': '(3)', 'twin': '(True)'}), "('product_name', sequence_length=3, twin=True)\n", (13747, 13793), False, 'import lore\n'), ((13807, 13967), 'pandas.DataFrame', 'pandas.DataFrame', (["{'product_name': ['organic orange juice', 'organic apple juice'],\n 'product_name_twin': ['healthy orange juice', 'naval orange juice']}"], {}), "({'product_name': ['organic orange juice',\n 'organic apple juice'], 'product_name_twin': ['healthy orange juice',\n 'naval orange juice']})\n", (13823, 13967), False, 'import pandas\n'), ((14390, 14443), 'lore.encoders.NestedUnique', 'lore.encoders.NestedUnique', (['"""test"""'], {'sequence_length': '(3)'}), "('test', sequence_length=3)\n", (14416, 14443), False, 'import lore\n'), ((15540, 15591), 'lore.encoders.NestedNorm', 'lore.encoders.NestedNorm', (['"""test"""'], {'sequence_length': '(3)'}), "('test', sequence_length=3)\n", (15564, 15591), False, 'import lore\n'), ((810, 853), 'pandas.DataFrame', 'pandas.DataFrame', (["{'test': [3, 1, 2, 1, 4]}"], {}), "({'test': [3, 1, 2, 1, 4]})\n", (826, 853), False, 'import pandas\n'), ((1657, 1706), 'pandas.DataFrame', 'pandas.DataFrame', (["{'test': [3, 1, 2, 1, 4, None]}"], {}), "({'test': [3, 1, 2, 1, 4, None]})\n", (1673, 1706), False, 'import pandas\n'), ((2105, 2139), 'pandas.DataFrame', 'pandas.DataFrame', (["{'test': self.x}"], {}), "({'test': self.x})\n", (2121, 2139), False, 'import pandas\n'), ((2391, 2404), 'numpy.mean', 'numpy.mean', (['b'], {}), '(b)\n', (2401, 2404), False, 'import numpy\n'), ((2440, 2452), 'numpy.std', 'numpy.std', (['b'], {}), '(b)\n', (2449, 2452), False, 'import numpy\n'), ((3356, 3405), 'pandas.DataFrame', 'pandas.DataFrame', (["{'test': [3, 1, 2, 1, 4, None]}"], {}), "({'test': [3, 1, 2, 1, 4, None]})\n", (3372, 3405), False, 'import pandas\n'), ((3676, 3719), 'pandas.DataFrame', 'pandas.DataFrame', (["{'test': [3, 1, 2, 1, 4]}"], {}), "({'test': [3, 1, 2, 1, 4]})\n", (3692, 3719), False, 'import pandas\n'), ((3756, 3790), 'pandas.DataFrame', 'pandas.DataFrame', (["{'test': [None]}"], {}), "({'test': [None]})\n", (3772, 3790), False, 'import pandas\n'), ((3985, 4019), 'pandas.DataFrame', 'pandas.DataFrame', (["{'test': [0, 4]}"], {}), "({'test': [0, 4]})\n", (4001, 4019), False, 'import pandas\n'), ((4171, 4214), 'pandas.DataFrame', 'pandas.DataFrame', (["{'test': [0, 1, 2, 3, 4]}"], {}), "({'test': [0, 1, 2, 3, 4]})\n", (4187, 4214), False, 'import pandas\n'), ((4348, 4416), 'pandas.DataFrame', 'pandas.DataFrame', (["{'test': [0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5]}"], {}), "({'test': [0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5]})\n", (4364, 4416), False, 'import pandas\n'), ((4818, 4835), 'datetime.datetime', 'datetime', (['(1)', '(1)', '(1)'], {}), '(1, 1, 1)\n', (4826, 4835), False, 'from datetime import datetime\n'), ((4837, 4854), 'datetime.datetime', 'datetime', (['(5)', '(5)', '(5)'], {}), '(5, 5, 5)\n', (4845, 4854), False, 'from datetime import datetime\n'), ((4881, 4912), 'pandas.DataFrame', 'pandas.DataFrame', (["{'test': fit}"], {}), "({'test': fit})\n", (4897, 4912), False, 'import pandas\n'), ((4943, 4960), 'datetime.datetime', 'datetime', (['(1)', '(1)', '(1)'], {}), '(1, 1, 1)\n', (4951, 4960), False, 'from datetime import datetime\n'), ((4974, 4991), 'datetime.datetime', 'datetime', (['(2)', '(2)', '(2)'], {}), '(2, 2, 2)\n', (4982, 4991), False, 'from datetime import datetime\n'), ((5005, 5022), 'datetime.datetime', 'datetime', (['(3)', '(3)', '(3)'], {}), '(3, 3, 3)\n', (5013, 5022), False, 'from datetime import datetime\n'), ((5036, 5053), 'datetime.datetime', 'datetime', (['(4)', '(4)', '(4)'], {}), '(4, 4, 4)\n', (5044, 5053), False, 'from datetime import datetime\n'), ((5067, 5084), 'datetime.datetime', 'datetime', (['(5)', '(5)', '(5)'], {}), '(5, 5, 5)\n', (5075, 5084), False, 'from datetime import datetime\n'), ((5131, 5163), 'pandas.DataFrame', 'pandas.DataFrame', (["{'test': test}"], {}), "({'test': test})\n", (5147, 5163), False, 'import pandas\n'), ((5818, 5855), 'pandas.DataFrame', 'pandas.DataFrame', (["{'test': [0, 1, 4]}"], {}), "({'test': [0, 1, 4]})\n", (5834, 5855), False, 'import pandas\n'), ((6276, 6325), 'pandas.DataFrame', 'pandas.DataFrame', (["{'test': [3, 1, 2, 1, 4, None]}"], {}), "({'test': [3, 1, 2, 1, 4, None]})\n", (6292, 6325), False, 'import pandas\n'), ((6848, 6925), 'pandas.DataFrame', 'pandas.DataFrame', (["{'test': [1, 2, 3, 4, 5, 6, 10, 20, 30, 40, 50, 100, 1000]}"], {}), "({'test': [1, 2, 3, 4, 5, 6, 10, 20, 30, 40, 50, 100, 1000]})\n", (6864, 6925), False, 'import pandas\n'), ((7307, 7366), 'pandas.DataFrame', 'pandas.DataFrame', (["{'test': [1, 1, 1, 1, 1, 1, 1, 1, 9, 10]}"], {}), "({'test': [1, 1, 1, 1, 1, 1, 1, 1, 9, 10]})\n", (7323, 7366), False, 'import pandas\n'), ((8181, 8234), 'pandas.DataFrame', 'pandas.DataFrame', (["{'test': ['a', 'b', 'd', 'c', 'b']}"], {}), "({'test': ['a', 'b', 'd', 'c', 'b']})\n", (8197, 8234), False, 'import pandas\n'), ((8653, 8706), 'pandas.DataFrame', 'pandas.DataFrame', (["{'test': ['a', 'b', 'd', 'c', 'b']}"], {}), "({'test': ['a', 'b', 'd', 'c', 'b']})\n", (8669, 8706), False, 'import pandas\n'), ((9683, 9776), 'pandas.DataFrame', 'pandas.DataFrame', (["{'test': ['a', 'b', 'd', 'c', 'b', 'a'], 'user_id': [0, 1, 2, 3, 4, 0]}"], {}), "({'test': ['a', 'b', 'd', 'c', 'b', 'a'], 'user_id': [0, 1,\n 2, 3, 4, 0]})\n", (9699, 9776), False, 'import pandas\n'), ((11288, 11342), 'pandas.DataFrame', 'pandas.DataFrame', (["{'test': ['apple, !orange! carrot']}"], {}), "({'test': ['apple, !orange! carrot']})\n", (11304, 11342), False, 'import pandas\n'), ((14468, 14527), 'pandas.DataFrame', 'pandas.DataFrame', (["{'test': [['apple', 'orange', 'carrot']]}"], {}), "({'test': [['apple', 'orange', 'carrot']]})\n", (14484, 14527), False, 'import pandas\n'), ((15616, 15655), 'pandas.DataFrame', 'pandas.DataFrame', (["{'test': [[1, 2, 3]]}"], {}), "({'test': [[1, 2, 3]]})\n", (15632, 15655), False, 'import pandas\n'), ((6037, 6074), 'pandas.DataFrame', 'pandas.DataFrame', (["{'test': [100, -1]}"], {}), "({'test': [100, -1]})\n", (6053, 6074), False, 'import pandas\n'), ((1092, 1121), 'pandas.DataFrame', 'pandas.DataFrame', (["{'test': a}"], {}), "({'test': a})\n", (1108, 1121), False, 'import pandas\n'), ((2694, 2723), 'pandas.DataFrame', 'pandas.DataFrame', (["{'test': a}"], {}), "({'test': a})\n", (2710, 2723), False, 'import pandas\n'), ((8843, 8892), 'pandas.DataFrame', 'pandas.DataFrame', (["{'test': ['a', 'notafitlabel']}"], {}), "({'test': ['a', 'notafitlabel']})\n", (8859, 8892), False, 'import pandas\n'), ((9115, 9144), 'pandas.DataFrame', 'pandas.DataFrame', (["{'test': a}"], {}), "({'test': a})\n", (9131, 9144), False, 'import pandas\n'), ((9352, 9381), 'pandas.DataFrame', 'pandas.DataFrame', (["{'test': a}"], {}), "({'test': a})\n", (9368, 9381), False, 'import pandas\n'), ((11610, 11639), 'pandas.DataFrame', 'pandas.DataFrame', (["{'test': a}"], {}), "({'test': a})\n", (11626, 11639), False, 'import pandas\n'), ((11819, 11848), 'pandas.DataFrame', 'pandas.DataFrame', (["{'test': a}"], {}), "({'test': a})\n", (11835, 11848), False, 'import pandas\n'), ((12138, 12167), 'pandas.DataFrame', 'pandas.DataFrame', (["{'test': a}"], {}), "({'test': a})\n", (12154, 12167), False, 'import pandas\n'), ((12635, 12650), 'numpy.arange', 'numpy.arange', (['(8)'], {}), '(8)\n', (12647, 12650), False, 'import numpy\n'), ((12905, 12920), 'numpy.arange', 'numpy.arange', (['(4)'], {}), '(4)\n', (12917, 12920), False, 'import numpy\n'), ((13164, 13179), 'numpy.arange', 'numpy.arange', (['(5)'], {}), '(5)\n', (13176, 13179), False, 'import numpy\n'), ((14811, 14840), 'pandas.DataFrame', 'pandas.DataFrame', (["{'test': a}"], {}), "({'test': a})\n", (14827, 14840), False, 'import pandas\n'), ((15090, 15119), 'pandas.DataFrame', 'pandas.DataFrame', (["{'test': a}"], {}), "({'test': a})\n", (15106, 15119), False, 'import pandas\n'), ((15810, 15839), 'pandas.DataFrame', 'pandas.DataFrame', (["{'test': a}"], {}), "({'test': a})\n", (15826, 15839), False, 'import pandas\n'), ((16077, 16106), 'pandas.DataFrame', 'pandas.DataFrame', (["{'test': a}"], {}), "({'test': a})\n", (16093, 16106), False, 'import pandas\n')]
""" Analytical equation of motions for a wind turbine using 1 degree of freedom: - flexible fore-aft tower """ import numpy as np import unittest from sympy import Symbol from sympy.physics.mechanics import dynamicsymbols from sympy.parsing.sympy_parser import parse_expr from welib.yams.models.FTNSB_sympy import get_model from welib.yams.models.FTNSB_sympy_symbols import * def main(unittest=False): # 'rot_elastic_type':'Body', #<<< Very important, SmallRot, or Body, will affect the rotation matrix # 'rot_elastic_subs':True, #<<< Very important, will substitute alpha_y with nuy q. Recommended True # 'rot_elastic_smallAngle':False,#<<< Very important, will perform small angle approx: sin(nu q) = nu q and nu^2=0 !!! Will remove all nu^2 and nu^3 terms!! might not be recommended # 'orderMM':2, #< order of taylor expansion for Mass Matrix # 'orderH':2, #< order of taylor expansion for H term model = get_model('F0T1RNA', mergeFndTwr=True, yaw='zero', tilt='fixed', tiltShaft=False, rot_elastic_type='SmallRot', rot_elastic_smallAngle=True, aero_torques=True ) model.kaneEquations() extraSubs=model.shapeNormSubs model.smallAngleApprox(model.smallAngles, extraSubs) return model class TestF0T1RNA(unittest.TestCase): def test_F0T1RNA(self): """ Test expression of mass and forcing """ model=main(unittest=True) twr=model.twr import sys if sys.version_info.major < 3 : print('>>>> Skipping test for python 2, due to sign error') return # --- Mass matrix MM = model._sa_mass_matrix MM_noTwr= parse_expr('Matrix([[-2*M_RNA*v_yT1c*(x_RNAG*sin(theta_tilt) - z_RNAG*cos(theta_tilt)) + M_RNA]])')# M_e^0_T_11 + M_e^1_1_T_11*q_T1(t) MM_twr = model.twr.MM #print('MM',MM) #print('MM_noT',MM_noTwr) #print('MM_twr',MM_twr) #MM_twr = twr.Me.eval(twr.q) DMM = MM-MM_twr-MM_noTwr DMM.simplify() #print('DMM') self.assertEqual(DMM[0,0],0) # forcing FF = model._sa_forcing[0,0].subs([(dynamicsymbols('g'),Symbol('g')),(dynamicsymbols('T_a'),Symbol('T_a')), ]) #forcing1=parse_expr('-D_e^0_T_11*Derivative(q_T1(t), t) - K_e^0_T_11*q_T1(t)') forcing1 = twr.bodyElasticForce(twr.q, twr.qdot)[6,0] forcing2 = parse_expr('T_a*cos(theta_tilt) + v_yT1c*(M_RNA*g*x_RNAG*cos(theta_tilt) + M_RNA*g*z_RNAG*sin(theta_tilt) + T_a*z_NR - T_a*q_T1(t)*sin(theta_tilt) + M_y_a(t))') #print('ff ',FF) #print('forcing 1',forcing1) #print('forcing 2',forcing2) DFF = FF-forcing2+forcing1 DFF = DFF.simplify() #print('DFF',DFF) self.assertEqual(DFF,0) if __name__=='__main__': np.set_printoptions(linewidth=500) #main(unittest=False) unittest.main()
[ "unittest.main", "sympy.Symbol", "sympy.physics.mechanics.dynamicsymbols", "numpy.set_printoptions", "welib.yams.models.FTNSB_sympy.get_model", "sympy.parsing.sympy_parser.parse_expr" ]
[((952, 1119), 'welib.yams.models.FTNSB_sympy.get_model', 'get_model', (['"""F0T1RNA"""'], {'mergeFndTwr': '(True)', 'yaw': '"""zero"""', 'tilt': '"""fixed"""', 'tiltShaft': '(False)', 'rot_elastic_type': '"""SmallRot"""', 'rot_elastic_smallAngle': '(True)', 'aero_torques': '(True)'}), "('F0T1RNA', mergeFndTwr=True, yaw='zero', tilt='fixed', tiltShaft=\n False, rot_elastic_type='SmallRot', rot_elastic_smallAngle=True,\n aero_torques=True)\n", (961, 1119), False, 'from welib.yams.models.FTNSB_sympy import get_model\n'), ((2861, 2895), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'linewidth': '(500)'}), '(linewidth=500)\n', (2880, 2895), True, 'import numpy as np\n'), ((2926, 2941), 'unittest.main', 'unittest.main', ([], {}), '()\n', (2939, 2941), False, 'import unittest\n'), ((1723, 1832), 'sympy.parsing.sympy_parser.parse_expr', 'parse_expr', (['"""Matrix([[-2*M_RNA*v_yT1c*(x_RNAG*sin(theta_tilt) - z_RNAG*cos(theta_tilt)) + M_RNA]])"""'], {}), "(\n 'Matrix([[-2*M_RNA*v_yT1c*(x_RNAG*sin(theta_tilt) - z_RNAG*cos(theta_tilt)) + M_RNA]])'\n )\n", (1733, 1832), False, 'from sympy.parsing.sympy_parser import parse_expr\n'), ((2439, 2609), 'sympy.parsing.sympy_parser.parse_expr', 'parse_expr', (['"""T_a*cos(theta_tilt) + v_yT1c*(M_RNA*g*x_RNAG*cos(theta_tilt) + M_RNA*g*z_RNAG*sin(theta_tilt) + T_a*z_NR - T_a*q_T1(t)*sin(theta_tilt) + M_y_a(t))"""'], {}), "(\n 'T_a*cos(theta_tilt) + v_yT1c*(M_RNA*g*x_RNAG*cos(theta_tilt) + M_RNA*g*z_RNAG*sin(theta_tilt) + T_a*z_NR - T_a*q_T1(t)*sin(theta_tilt) + M_y_a(t))'\n )\n", (2449, 2609), False, 'from sympy.parsing.sympy_parser import parse_expr\n'), ((2195, 2214), 'sympy.physics.mechanics.dynamicsymbols', 'dynamicsymbols', (['"""g"""'], {}), "('g')\n", (2209, 2214), False, 'from sympy.physics.mechanics import dynamicsymbols\n'), ((2215, 2226), 'sympy.Symbol', 'Symbol', (['"""g"""'], {}), "('g')\n", (2221, 2226), False, 'from sympy import Symbol\n'), ((2229, 2250), 'sympy.physics.mechanics.dynamicsymbols', 'dynamicsymbols', (['"""T_a"""'], {}), "('T_a')\n", (2243, 2250), False, 'from sympy.physics.mechanics import dynamicsymbols\n'), ((2251, 2264), 'sympy.Symbol', 'Symbol', (['"""T_a"""'], {}), "('T_a')\n", (2257, 2264), False, 'from sympy import Symbol\n')]
import numpy as np import pytest from pandas import ( Timedelta, timedelta_range, to_timedelta, ) import pandas._testing as tm from pandas.tseries.offsets import ( Day, Second, ) class TestTimedeltas: def test_timedelta_range(self): expected = to_timedelta(np.arange(5), unit="D") result = timedelta_range("0 days", periods=5, freq="D") tm.assert_index_equal(result, expected) expected = to_timedelta(np.arange(11), unit="D") result = timedelta_range("0 days", "10 days", freq="D") tm.assert_index_equal(result, expected) expected = to_timedelta(np.arange(5), unit="D") + Second(2) + Day() result = timedelta_range("1 days, 00:00:02", "5 days, 00:00:02", freq="D") tm.assert_index_equal(result, expected) expected = to_timedelta([1, 3, 5, 7, 9], unit="D") + Second(2) result = timedelta_range("1 days, 00:00:02", periods=5, freq="2D") tm.assert_index_equal(result, expected) expected = to_timedelta(np.arange(50), unit="T") * 30 result = timedelta_range("0 days", freq="30T", periods=50) tm.assert_index_equal(result, expected) @pytest.mark.parametrize( "periods, freq", [(3, "2D"), (5, "D"), (6, "19H12T"), (7, "16H"), (9, "12H")] ) def test_linspace_behavior(self, periods, freq): # GH 20976 result = timedelta_range(start="0 days", end="4 days", periods=periods) expected = timedelta_range(start="0 days", end="4 days", freq=freq) tm.assert_index_equal(result, expected) def test_errors(self): # not enough params msg = ( "Of the four parameters: start, end, periods, and freq, " "exactly three must be specified" ) with pytest.raises(ValueError, match=msg): timedelta_range(start="0 days") with pytest.raises(ValueError, match=msg): timedelta_range(end="5 days") with pytest.raises(ValueError, match=msg): timedelta_range(periods=2) with pytest.raises(ValueError, match=msg): timedelta_range() # too many params with pytest.raises(ValueError, match=msg): timedelta_range(start="0 days", end="5 days", periods=10, freq="H") @pytest.mark.parametrize( "start, end, freq, expected_periods", [ ("1D", "10D", "2D", (10 - 1) // 2 + 1), ("2D", "30D", "3D", (30 - 2) // 3 + 1), ("2s", "50s", "5s", (50 - 2) // 5 + 1), # tests that worked before GH 33498: ("4D", "16D", "3D", (16 - 4) // 3 + 1), ("8D", "16D", "40s", (16 * 3600 * 24 - 8 * 3600 * 24) // 40 + 1), ], ) def test_timedelta_range_freq_divide_end(self, start, end, freq, expected_periods): # GH 33498 only the cases where `(end % freq) == 0` used to fail res = timedelta_range(start=start, end=end, freq=freq) assert Timedelta(start) == res[0] assert Timedelta(end) >= res[-1] assert len(res) == expected_periods def test_timedelta_range_infer_freq(self): # https://github.com/pandas-dev/pandas/issues/35897 result = timedelta_range("0s", "1s", periods=31) assert result.freq is None
[ "pandas.timedelta_range", "pandas.tseries.offsets.Day", "pandas.tseries.offsets.Second", "pytest.raises", "pandas.to_timedelta", "pandas._testing.assert_index_equal", "numpy.arange", "pandas.Timedelta", "pytest.mark.parametrize" ]
[((1187, 1294), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""periods, freq"""', "[(3, '2D'), (5, 'D'), (6, '19H12T'), (7, '16H'), (9, '12H')]"], {}), "('periods, freq', [(3, '2D'), (5, 'D'), (6, '19H12T'\n ), (7, '16H'), (9, '12H')])\n", (1210, 1294), False, 'import pytest\n'), ((2304, 2605), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""start, end, freq, expected_periods"""', "[('1D', '10D', '2D', (10 - 1) // 2 + 1), ('2D', '30D', '3D', (30 - 2) // 3 +\n 1), ('2s', '50s', '5s', (50 - 2) // 5 + 1), ('4D', '16D', '3D', (16 - 4\n ) // 3 + 1), ('8D', '16D', '40s', (16 * 3600 * 24 - 8 * 3600 * 24) // \n 40 + 1)]"], {}), "('start, end, freq, expected_periods', [('1D', '10D',\n '2D', (10 - 1) // 2 + 1), ('2D', '30D', '3D', (30 - 2) // 3 + 1), ('2s',\n '50s', '5s', (50 - 2) // 5 + 1), ('4D', '16D', '3D', (16 - 4) // 3 + 1),\n ('8D', '16D', '40s', (16 * 3600 * 24 - 8 * 3600 * 24) // 40 + 1)])\n", (2327, 2605), False, 'import pytest\n'), ((335, 381), 'pandas.timedelta_range', 'timedelta_range', (['"""0 days"""'], {'periods': '(5)', 'freq': '"""D"""'}), "('0 days', periods=5, freq='D')\n", (350, 381), False, 'from pandas import Timedelta, timedelta_range, to_timedelta\n'), ((390, 429), 'pandas._testing.assert_index_equal', 'tm.assert_index_equal', (['result', 'expected'], {}), '(result, expected)\n', (411, 429), True, 'import pandas._testing as tm\n'), ((505, 551), 'pandas.timedelta_range', 'timedelta_range', (['"""0 days"""', '"""10 days"""'], {'freq': '"""D"""'}), "('0 days', '10 days', freq='D')\n", (520, 551), False, 'from pandas import Timedelta, timedelta_range, to_timedelta\n'), ((560, 599), 'pandas._testing.assert_index_equal', 'tm.assert_index_equal', (['result', 'expected'], {}), '(result, expected)\n', (581, 599), True, 'import pandas._testing as tm\n'), ((694, 759), 'pandas.timedelta_range', 'timedelta_range', (['"""1 days, 00:00:02"""', '"""5 days, 00:00:02"""'], {'freq': '"""D"""'}), "('1 days, 00:00:02', '5 days, 00:00:02', freq='D')\n", (709, 759), False, 'from pandas import Timedelta, timedelta_range, to_timedelta\n'), ((768, 807), 'pandas._testing.assert_index_equal', 'tm.assert_index_equal', (['result', 'expected'], {}), '(result, expected)\n', (789, 807), True, 'import pandas._testing as tm\n'), ((897, 954), 'pandas.timedelta_range', 'timedelta_range', (['"""1 days, 00:00:02"""'], {'periods': '(5)', 'freq': '"""2D"""'}), "('1 days, 00:00:02', periods=5, freq='2D')\n", (912, 954), False, 'from pandas import Timedelta, timedelta_range, to_timedelta\n'), ((963, 1002), 'pandas._testing.assert_index_equal', 'tm.assert_index_equal', (['result', 'expected'], {}), '(result, expected)\n', (984, 1002), True, 'import pandas._testing as tm\n'), ((1083, 1132), 'pandas.timedelta_range', 'timedelta_range', (['"""0 days"""'], {'freq': '"""30T"""', 'periods': '(50)'}), "('0 days', freq='30T', periods=50)\n", (1098, 1132), False, 'from pandas import Timedelta, timedelta_range, to_timedelta\n'), ((1141, 1180), 'pandas._testing.assert_index_equal', 'tm.assert_index_equal', (['result', 'expected'], {}), '(result, expected)\n', (1162, 1180), True, 'import pandas._testing as tm\n'), ((1393, 1455), 'pandas.timedelta_range', 'timedelta_range', ([], {'start': '"""0 days"""', 'end': '"""4 days"""', 'periods': 'periods'}), "(start='0 days', end='4 days', periods=periods)\n", (1408, 1455), False, 'from pandas import Timedelta, timedelta_range, to_timedelta\n'), ((1475, 1531), 'pandas.timedelta_range', 'timedelta_range', ([], {'start': '"""0 days"""', 'end': '"""4 days"""', 'freq': 'freq'}), "(start='0 days', end='4 days', freq=freq)\n", (1490, 1531), False, 'from pandas import Timedelta, timedelta_range, to_timedelta\n'), ((1540, 1579), 'pandas._testing.assert_index_equal', 'tm.assert_index_equal', (['result', 'expected'], {}), '(result, expected)\n', (1561, 1579), True, 'import pandas._testing as tm\n'), ((2912, 2960), 'pandas.timedelta_range', 'timedelta_range', ([], {'start': 'start', 'end': 'end', 'freq': 'freq'}), '(start=start, end=end, freq=freq)\n', (2927, 2960), False, 'from pandas import Timedelta, timedelta_range, to_timedelta\n'), ((3213, 3252), 'pandas.timedelta_range', 'timedelta_range', (['"""0s"""', '"""1s"""'], {'periods': '(31)'}), "('0s', '1s', periods=31)\n", (3228, 3252), False, 'from pandas import Timedelta, timedelta_range, to_timedelta\n'), ((294, 306), 'numpy.arange', 'np.arange', (['(5)'], {}), '(5)\n', (303, 306), True, 'import numpy as np\n'), ((463, 476), 'numpy.arange', 'np.arange', (['(11)'], {}), '(11)\n', (472, 476), True, 'import numpy as np\n'), ((671, 676), 'pandas.tseries.offsets.Day', 'Day', ([], {}), '()\n', (674, 676), False, 'from pandas.tseries.offsets import Day, Second\n'), ((828, 867), 'pandas.to_timedelta', 'to_timedelta', (['[1, 3, 5, 7, 9]'], {'unit': '"""D"""'}), "([1, 3, 5, 7, 9], unit='D')\n", (840, 867), False, 'from pandas import Timedelta, timedelta_range, to_timedelta\n'), ((870, 879), 'pandas.tseries.offsets.Second', 'Second', (['(2)'], {}), '(2)\n', (876, 879), False, 'from pandas.tseries.offsets import Day, Second\n'), ((1791, 1827), 'pytest.raises', 'pytest.raises', (['ValueError'], {'match': 'msg'}), '(ValueError, match=msg)\n', (1804, 1827), False, 'import pytest\n'), ((1841, 1872), 'pandas.timedelta_range', 'timedelta_range', ([], {'start': '"""0 days"""'}), "(start='0 days')\n", (1856, 1872), False, 'from pandas import Timedelta, timedelta_range, to_timedelta\n'), ((1887, 1923), 'pytest.raises', 'pytest.raises', (['ValueError'], {'match': 'msg'}), '(ValueError, match=msg)\n', (1900, 1923), False, 'import pytest\n'), ((1937, 1966), 'pandas.timedelta_range', 'timedelta_range', ([], {'end': '"""5 days"""'}), "(end='5 days')\n", (1952, 1966), False, 'from pandas import Timedelta, timedelta_range, to_timedelta\n'), ((1981, 2017), 'pytest.raises', 'pytest.raises', (['ValueError'], {'match': 'msg'}), '(ValueError, match=msg)\n', (1994, 2017), False, 'import pytest\n'), ((2031, 2057), 'pandas.timedelta_range', 'timedelta_range', ([], {'periods': '(2)'}), '(periods=2)\n', (2046, 2057), False, 'from pandas import Timedelta, timedelta_range, to_timedelta\n'), ((2072, 2108), 'pytest.raises', 'pytest.raises', (['ValueError'], {'match': 'msg'}), '(ValueError, match=msg)\n', (2085, 2108), False, 'import pytest\n'), ((2122, 2139), 'pandas.timedelta_range', 'timedelta_range', ([], {}), '()\n', (2137, 2139), False, 'from pandas import Timedelta, timedelta_range, to_timedelta\n'), ((2180, 2216), 'pytest.raises', 'pytest.raises', (['ValueError'], {'match': 'msg'}), '(ValueError, match=msg)\n', (2193, 2216), False, 'import pytest\n'), ((2230, 2297), 'pandas.timedelta_range', 'timedelta_range', ([], {'start': '"""0 days"""', 'end': '"""5 days"""', 'periods': '(10)', 'freq': '"""H"""'}), "(start='0 days', end='5 days', periods=10, freq='H')\n", (2245, 2297), False, 'from pandas import Timedelta, timedelta_range, to_timedelta\n'), ((2976, 2992), 'pandas.Timedelta', 'Timedelta', (['start'], {}), '(start)\n', (2985, 2992), False, 'from pandas import Timedelta, timedelta_range, to_timedelta\n'), ((3018, 3032), 'pandas.Timedelta', 'Timedelta', (['end'], {}), '(end)\n', (3027, 3032), False, 'from pandas import Timedelta, timedelta_range, to_timedelta\n'), ((659, 668), 'pandas.tseries.offsets.Second', 'Second', (['(2)'], {}), '(2)\n', (665, 668), False, 'from pandas.tseries.offsets import Day, Second\n'), ((1036, 1049), 'numpy.arange', 'np.arange', (['(50)'], {}), '(50)\n', (1045, 1049), True, 'import numpy as np\n'), ((633, 645), 'numpy.arange', 'np.arange', (['(5)'], {}), '(5)\n', (642, 645), True, 'import numpy as np\n')]
import numpy as np from .BaseDeterioration import BaseDeterioration class Markovian(BaseDeterioration): def __init__(self, probs_list): super().__init__() """ The probs_list must contains the transition probabilities of each state ti itself A system of 5 states must have the probs_list of length equal to 5 """ self.probs_list = probs_list def predict_condition(self, previous_condition = 0, t = None, **kwargs): '''To predict the condition rating after one time step given some information''' if np.random.rand() > self.probs_list[previous_condition]: return previous_condition + 1 else: return previous_condition
[ "numpy.random.rand" ]
[((520, 536), 'numpy.random.rand', 'np.random.rand', ([], {}), '()\n', (534, 536), True, 'import numpy as np\n')]
# adapt from https://github.com/bknyaz/graph_attention_pool/blob/master/graphdata.py import numpy as np import os.path as osp import pickle import torch import torch.utils import torch.utils.data import torch.nn.functional as F from scipy.spatial.distance import cdist from torch_geometric.utils import dense_to_sparse from torch_geometric.data import InMemoryDataset, Data import yaml from pathlib import Path from torch_geometric.loader import DataLoader def compute_adjacency_matrix_images(coord, sigma=0.1): coord = coord.reshape(-1, 2) dist = cdist(coord, coord) A = np.exp(- dist / (sigma * np.pi) ** 2) A[np.diag_indices_from(A)] = 0 return A def list_to_torch(data): for i in range(len(data)): if data[i] is None: continue elif isinstance(data[i], np.ndarray): if data[i].dtype == np.bool: data[i] = data[i].astype(np.float32) data[i] = torch.from_numpy(data[i]).float() elif isinstance(data[i], list): data[i] = list_to_torch(data[i]) return data class MNIST75sp(InMemoryDataset): splits = ['test', 'train'] def __init__(self, root, mode='train', use_mean_px=True, use_coord=True, node_gt_att_threshold=0, transform=None, pre_transform=None, pre_filter=None): assert mode in self.splits self.mode = mode self.node_gt_att_threshold = node_gt_att_threshold self.use_mean_px, self.use_coord = use_mean_px, use_coord super(MNIST75sp, self).__init__(root, transform, pre_transform, pre_filter) idx = self.processed_file_names.index('mnist_75sp_{}.pt'.format(mode)) self.data, self.slices = torch.load(self.processed_paths[idx]) @property def raw_file_names(self): return ['mnist_75sp_train.pkl', 'mnist_75sp_test.pkl'] @property def processed_file_names(self): return ['mnist_75sp_train.pt', 'mnist_75sp_test.pt'] def download(self): for file in self.raw_file_names: if not osp.exists(osp.join(self.raw_dir, file)): print("raw data of `{}` doesn't exist, please download from our github.".format(file)) raise FileNotFoundError def process(self): data_file = 'mnist_75sp_%s.pkl' % self.mode with open(osp.join(self.raw_dir, data_file), 'rb') as f: self.labels, self.sp_data = pickle.load(f) sp_file = 'mnist_75sp_%s_superpixels.pkl' % self.mode with open(osp.join(self.raw_dir, sp_file), 'rb') as f: self.all_superpixels = pickle.load(f) self.use_mean_px = self.use_mean_px self.use_coord = self.use_coord self.n_samples = len(self.labels) self.img_size = 28 self.node_gt_att_threshold = self.node_gt_att_threshold self.edge_indices, self.xs, self.edge_attrs, self.node_gt_atts, self.edge_gt_atts = [], [], [], [], [] data_list = [] for index, sample in enumerate(self.sp_data): mean_px, coord, sp_order = sample[:3] superpixels = self.all_superpixels[index] coord = coord / self.img_size A = compute_adjacency_matrix_images(coord) N_nodes = A.shape[0] A = torch.FloatTensor((A > 0.1) * A) edge_index, edge_attr = dense_to_sparse(A) x = None if self.use_mean_px: x = mean_px.reshape(N_nodes, -1) if self.use_coord: coord = coord.reshape(N_nodes, 2) if self.use_mean_px: x = np.concatenate((x, coord), axis=1) else: x = coord if x is None: x = np.ones(N_nodes, 1) # dummy features # replicate features to make it possible to test on colored images x = np.pad(x, ((0, 0), (2, 0)), 'edge') if self.node_gt_att_threshold == 0: node_gt_att = (mean_px > 0).astype(np.float32) else: node_gt_att = mean_px.copy() node_gt_att[node_gt_att < self.node_gt_att_threshold] = 0 node_gt_att = torch.LongTensor(node_gt_att).view(-1) row, col = edge_index edge_gt_att = torch.LongTensor(node_gt_att[row] * node_gt_att[col]).view(-1) data_list.append( Data( x=torch.tensor(x), y=torch.LongTensor([self.labels[index]]), edge_index=edge_index, edge_attr=edge_attr.reshape(-1, 1), node_label=node_gt_att.float(), edge_label=edge_gt_att.float(), sp_order=torch.tensor(sp_order), superpixels=torch.tensor(superpixels), name=f'MNISTSP-{self.mode}-{index}', idx=index ) ) idx = self.processed_file_names.index('mnist_75sp_{}.pt'.format(self.mode)) torch.save(self.collate(data_list), self.processed_paths[idx])
[ "scipy.spatial.distance.cdist", "numpy.pad", "numpy.diag_indices_from", "torch.LongTensor", "torch.load", "torch.FloatTensor", "numpy.ones", "pickle.load", "numpy.exp", "torch.tensor", "torch_geometric.utils.dense_to_sparse", "os.path.join", "numpy.concatenate", "torch.from_numpy" ]
[((560, 579), 'scipy.spatial.distance.cdist', 'cdist', (['coord', 'coord'], {}), '(coord, coord)\n', (565, 579), False, 'from scipy.spatial.distance import cdist\n'), ((588, 624), 'numpy.exp', 'np.exp', (['(-dist / (sigma * np.pi) ** 2)'], {}), '(-dist / (sigma * np.pi) ** 2)\n', (594, 624), True, 'import numpy as np\n'), ((632, 655), 'numpy.diag_indices_from', 'np.diag_indices_from', (['A'], {}), '(A)\n', (652, 655), True, 'import numpy as np\n'), ((1717, 1754), 'torch.load', 'torch.load', (['self.processed_paths[idx]'], {}), '(self.processed_paths[idx])\n', (1727, 1754), False, 'import torch\n'), ((2427, 2441), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (2438, 2441), False, 'import pickle\n'), ((2603, 2617), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (2614, 2617), False, 'import pickle\n'), ((3276, 3308), 'torch.FloatTensor', 'torch.FloatTensor', (['((A > 0.1) * A)'], {}), '((A > 0.1) * A)\n', (3293, 3308), False, 'import torch\n'), ((3345, 3363), 'torch_geometric.utils.dense_to_sparse', 'dense_to_sparse', (['A'], {}), '(A)\n', (3360, 3363), False, 'from torch_geometric.utils import dense_to_sparse\n'), ((3877, 3912), 'numpy.pad', 'np.pad', (['x', '((0, 0), (2, 0))', '"""edge"""'], {}), "(x, ((0, 0), (2, 0)), 'edge')\n", (3883, 3912), True, 'import numpy as np\n'), ((2340, 2373), 'os.path.join', 'osp.join', (['self.raw_dir', 'data_file'], {}), '(self.raw_dir, data_file)\n', (2348, 2373), True, 'import os.path as osp\n'), ((2523, 2554), 'os.path.join', 'osp.join', (['self.raw_dir', 'sp_file'], {}), '(self.raw_dir, sp_file)\n', (2531, 2554), True, 'import os.path as osp\n'), ((3743, 3762), 'numpy.ones', 'np.ones', (['N_nodes', '(1)'], {}), '(N_nodes, 1)\n', (3750, 3762), True, 'import numpy as np\n'), ((2071, 2099), 'os.path.join', 'osp.join', (['self.raw_dir', 'file'], {}), '(self.raw_dir, file)\n', (2079, 2099), True, 'import os.path as osp\n'), ((3610, 3644), 'numpy.concatenate', 'np.concatenate', (['(x, coord)'], {'axis': '(1)'}), '((x, coord), axis=1)\n', (3624, 3644), True, 'import numpy as np\n'), ((4188, 4217), 'torch.LongTensor', 'torch.LongTensor', (['node_gt_att'], {}), '(node_gt_att)\n', (4204, 4217), False, 'import torch\n'), ((4287, 4340), 'torch.LongTensor', 'torch.LongTensor', (['(node_gt_att[row] * node_gt_att[col])'], {}), '(node_gt_att[row] * node_gt_att[col])\n', (4303, 4340), False, 'import torch\n'), ((943, 968), 'torch.from_numpy', 'torch.from_numpy', (['data[i]'], {}), '(data[i])\n', (959, 968), False, 'import torch\n'), ((4425, 4440), 'torch.tensor', 'torch.tensor', (['x'], {}), '(x)\n', (4437, 4440), False, 'import torch\n'), ((4464, 4502), 'torch.LongTensor', 'torch.LongTensor', (['[self.labels[index]]'], {}), '([self.labels[index]])\n', (4480, 4502), False, 'import torch\n'), ((4736, 4758), 'torch.tensor', 'torch.tensor', (['sp_order'], {}), '(sp_order)\n', (4748, 4758), False, 'import torch\n'), ((4792, 4817), 'torch.tensor', 'torch.tensor', (['superpixels'], {}), '(superpixels)\n', (4804, 4817), False, 'import torch\n')]
from typing import Callable, Dict, List, Tuple, cast import Operators as op import Target as ta import numpy as np def toTarget(o: op.Target, weights: Dict[str,float]) -> ta.Target: print("toTarget:", o) terms : List[ta.Term] = [] parameters : Dict[str,float] = {} init: Dict[str,Tuple[ta.Embedding, np.ndarray]] = {} interpretation: Dict[str, Callable[[np.ndarray], np.ndarray]] = {} smax = 0 def makeInterpretation(a:int, b:int) -> Callable[[np.ndarray], np.ndarray]: return lambda x: x[a:b] for k in o.positions: p = o.positions[k] s = o.sizes[k] s2 = p+s if s2 > smax: smax = s2 interpretation[k] = makeInterpretation(p, s2) idMat = np.diag([1.0 for k in range(smax)]) idEmbedding = ta.Embedding("id", idMat) for c in o.components: tag = c.op # getTag() is TERM_OPT, always if tag == op.OPT_TERM_EQ: ntEqu = ta.Equal(c.label, idEmbedding, np.reshape(c.lin, (1, c.lin.shape[0])), np.array([[np.sum(c.cmp)]])) # bad trick terms.append(ntEqu) parameters[c.label] = 1.0 if tag == op.OPT_TERM_GT: ntGt = ta.GreaterThan(c.label, idEmbedding, np.reshape(c.lin, (1, c.lin.shape[0])), np.array([[np.sum(c.cmp)]])) # bad trick terms.append(ntGt) parameters[c.label] = 1.0 if tag == op.OPT_TERM_GT_MAX: # MAX > ... raise Exception("GT_MAX not supported for now") if tag == op.OPT_TERM_LT: ntLt = ta.LessThan(c.label, idEmbedding, np.reshape(c.lin, (1, c.lin.shape[0])), np.array([[np.sum(c.cmp)]])) # bad trick terms.append(ntLt) parameters[c.label] = 1.0 if tag == op.OPT_TERM_GT_MIN: # MIN > ... and remove if 0 ~ print("gt_min", c) pass if tag == op.OPT_TERM_LT_MAX: # MAX < ... => forall x: x < ... print("lt_max", c) pass if tag == op.OPT_TERM_LT_MIN: # MIN < ... raise Exception("LT_MIN not supported for now") if tag == op.OPT_TERM_MAXIMIZE: ntMaximize = ta.Max(c.label, idEmbedding, c.quad, c.lin) terms.append(ntMaximize) parameters[c.label] = 1.0 if tag == op.OPT_TERM_MINIMIZE: ntMinimize = ta.Min(c.label, idEmbedding, c.quad, c.lin) terms.append(ntMinimize) parameters[c.label] = 1.0 bs: List[int] = [] for a in o.annotations: tg = a.getTag() if tg == op.TERM_LABEL: pass if tg == op.TERM_BITSIZE: print("bitsize", a) tgb = cast(op.TermBitsize, a) name = tgb.left ns = "" if name.getTag() == op.TERM_SYMBOL: ns = cast(op.TermSymbol, name).name else: raise Exception("bitsize/symbol/bad format") nb = tgb.right nbits = 0 if nb.getTag() == op.TERM_ATOM: nbits = int(cast(op.TermAtom, nb).atom) else: raise Exception("bitsize/atom/bad format") print(ns, nbits) idx = o.positions[ns] while idx >= len(bs): bs.append(0) bs[idx] = nbits for w in parameters: if w in weights: print(w, "<-", weights[w]) parameters[w] = weights[w] return ta.Target(terms, bs, parameters, init, interpretation) def expressionToTarget(o: op.Term, weights: Dict[str,float]) -> ta.Target: t = op.extractOptTermOrCondition(o) return toTarget(t, weights)
[ "Operators.extractOptTermOrCondition", "Target.Target", "Target.Max", "numpy.sum", "Target.Min", "typing.cast", "Target.Embedding", "numpy.reshape" ]
[((789, 814), 'Target.Embedding', 'ta.Embedding', (['"""id"""', 'idMat'], {}), "('id', idMat)\n", (801, 814), True, 'import Target as ta\n'), ((3408, 3462), 'Target.Target', 'ta.Target', (['terms', 'bs', 'parameters', 'init', 'interpretation'], {}), '(terms, bs, parameters, init, interpretation)\n', (3417, 3462), True, 'import Target as ta\n'), ((3551, 3582), 'Operators.extractOptTermOrCondition', 'op.extractOptTermOrCondition', (['o'], {}), '(o)\n', (3579, 3582), True, 'import Operators as op\n'), ((2126, 2169), 'Target.Max', 'ta.Max', (['c.label', 'idEmbedding', 'c.quad', 'c.lin'], {}), '(c.label, idEmbedding, c.quad, c.lin)\n', (2132, 2169), True, 'import Target as ta\n'), ((2310, 2353), 'Target.Min', 'ta.Min', (['c.label', 'idEmbedding', 'c.quad', 'c.lin'], {}), '(c.label, idEmbedding, c.quad, c.lin)\n', (2316, 2353), True, 'import Target as ta\n'), ((2637, 2660), 'typing.cast', 'cast', (['op.TermBitsize', 'a'], {}), '(op.TermBitsize, a)\n', (2641, 2660), False, 'from typing import Callable, Dict, List, Tuple, cast\n'), ((977, 1015), 'numpy.reshape', 'np.reshape', (['c.lin', '(1, c.lin.shape[0])'], {}), '(c.lin, (1, c.lin.shape[0]))\n', (987, 1015), True, 'import numpy as np\n'), ((1218, 1256), 'numpy.reshape', 'np.reshape', (['c.lin', '(1, c.lin.shape[0])'], {}), '(c.lin, (1, c.lin.shape[0]))\n', (1228, 1256), True, 'import numpy as np\n'), ((1565, 1603), 'numpy.reshape', 'np.reshape', (['c.lin', '(1, c.lin.shape[0])'], {}), '(c.lin, (1, c.lin.shape[0]))\n', (1575, 1603), True, 'import numpy as np\n'), ((2778, 2803), 'typing.cast', 'cast', (['op.TermSymbol', 'name'], {}), '(op.TermSymbol, name)\n', (2782, 2803), False, 'from typing import Callable, Dict, List, Tuple, cast\n'), ((3009, 3030), 'typing.cast', 'cast', (['op.TermAtom', 'nb'], {}), '(op.TermAtom, nb)\n', (3013, 3030), False, 'from typing import Callable, Dict, List, Tuple, cast\n'), ((1028, 1041), 'numpy.sum', 'np.sum', (['c.cmp'], {}), '(c.cmp)\n', (1034, 1041), True, 'import numpy as np\n'), ((1269, 1282), 'numpy.sum', 'np.sum', (['c.cmp'], {}), '(c.cmp)\n', (1275, 1282), True, 'import numpy as np\n'), ((1616, 1629), 'numpy.sum', 'np.sum', (['c.cmp'], {}), '(c.cmp)\n', (1622, 1629), True, 'import numpy as np\n')]
__author__ = '<NAME>, <EMAIL>' #from .timeseries import AR1Environment from pybrain.rl.environments.task import Task from numpy import sign from math import log class MaximizeReturnTask(Task): def getReward(self): # TODO: make sure to check how to combine the returns (sum or product) depending on whether the timeseries is given in price, return or log returns # TODO: also, MUST check whether the reward is the cumulative reward or the one-step reward (it is currently the cumulative reward) # TODO: make sure that the returns array is always the first column of ts. EDIT t=self.env.time delta=0.025 latestAction=self.env.action[0] previousAction = self.env.actionHistory[-2] cost=delta*abs(sign(latestAction)-sign(previousAction)) #ret=sum([log(1+self.env.ts[i]) for i in range(t,t+30)]) ret=self.env.ts[t] #reward=ret*sign(latestAction)-cost #reward=ret*sign(latestAction) #reward=sum([log(1+(x/100))*sign(latestAction) for x in ret])#*sign(latestAction) reward=(1+(previousAction*ret))*(1-cost)-1 self.env.incrementTime() return reward def reset(self): self class NeuneierRewardTask(Task): """ This task implements a reward structure as outlined in Neuneier(1996) """ def getReward(self): # TODO: change the capital so that it reinvestes t=self.env.time c=1.0 #capital to invest at time t epsilon=0.1+(c/100) # transaction cost latestAction=self.env.action ret=self.env.ts[0,t-1] reward = (ret*latestAction)*(c-epsilon)-c return reward
[ "numpy.sign" ]
[((765, 783), 'numpy.sign', 'sign', (['latestAction'], {}), '(latestAction)\n', (769, 783), False, 'from numpy import sign\n'), ((784, 804), 'numpy.sign', 'sign', (['previousAction'], {}), '(previousAction)\n', (788, 804), False, 'from numpy import sign\n')]
"""Example use of TwoAlternatingCSTRs unit operation. In this example we simulate propagation of periodic inlet flow rate and concentration profiles throughout the unit operation with two alternating CSTRs. Afterwards we create a bunch of plots. """ import numpy as np from bokeh.layouts import column from bokeh.models import LinearAxis, Range1d from bokeh.plotting import figure, show from bio_rtd.uo.surge_tank import TwoAlternatingCSTRs """Simulation time vector.""" t = np.linspace(0, 100, 1001) dt = t[1] """Define unit operation.""" a2cstr = TwoAlternatingCSTRs(t, "a2cstr") a2cstr.v_leftover_rel = 0.05 # 95 % discharge """Inlet profile.""" # Periodic inlet profile. f_in = np.zeros_like(t) c_in = np.zeros([5, t.size]) i_f_on_duration = int(round(0.025 * t.size)) for i, period_start in enumerate(np.arange(0.2, 0.9, 0.1) * t.size): i_f_start = int(round(period_start)) f_in[i_f_start:i_f_start + i_f_on_duration] = 3.5 i_mod = i % c_in.shape[0] c_in[i_mod, i_f_start:i_f_start + i_f_on_duration] = 1 + 0.1 * i_mod """Simulation.""" f_out, c_out = a2cstr.evaluate(f_in, c_in) """Plot inlet and outlet profiles.""" def make_plot(f, c, title_extra): p1 = figure(plot_width=695, plot_height=350, title=f"TwoAlternatingCSTRs - {title_extra}", x_axis_label="t [min]", y_axis_label="c [mg/mL]") # Add flow rate axis. p1.extra_y_ranges = {'f': Range1d(0, f.max() * 1.1)} p1.y_range = Range1d(0, c.max() * 1.5) p1.add_layout(LinearAxis(y_range_name='f'), 'right') p1.yaxis[1].axis_label = "f [mL/min]" # Flow. p1.line(t, f, y_range_name='f', line_width=1.5, color='black', legend_label='flow rate') # Conc. line_colors = ['#3288bd', '#11d594', 'red', '#fc8d59', 'navy'] for i_specie in range(c.shape[0]): p1.line(t, c[i_specie], line_width=2, color=line_colors[i_specie], legend_label=f"conc {i_specie}") p1.legend.location = "top_left" return p1 p_in = make_plot(f_in, c_in, "inlet") p_out = make_plot(f_out, c_out, "outlet") show(column(p_in, p_out))
[ "numpy.zeros_like", "bokeh.plotting.figure", "numpy.zeros", "numpy.arange", "bokeh.models.LinearAxis", "numpy.linspace", "bio_rtd.uo.surge_tank.TwoAlternatingCSTRs", "bokeh.layouts.column" ]
[((482, 507), 'numpy.linspace', 'np.linspace', (['(0)', '(100)', '(1001)'], {}), '(0, 100, 1001)\n', (493, 507), True, 'import numpy as np\n'), ((557, 589), 'bio_rtd.uo.surge_tank.TwoAlternatingCSTRs', 'TwoAlternatingCSTRs', (['t', '"""a2cstr"""'], {}), "(t, 'a2cstr')\n", (576, 589), False, 'from bio_rtd.uo.surge_tank import TwoAlternatingCSTRs\n'), ((692, 708), 'numpy.zeros_like', 'np.zeros_like', (['t'], {}), '(t)\n', (705, 708), True, 'import numpy as np\n'), ((716, 737), 'numpy.zeros', 'np.zeros', (['[5, t.size]'], {}), '([5, t.size])\n', (724, 737), True, 'import numpy as np\n'), ((1196, 1340), 'bokeh.plotting.figure', 'figure', ([], {'plot_width': '(695)', 'plot_height': '(350)', 'title': 'f"""TwoAlternatingCSTRs - {title_extra}"""', 'x_axis_label': '"""t [min]"""', 'y_axis_label': '"""c [mg/mL]"""'}), "(plot_width=695, plot_height=350, title=\n f'TwoAlternatingCSTRs - {title_extra}', x_axis_label='t [min]',\n y_axis_label='c [mg/mL]')\n", (1202, 1340), False, 'from bokeh.plotting import figure, show\n'), ((2117, 2136), 'bokeh.layouts.column', 'column', (['p_in', 'p_out'], {}), '(p_in, p_out)\n', (2123, 2136), False, 'from bokeh.layouts import column\n'), ((816, 840), 'numpy.arange', 'np.arange', (['(0.2)', '(0.9)', '(0.1)'], {}), '(0.2, 0.9, 0.1)\n', (825, 840), True, 'import numpy as np\n'), ((1508, 1536), 'bokeh.models.LinearAxis', 'LinearAxis', ([], {'y_range_name': '"""f"""'}), "(y_range_name='f')\n", (1518, 1536), False, 'from bokeh.models import LinearAxis, Range1d\n')]
#!/usr/bin/env python2 import sys import rospy import yaml import numpy as np from ROSInterface import ROSInterface from MotorController import MotorController class RoboticControl: def __init__(self, t_cam2body): self.ros_interface = ROSInterface(t_cam2body) self.time_init = -1.0 max_speed = 0.3 # Param max_omega = 1.6 # Param self.motor_controller = MotorController(max_speed, max_omega) def process_measurements(self): cam_measurements = self.ros_interface.get_cam_measurements() imu_measurements = self.ros_interface.get_imu() #print("imu measurements are present", imu_measurements) if cam_measurements != None: #print("Cam measurements: ", cam_measurements) state = np.array([0.0, 0.0, 0.0]) goal = np.array([cam_measurements[0], -cam_measurements[1], cam_measurements[2]]) vw = self.motor_controller.compute_vel(state, goal) print("Computed command vel: ", vw) if vw[2] == False: self.ros_interface.command_velocity(vw[0], vw[1]) else: self.ros_interface.command_velocity(0, 0) return else: print("No Measurement.") return if __name__ == '__main__': try: rospy.init_node('robotic_control') param_path = rospy.get_param("~param_path") f = open(param_path, 'r') params_raw = f.read() f.close() params = yaml.load(params_raw) t_cam2body = params['t_cam2body'] t_cam2body_as_np_array = np.asarray(t_cam2body, dtype='float64') print("t_cam2body_as_np_array shape", t_cam2body_as_np_array.shape) robotic_control = RoboticControl(t_cam2body_as_np_array) rate_of_measurement = rospy.Rate(60) while not rospy.is_shutdown(): robotic_control.process_measurements() rate_of_measurement.sleep() ## Once Done, stop the robot robotic_control.ros_interface.command_velocity(0, 0) except rospy.ROSInterruptException: pass
[ "yaml.load", "ROSInterface.ROSInterface", "numpy.asarray", "rospy.Rate", "rospy.get_param", "MotorController.MotorController", "rospy.is_shutdown", "numpy.array", "rospy.init_node" ]
[((241, 265), 'ROSInterface.ROSInterface', 'ROSInterface', (['t_cam2body'], {}), '(t_cam2body)\n', (253, 265), False, 'from ROSInterface import ROSInterface\n'), ((369, 406), 'MotorController.MotorController', 'MotorController', (['max_speed', 'max_omega'], {}), '(max_speed, max_omega)\n', (384, 406), False, 'from MotorController import MotorController\n'), ((1146, 1180), 'rospy.init_node', 'rospy.init_node', (['"""robotic_control"""'], {}), "('robotic_control')\n", (1161, 1180), False, 'import rospy\n'), ((1199, 1229), 'rospy.get_param', 'rospy.get_param', (['"""~param_path"""'], {}), "('~param_path')\n", (1214, 1229), False, 'import rospy\n'), ((1306, 1327), 'yaml.load', 'yaml.load', (['params_raw'], {}), '(params_raw)\n', (1315, 1327), False, 'import yaml\n'), ((1397, 1436), 'numpy.asarray', 'np.asarray', (['t_cam2body'], {'dtype': '"""float64"""'}), "(t_cam2body, dtype='float64')\n", (1407, 1436), True, 'import numpy as np\n'), ((1594, 1608), 'rospy.Rate', 'rospy.Rate', (['(60)'], {}), '(60)\n', (1604, 1608), False, 'import rospy\n'), ((711, 736), 'numpy.array', 'np.array', (['[0.0, 0.0, 0.0]'], {}), '([0.0, 0.0, 0.0])\n', (719, 736), True, 'import numpy as np\n'), ((747, 821), 'numpy.array', 'np.array', (['[cam_measurements[0], -cam_measurements[1], cam_measurements[2]]'], {}), '([cam_measurements[0], -cam_measurements[1], cam_measurements[2]])\n', (755, 821), True, 'import numpy as np\n'), ((1621, 1640), 'rospy.is_shutdown', 'rospy.is_shutdown', ([], {}), '()\n', (1638, 1640), False, 'import rospy\n')]
from typing import Counter import cv2 import numpy as np import mediapipe as mp from numpy.core.defchararray import count from numpy.lib.function_base import angle from numpy.lib.type_check import imag mp_draw = mp.solutions.drawing_utils mp_hs = mp.solutions.holistic mp_pose = mp.solutions.pose cap = cv2.VideoCapture(0) cap.set(cv2.CAP_PROP_FPS, 10) cap.set(3, 1920) cap.set(4, 1080) state_r = None counter_right = 0 state_l = None counter_left = 0 print("Zero(0) To Reset Counter..... ") with mp_pose.Pose(min_detection_confidence=1.0, min_tracking_confidence=1.0)as pose: while(cap.isOpened()): ret, frame = cap.read() flip_image = cv2.flip(frame, 1) if(ret == True): # recolouring the image to RGB img = cv2.cvtColor(flip_image, cv2.COLOR_BGR2RGB) img.flags.writeable = False # making dection with the pose.process result = pose.process(img) # print(result.pose_landmarks) # recolouring it into BGR(Blue,Green,Red) img.flags.writeable = True img_bgr = cv2.cvtColor(img, cv2.COLOR_RGB2BGR) # TRY NO:1 (FOR RIGHT UPPER BODY ) # grabing the landmarks(inside landmarks variable) try: landmarks = result.pose_landmarks.landmark # print(landmarks) # grabing the coordinates of the left side for co_ordinates_left in landmarks: shoulder_left = landmarks[mp_pose.PoseLandmark.LEFT_SHOULDER.value].x, landmarks[ mp_pose.PoseLandmark.LEFT_SHOULDER.value].y elbow_left = landmarks[mp_pose.PoseLandmark.LEFT_ELBOW.value].x, landmarks[mp_pose.PoseLandmark.LEFT_ELBOW.value].y wrist_left = landmarks[mp_pose.PoseLandmark.LEFT_WRIST.value].x, landmarks[mp_pose.PoseLandmark.LEFT_WRIST.value].y # print([shoulder_left], [elbow_left], [wrist_left]) # passing the three arguments as [shoulder, elbow, wrist] angle_right = cal_angle(shoulder_left, elbow_left, wrist_left) # print("RIGHT HAND ANGLE :", angle_right) # rat = tuple(np.multiply(elbow, [1280, 720]).astype(int)) # print(rat) # visualizing or print the angle on the screen cv2.putText(img_bgr, str(angle_right), tuple( np.multiply(elbow_left, [1280, 720]).astype(int)), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2, cv2.LINE_AA) # counter logic right if angle_right > 160: state_r = "down" if angle_right < 35 and state_r == "down": state_r = "up" counter_right += 1 # print("RIGHT HAND COUNT : ", counter_right) except: pass # rendering the box at pixel(0,0) cv2.rectangle(img_bgr, (0, 0), (300, 100), (245, 117, 16), -1) # processed data of the right elbow # rendering the counter variable cv2.putText(img_bgr, 'R_Hand_Count', (15, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0), 1, cv2.LINE_AA) cv2.putText(img_bgr, str(counter_right), (40, 80), cv2.FONT_HERSHEY_SIMPLEX, 2, (255, 255, 255), 2, cv2.LINE_AA) # TRY NO:2 (FOR LEFT UPPER BODY ) try: landmarks = result.pose_landmarks.landmark # grabing the right side of the upper body coordinates for co_ordinates_right in landmarks: shoulder_right = landmarks[mp_pose.PoseLandmark.RIGHT_SHOULDER.value].x, landmarks[ mp_pose.PoseLandmark.RIGHT_SHOULDER.value].y elbow_right = landmarks[mp_pose.PoseLandmark.RIGHT_ELBOW.value].x, landmarks[ mp_pose.PoseLandmark.RIGHT_ELBOW.value].y wrist_right = landmarks[mp_pose.PoseLandmark.RIGHT_WRIST.value].x, landmarks[ mp_pose.PoseLandmark.RIGHT_WRIST.value].y # print(shoulder_right, elbow_right, wrist_right) angle_left = cal_angle( shoulder_right, elbow_right, wrist_right) # print("LEFT HAND ANGLE:", angle_left) # visualizing or print the angle on the screen cv2.putText(img_bgr, str(angle_left), tuple( np.multiply(elbow_right, [1280, 720]).astype(int)), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2, cv2.LINE_4) # counter logic left if angle_left > 160: state_l = "down" if angle_left < 35 and state_l == "down": state_l = "up" counter_left += 1 # print("LEFT HAND COUNT : ", counter_left) except: pass # processed data of the right elbow cv2.putText(img_bgr, 'L_Hand_Count', (160, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0), 1, cv2.LINE_AA) cv2.putText(img_bgr, str(counter_left), (180, 80), cv2.FONT_HERSHEY_SIMPLEX, 2, (255, 255, 255), 2, cv2.LINE_AA) # angle calculation function(where we can pass any 3 arguments) def cal_angle(a, b, c): a = np.array(a) # First point b = np.array(b) # mid point c = np.array(c) # last point radian = (np.arctan2(c[1]-b[1], c[0]-b[0]) - np.arctan2(a[1]-b[1], a[0]-b[0])) real_angle = np.abs(radian*180.0/np.pi) if real_angle > 180: real_angle = 360-real_angle return real_angle if cv2.waitKey(1) == ord('0'): counter_left = 0 counter_right = 0 stage_right = None stage_left = None print("COUNTER RESET.....") # p = mp_pose.PoseLandmark # print(p) # for i in mp_pose.PoseLandmark: # print(i) # print([mp_pose.PoseLandmark.LEFT_WRIST.value]) # print([mp_pose.PoseLandmark.LEFT_ELBOW.value]) # for left_elbow in landmarks: # print([mp_pose.PoseLandmark.LEFT_ELBOW.value]) # for left_wrist in landmarks: # print([mp_pose.PoseLandmark.LEFT_WRIST.value]) # rendering it or rather drawing the pose co-ordinates mp_draw.draw_landmarks( img_bgr, result.pose_landmarks, mp_pose.POSE_CONNECTIONS, mp_draw.DrawingSpec(circle_radius=2), mp_draw.DrawingSpec(color=(200, 66, 26), thickness=2, circle_radius=2) ) # print(mp_pose.POSE_CONNECTIONS) cv2.imshow('output', img_bgr) if(cv2.waitKey(1) & 0xFF == ord('q')): break cap.release() cv2.destroyAllWindows()
[ "cv2.putText", "numpy.abs", "numpy.arctan2", "numpy.multiply", "cv2.cvtColor", "cv2.waitKey", "cv2.imshow", "cv2.VideoCapture", "numpy.array", "cv2.rectangle", "cv2.flip", "cv2.destroyAllWindows" ]
[((305, 324), 'cv2.VideoCapture', 'cv2.VideoCapture', (['(0)'], {}), '(0)\n', (321, 324), False, 'import cv2\n'), ((7155, 7178), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (7176, 7178), False, 'import cv2\n'), ((663, 681), 'cv2.flip', 'cv2.flip', (['frame', '(1)'], {}), '(frame, 1)\n', (671, 681), False, 'import cv2\n'), ((769, 812), 'cv2.cvtColor', 'cv2.cvtColor', (['flip_image', 'cv2.COLOR_BGR2RGB'], {}), '(flip_image, cv2.COLOR_BGR2RGB)\n', (781, 812), False, 'import cv2\n'), ((1103, 1139), 'cv2.cvtColor', 'cv2.cvtColor', (['img', 'cv2.COLOR_RGB2BGR'], {}), '(img, cv2.COLOR_RGB2BGR)\n', (1115, 1139), False, 'import cv2\n'), ((2975, 3037), 'cv2.rectangle', 'cv2.rectangle', (['img_bgr', '(0, 0)', '(300, 100)', '(245, 117, 16)', '(-1)'], {}), '(img_bgr, (0, 0), (300, 100), (245, 117, 16), -1)\n', (2988, 3037), False, 'import cv2\n'), ((3144, 3253), 'cv2.putText', 'cv2.putText', (['img_bgr', '"""R_Hand_Count"""', '(15, 20)', 'cv2.FONT_HERSHEY_SIMPLEX', '(0.5)', '(0, 0, 0)', '(1)', 'cv2.LINE_AA'], {}), "(img_bgr, 'R_Hand_Count', (15, 20), cv2.FONT_HERSHEY_SIMPLEX, \n 0.5, (0, 0, 0), 1, cv2.LINE_AA)\n", (3155, 3253), False, 'import cv2\n'), ((5070, 5180), 'cv2.putText', 'cv2.putText', (['img_bgr', '"""L_Hand_Count"""', '(160, 20)', 'cv2.FONT_HERSHEY_SIMPLEX', '(0.5)', '(0, 0, 0)', '(1)', 'cv2.LINE_AA'], {}), "(img_bgr, 'L_Hand_Count', (160, 20), cv2.FONT_HERSHEY_SIMPLEX, \n 0.5, (0, 0, 0), 1, cv2.LINE_AA)\n", (5081, 5180), False, 'import cv2\n'), ((7037, 7066), 'cv2.imshow', 'cv2.imshow', (['"""output"""', 'img_bgr'], {}), "('output', img_bgr)\n", (7047, 7066), False, 'import cv2\n'), ((5483, 5494), 'numpy.array', 'np.array', (['a'], {}), '(a)\n', (5491, 5494), True, 'import numpy as np\n'), ((5530, 5541), 'numpy.array', 'np.array', (['b'], {}), '(b)\n', (5538, 5541), True, 'import numpy as np\n'), ((5575, 5586), 'numpy.array', 'np.array', (['c'], {}), '(c)\n', (5583, 5586), True, 'import numpy as np\n'), ((5752, 5782), 'numpy.abs', 'np.abs', (['(radian * 180.0 / np.pi)'], {}), '(radian * 180.0 / np.pi)\n', (5758, 5782), True, 'import numpy as np\n'), ((5916, 5930), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (5927, 5930), False, 'import cv2\n'), ((5628, 5664), 'numpy.arctan2', 'np.arctan2', (['(c[1] - b[1])', '(c[0] - b[0])'], {}), '(c[1] - b[1], c[0] - b[0])\n', (5638, 5664), True, 'import numpy as np\n'), ((5689, 5725), 'numpy.arctan2', 'np.arctan2', (['(a[1] - b[1])', '(a[0] - b[0])'], {}), '(a[1] - b[1], a[0] - b[0])\n', (5699, 5725), True, 'import numpy as np\n'), ((7082, 7096), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (7093, 7096), False, 'import cv2\n'), ((2452, 2488), 'numpy.multiply', 'np.multiply', (['elbow_left', '[1280, 720]'], {}), '(elbow_left, [1280, 720])\n', (2463, 2488), True, 'import numpy as np\n'), ((4547, 4584), 'numpy.multiply', 'np.multiply', (['elbow_right', '[1280, 720]'], {}), '(elbow_right, [1280, 720])\n', (4558, 4584), True, 'import numpy as np\n')]
import tensorflow as tf import random import numpy as np import math """implementation by <NAME> (https://github.com/ysmiao/nvdm), adapted with some additional methods by <NAME>""" def data_set_y(data_url): data = [] fin = open(data_url) while True: line = fin.readline() if not line: break data.append(int(line)) fin.close() return data def data_set(data_url): """process data input.""" data = [] word_count = [] fin = open(data_url) while True: line = fin.readline() if not line: break id_freqs = line.split() doc = {} count = 0 for id_freq in id_freqs[1:]: items = id_freq.split(':') # python starts from 0 if int(items[0]) - 1 < 0: print('WARNING INDICES!!!!!!!!!!!!!!!!!!!!!!!!!!!!') doc[int(items[0]) - 1] = int(items[1]) count += int(items[1]) if count > 0: data.append(doc) word_count.append(count) fin.close() return data, word_count def create_batches_new(len_labeled, len_unlabeled, batch_size, shuffle): batches_labeled = [] batches_unlabeled=[] ids_labeled = list(range(len_labeled)) ids_unlabeled=list(range(len_unlabeled)) if len_labeled>len_unlabeled: rest=len_labeled%len_unlabeled mul=len_labeled//len_unlabeled ids_unlabeled=ids_unlabeled*mul+ids_unlabeled[:rest] elif len_labeled<len_unlabeled: rest=len_unlabeled%len_labeled mul=len_unlabeled//len_labeled ids_labeled=ids_labeled*mul+ids_labeled[:rest] if shuffle: random.shuffle(ids_labeled) random.shuffle(ids_unlabeled) max_len=np.maximum(len_labeled,len_unlabeled) for i in range(int(max_len / batch_size)): start = i * batch_size end = (i + 1) * batch_size batches_labeled.append(ids_labeled[start:end]) batches_unlabeled.append(ids_unlabeled[start:end]) # the batch of which the length is less than batch_size rest = max_len % batch_size if rest > 0: batches_labeled.append(list(ids_labeled[-rest:]) + [-1] * (batch_size - rest)) # -1 as padding batches_unlabeled.append(list(ids_unlabeled[-rest:]) + [-1] * (batch_size - rest)) # -1 as padding return batches_labeled,batches_unlabeled def create_batches(data_size, batch_size, shuffle=True): """create index by batches.""" batches = [] ids = list(range(data_size)) if shuffle: random.shuffle(ids) for i in range(int(data_size / batch_size)): start = i * batch_size end = (i + 1) * batch_size batches.append(ids[start:end]) # the batch of which the length is less than batch_size rest = data_size % batch_size if rest > 0: batches.append(list(ids[-rest:]) + [-1] * (batch_size - rest)) # -1 as padding return batches def create_batches_without_lab(data_size, batch_size,n_clss, shuffle=True): """create index by batches.""" batches = [] ids = list(range(data_size)) div=math.floor(batch_size / n_clss) if shuffle: random.shuffle(ids) for i in range(int(data_size / div)): start = i * div end = (i + 1) * div batches.append(ids[start:end]) # the batch of which the length is less than batch_size rest = data_size % div if rest > 0: batches.append(list(ids[-rest:]) + [-1] * (div - rest)) # -1 as padding return batches def fetch_data_y(data, idx_batch,class_size): """fetch input data by batch.""" batch_size = len(idx_batch) data_batch = np.zeros((batch_size, class_size)) for i, doc_id in enumerate(idx_batch):#for all documents if doc_id != -1: data_batch[i, data[doc_id]] = 1.0 return data_batch#,count_batch, #mask def fetch_data_y_new(data, idx_batch,class_size): batch_size = len(idx_batch) data_batch = np.zeros((batch_size, class_size)) data_batch_y_neg, data_batch_y_pos=np.zeros((batch_size, class_size)),np.zeros((batch_size, class_size)) for i, doc_id in enumerate(idx_batch): # for all documents if doc_id != -1: data_batch[i, data[doc_id]] = 1.0 data_batch_y_neg[i,0]=1.0 data_batch_y_pos[i, 1] = 1.0 return data_batch,data_batch_y_neg,data_batch_y_pos def fetch_data_y_dummy_new(data, class_size): batch_size = len(data) data_batch = np.zeros((batch_size, class_size)) data_batch_y_neg, data_batch_y_pos = np.zeros((batch_size, class_size)), np.zeros((batch_size, class_size)) return data_batch, data_batch_y_neg, data_batch_y_pos def fetch_data_y_dummy( idx_batch, n_clss,clss_idx): y_batch=np.zeros((len(idx_batch), n_clss)) for i in range(len(idx_batch)): y_batch[i,clss_idx]=1.0 return y_batch def fetch_data_new(data, idx_batch, vocab_size): batch_size = len(idx_batch) data_batch = np.zeros((batch_size, vocab_size)) mask = np.zeros(batch_size) for i, doc_id in enumerate(idx_batch): if doc_id != -1: for word_id, freq in data[doc_id].items(): data_batch[i, word_id] = freq mask[i] = 1.0 return data_batch, mask def variable_parser(var_list, prefix): """return a subset of the all_variables by prefix.""" ret_list = [] for var in var_list: varname = var.name varprefix = varname.split('/')[0] if varprefix == prefix: ret_list.append(var) elif prefix in varname: ret_list.append(var) return ret_list def linear(inputs, output_size, no_bias=False, bias_start_zero=False, matrix_start_zero=False, scope=None): """Define a linear connection.""" with tf.variable_scope(scope or 'Linear'): if matrix_start_zero: matrix_initializer = tf.constant_initializer( 0) # (tf.truncated_normal_initializer()+1.0)/100.#tf.constant_initializer(0) else: matrix_initializer = None # tf.truncated_normal_initializer(mean = 0.0, stddev=0.01)#None if bias_start_zero: bias_initializer = tf.constant_initializer(0) else: bias_initializer = None # tf.constant_initializer(0.1)#tf.truncated_normal_initializer(mean = 0.0 , stddev=0.01)#None input_size = inputs.get_shape()[1].value matrix = tf.get_variable('Matrix', [input_size, output_size], initializer=matrix_initializer) output = tf.matmul(inputs, matrix) if not no_bias: bias_term = tf.get_variable('Bias', [output_size],initializer=bias_initializer) output = output + bias_term return output def mlp(inputs, mlp_hidden=[], mlp_nonlinearity=tf.nn.tanh, scope=None,is_training=False): """Define an MLP.""" with tf.variable_scope(scope or 'Linear'): mlp_layer = len(mlp_hidden) res = inputs for l in range(mlp_layer): res = tf.contrib.layers.batch_norm( mlp_nonlinearity(linear(res, mlp_hidden[l], scope='l' + str(l))), is_training=is_training) return res def fetch_data_without_idx_new(to_label, vocab_size): batch_size = len(to_label) data_batch = np.zeros((batch_size, vocab_size)) mask = np.zeros(batch_size) for i in range(batch_size): for word_id, freq in to_label[i].items(): data_batch[i, word_id] = freq mask[i] = 1.0 return data_batch,mask
[ "numpy.maximum", "tensorflow.constant_initializer", "random.shuffle", "numpy.zeros", "math.floor", "tensorflow.variable_scope", "tensorflow.matmul", "tensorflow.get_variable" ]
[((1756, 1794), 'numpy.maximum', 'np.maximum', (['len_labeled', 'len_unlabeled'], {}), '(len_labeled, len_unlabeled)\n', (1766, 1794), True, 'import numpy as np\n'), ((3119, 3150), 'math.floor', 'math.floor', (['(batch_size / n_clss)'], {}), '(batch_size / n_clss)\n', (3129, 3150), False, 'import math\n'), ((3667, 3701), 'numpy.zeros', 'np.zeros', (['(batch_size, class_size)'], {}), '((batch_size, class_size))\n', (3675, 3701), True, 'import numpy as np\n'), ((3977, 4011), 'numpy.zeros', 'np.zeros', (['(batch_size, class_size)'], {}), '((batch_size, class_size))\n', (3985, 4011), True, 'import numpy as np\n'), ((4482, 4516), 'numpy.zeros', 'np.zeros', (['(batch_size, class_size)'], {}), '((batch_size, class_size))\n', (4490, 4516), True, 'import numpy as np\n'), ((4977, 5011), 'numpy.zeros', 'np.zeros', (['(batch_size, vocab_size)'], {}), '((batch_size, vocab_size))\n', (4985, 5011), True, 'import numpy as np\n'), ((5023, 5043), 'numpy.zeros', 'np.zeros', (['batch_size'], {}), '(batch_size)\n', (5031, 5043), True, 'import numpy as np\n'), ((7321, 7355), 'numpy.zeros', 'np.zeros', (['(batch_size, vocab_size)'], {}), '((batch_size, vocab_size))\n', (7329, 7355), True, 'import numpy as np\n'), ((7367, 7387), 'numpy.zeros', 'np.zeros', (['batch_size'], {}), '(batch_size)\n', (7375, 7387), True, 'import numpy as np\n'), ((1678, 1705), 'random.shuffle', 'random.shuffle', (['ids_labeled'], {}), '(ids_labeled)\n', (1692, 1705), False, 'import random\n'), ((1714, 1743), 'random.shuffle', 'random.shuffle', (['ids_unlabeled'], {}), '(ids_unlabeled)\n', (1728, 1743), False, 'import random\n'), ((2555, 2574), 'random.shuffle', 'random.shuffle', (['ids'], {}), '(ids)\n', (2569, 2574), False, 'import random\n'), ((3175, 3194), 'random.shuffle', 'random.shuffle', (['ids'], {}), '(ids)\n', (3189, 3194), False, 'import random\n'), ((4051, 4085), 'numpy.zeros', 'np.zeros', (['(batch_size, class_size)'], {}), '((batch_size, class_size))\n', (4059, 4085), True, 'import numpy as np\n'), ((4086, 4120), 'numpy.zeros', 'np.zeros', (['(batch_size, class_size)'], {}), '((batch_size, class_size))\n', (4094, 4120), True, 'import numpy as np\n'), ((4558, 4592), 'numpy.zeros', 'np.zeros', (['(batch_size, class_size)'], {}), '((batch_size, class_size))\n', (4566, 4592), True, 'import numpy as np\n'), ((4594, 4628), 'numpy.zeros', 'np.zeros', (['(batch_size, class_size)'], {}), '((batch_size, class_size))\n', (4602, 4628), True, 'import numpy as np\n'), ((5840, 5876), 'tensorflow.variable_scope', 'tf.variable_scope', (["(scope or 'Linear')"], {}), "(scope or 'Linear')\n", (5857, 5876), True, 'import tensorflow as tf\n'), ((6474, 6563), 'tensorflow.get_variable', 'tf.get_variable', (['"""Matrix"""', '[input_size, output_size]'], {'initializer': 'matrix_initializer'}), "('Matrix', [input_size, output_size], initializer=\n matrix_initializer)\n", (6489, 6563), True, 'import tensorflow as tf\n'), ((6577, 6602), 'tensorflow.matmul', 'tf.matmul', (['inputs', 'matrix'], {}), '(inputs, matrix)\n', (6586, 6602), True, 'import tensorflow as tf\n'), ((6928, 6964), 'tensorflow.variable_scope', 'tf.variable_scope', (["(scope or 'Linear')"], {}), "(scope or 'Linear')\n", (6945, 6964), True, 'import tensorflow as tf\n'), ((5941, 5967), 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0)'], {}), '(0)\n', (5964, 5967), True, 'import tensorflow as tf\n'), ((6236, 6262), 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0)'], {}), '(0)\n', (6259, 6262), True, 'import tensorflow as tf\n'), ((6651, 6719), 'tensorflow.get_variable', 'tf.get_variable', (['"""Bias"""', '[output_size]'], {'initializer': 'bias_initializer'}), "('Bias', [output_size], initializer=bias_initializer)\n", (6666, 6719), True, 'import tensorflow as tf\n')]
import gym import gym_panda from gym_panda.wrapper_env.VAE import VAE import torch import tensorflow as tf import numpy as np import copy import pickle import gym_panda from gym_panda.wrapper_env.wrapper import * import pdb import argparse from itertools import count import scipy.optimize from models import * from replay_memory import Memory from running_state import ZFilter from torch.autograd import Variable from trpo import trpo_step from utils import * #from gen_dem import demo import pickle import random import torch.nn as nn import torch from SAIL.utils.math import * from torch.distributions import Normal from SAIL.models.sac_models import weights_init_ from torch.distributions.categorical import Categorical from SAIL.models.ppo_models import Value, Policy, DiscretePolicy import pybullet as p env = gym.make("disabledpanda-v0") seed_list = [0,2345,3456,4567,5678] dict_list = ["disabledpanda-v0_default_simulated_robot_1.0_0.005_models_seed_0.pt", "disabledpanda-v0_default_simulated_robot_1.0_0.005_models_seed_2345.pt", "disabledpanda-v0_default_simulated_robot_1.0_0.005_models_seed_3456.pt", "disabledpanda-v0_default_simulated_robot_1.0_0.005_models_seed_4567.pt", "disabledpanda-v0_default_simulated_robot_1.0_0.005_models_seed_5678.pt"] reward = [] success = [] for i in range(1): seed = seed_list[i] env.seed(seed) torch.manual_seed(seed) np.random.seed(seed) num_inputs = env.observation_space.shape[0] num_actions = env.action_space.shape[0] policy_indices = list(range(num_inputs)) #state_dict = torch.load("disabledpanda-v0_default_simulated_robot_1.0_0.005_models_seed_0.pt") policy_net = Policy(num_inputs, 3, log_std=-5) policy_net.load_state_dict(torch.load(dict_list[i])[1]) print(i,dict_list[i]) for i in range(1): done = False state = torch.from_numpy(env.reset()['ee_position']) while not done: #pdb.set_trace() mean_action, action_log_std, action_std = policy_net.forward(state.float().reshape((1,3))) prev = state.detach().numpy() mean_action = mean_action.detach().numpy() #pdb.set_trace() state, rewards, done, info = env.step(np.array(mean_action[0])) state = torch.from_numpy(state['ee_position']) p.addUserDebugLine(prev, state, [1, 0, 0], lineWidth=3., lifeTime=0) pdb.set_trace() reward.append(rewards) success.append(int(rewards>0)) pickle.dump(reward, open('..\\logs\\plotdata\\sail_reward.pkl', 'wb')) pickle.dump(success, open('..\\logs\\plotdata\\sail_success.pkl', 'wb'))
[ "numpy.random.seed", "gym.make", "pybullet.addUserDebugLine", "torch.manual_seed", "torch.load", "numpy.array", "pdb.set_trace", "SAIL.models.ppo_models.Policy", "torch.from_numpy" ]
[((818, 846), 'gym.make', 'gym.make', (['"""disabledpanda-v0"""'], {}), "('disabledpanda-v0')\n", (826, 846), False, 'import gym\n'), ((1356, 1379), 'torch.manual_seed', 'torch.manual_seed', (['seed'], {}), '(seed)\n', (1373, 1379), False, 'import torch\n'), ((1384, 1404), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (1398, 1404), True, 'import numpy as np\n'), ((1659, 1692), 'SAIL.models.ppo_models.Policy', 'Policy', (['num_inputs', '(3)'], {'log_std': '(-5)'}), '(num_inputs, 3, log_std=-5)\n', (1665, 1692), False, 'from SAIL.models.ppo_models import Value, Policy, DiscretePolicy\n'), ((2392, 2407), 'pdb.set_trace', 'pdb.set_trace', ([], {}), '()\n', (2405, 2407), False, 'import pdb\n'), ((1724, 1748), 'torch.load', 'torch.load', (['dict_list[i]'], {}), '(dict_list[i])\n', (1734, 1748), False, 'import torch\n'), ((2264, 2302), 'torch.from_numpy', 'torch.from_numpy', (["state['ee_position']"], {}), "(state['ee_position'])\n", (2280, 2302), False, 'import torch\n'), ((2315, 2384), 'pybullet.addUserDebugLine', 'p.addUserDebugLine', (['prev', 'state', '[1, 0, 0]'], {'lineWidth': '(3.0)', 'lifeTime': '(0)'}), '(prev, state, [1, 0, 0], lineWidth=3.0, lifeTime=0)\n', (2333, 2384), True, 'import pybullet as p\n'), ((2218, 2242), 'numpy.array', 'np.array', (['mean_action[0]'], {}), '(mean_action[0])\n', (2226, 2242), True, 'import numpy as np\n')]
import matplotlib.colors as colors import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns from mpl_toolkits.mplot3d import Axes3D from sklearn.manifold import TSNE csfont = {'fontname': 'Times New Roman'} sns.set() sns.set(rc={"figure.figsize": (10, 8)}) resr = np.array([[0, 2], [3, 4]], dtype=int) u = np.unique(resr) bounds = np.concatenate(([resr.min() - 1], u[:-1] + np.diff(u) / 2., [resr.max() + 1])) norm = colors.BoundaryNorm(bounds, len(bounds) - 1) _files = [] _files.append('output_matrix____raw_signal') _files.append('output_matrix____dropout_1') _files.append('output_matrix____gru_1') _files.append('output_matrix____global_average_pooling1d_1') _files.append('output_matrix____concatenate_1') _files.append('output_matrix____dense_1') _plot_title = [] _plot_title.append('Raw Signal') _plot_title.append('LSTM Layer (a)') _plot_title.append('Dropout Layer (b)') _plot_title.append('FCN Layer (c) ') _plot_title.append('Concatenate Layer (d)') _plot_title.append('Softmax Layer 5 (e)') _colors = [ "#000066", "#4c0080", "#990033", "#ff0000", "#cc6600", "#cccc00", "#cccc00", "#00b300", "#669999", "#00ffcc", "#0086b3", "#0000ff", "#ccccff", "#cc00ff", "#ff33cc", "#ff99c2", ] PALETTE = sns.set_palette(sns.color_palette(_colors)) # PALETTE = sns.color_palette('deep', n_colors=18) CMAP = colors.ListedColormap(_colors) RANDOM_STATE = 42 file_name = 'concatenate_1' fig = plt.figure() # df = pd.read_csv('weights/output_matrix____dense_1.csv') # # Delete first # df = df.drop([df.columns[0]], axis=1) # dataset = load_iris() # m_features = list(df.columns.values)[:-1] # features = ['sepal_length', 'sepal_width', 'petal_length', 'petal_width'] m_target = 'class' # target = 'species' # iris = pd.DataFrame( # dataset.data, # columns=features) # iris[target] = dataset.target # print(df[m_features]) # print(iris[features]) fig.tight_layout(pad=1) def plot_iris_2d(x, y, title, xlabel="", ylabel="", index=1): plt.rcParams['font.family'] = ['serif'] # plt.rcParams.update({'font.size': 22}) # sns.set_style("darkgrid") plt.subplot(2, 3, index) # print(df['class']) plt.scatter(x, y, c=df['0'], cmap=CMAP, s=50) plt.title(title, y=-0.2) # plt.xlabel(xlabel, fontsize=16) # plt.ylabel(ylabel, fontsize=16) # plt.show() # plt.savefig('2D___tSNE_' + file_name + '___.png', # format='png') def plot_iris_3d(x, y, z, title, name=''): sns.set_style('whitegrid') fig = plt.figure(1, figsize=(8, 6)) ax = Axes3D(fig, elev=-150, azim=110) ax.scatter(x, y, z, c=df['class'], cmap=CMAP, s=70) ax.set_title(title, y=-0.2) # # fsize = 14 # ax.set_xlabel("1st feature", fontsize=fsize) # ax.set_ylabel("2nd feature", fontsize=fsize) # ax.set_zlabel("3rd feature", fontsize=fsize) ax.w_xaxis.set_ticklabels([]) ax.w_yaxis.set_ticklabels([]) ax.w_zaxis.set_ticklabels([]) # plt.show() fig.savefig(name + '.png', format='png') if __name__ == '__main__': for i in range(0, _files.__len__()): _name = _plot_title[i] df = pd.read_csv('weights/' + _files[i] + '.csv') # Delete first df = df.drop([df.columns[0]], axis=1) m_features = list(df.columns.values)[:-1] tsne = TSNE(n_components=2, n_iter=1000, random_state=RANDOM_STATE) points = tsne.fit_transform(df[m_features]) plot_iris_2d( x=points[:, 0], y=points[:, 1], title=_name, index=i + 1) # fig = matplotlib.pyplot.gcf() # fig.set_size_inches(15, 10) fig.savefig('2D3.png', dpi=200, format='png') # tsne3 = TSNE(n_components=3, n_iter=1000, random_state=RANDOM_STATE) # points3 = tsne3.fit_transform(df[m_features]) # # plot_iris_3d( # x=points3[:, 0], # y=points3[:, 1], # z=points3[:, 2], # title=_name, # name=_name)
[ "matplotlib.pyplot.title", "matplotlib.pyplot.subplot", "seaborn.set_style", "mpl_toolkits.mplot3d.Axes3D", "sklearn.manifold.TSNE", "pandas.read_csv", "matplotlib.pyplot.scatter", "matplotlib.pyplot.figure", "numpy.diff", "numpy.array", "seaborn.color_palette", "seaborn.set", "matplotlib.co...
[((244, 253), 'seaborn.set', 'sns.set', ([], {}), '()\n', (251, 253), True, 'import seaborn as sns\n'), ((254, 293), 'seaborn.set', 'sns.set', ([], {'rc': "{'figure.figsize': (10, 8)}"}), "(rc={'figure.figsize': (10, 8)})\n", (261, 293), True, 'import seaborn as sns\n'), ((302, 339), 'numpy.array', 'np.array', (['[[0, 2], [3, 4]]'], {'dtype': 'int'}), '([[0, 2], [3, 4]], dtype=int)\n', (310, 339), True, 'import numpy as np\n'), ((345, 360), 'numpy.unique', 'np.unique', (['resr'], {}), '(resr)\n', (354, 360), True, 'import numpy as np\n'), ((1413, 1443), 'matplotlib.colors.ListedColormap', 'colors.ListedColormap', (['_colors'], {}), '(_colors)\n', (1434, 1443), True, 'import matplotlib.colors as colors\n'), ((1498, 1510), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (1508, 1510), True, 'import matplotlib.pyplot as plt\n'), ((1327, 1353), 'seaborn.color_palette', 'sns.color_palette', (['_colors'], {}), '(_colors)\n', (1344, 1353), True, 'import seaborn as sns\n'), ((2178, 2202), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(3)', 'index'], {}), '(2, 3, index)\n', (2189, 2202), True, 'import matplotlib.pyplot as plt\n'), ((2233, 2278), 'matplotlib.pyplot.scatter', 'plt.scatter', (['x', 'y'], {'c': "df['0']", 'cmap': 'CMAP', 's': '(50)'}), "(x, y, c=df['0'], cmap=CMAP, s=50)\n", (2244, 2278), True, 'import matplotlib.pyplot as plt\n'), ((2332, 2356), 'matplotlib.pyplot.title', 'plt.title', (['title'], {'y': '(-0.2)'}), '(title, y=-0.2)\n', (2341, 2356), True, 'import matplotlib.pyplot as plt\n'), ((2588, 2614), 'seaborn.set_style', 'sns.set_style', (['"""whitegrid"""'], {}), "('whitegrid')\n", (2601, 2614), True, 'import seaborn as sns\n'), ((2625, 2654), 'matplotlib.pyplot.figure', 'plt.figure', (['(1)'], {'figsize': '(8, 6)'}), '(1, figsize=(8, 6))\n', (2635, 2654), True, 'import matplotlib.pyplot as plt\n'), ((2664, 2696), 'mpl_toolkits.mplot3d.Axes3D', 'Axes3D', (['fig'], {'elev': '(-150)', 'azim': '(110)'}), '(fig, elev=-150, azim=110)\n', (2670, 2696), False, 'from mpl_toolkits.mplot3d import Axes3D\n'), ((3303, 3347), 'pandas.read_csv', 'pd.read_csv', (["('weights/' + _files[i] + '.csv')"], {}), "('weights/' + _files[i] + '.csv')\n", (3314, 3347), True, 'import pandas as pd\n'), ((3483, 3543), 'sklearn.manifold.TSNE', 'TSNE', ([], {'n_components': '(2)', 'n_iter': '(1000)', 'random_state': 'RANDOM_STATE'}), '(n_components=2, n_iter=1000, random_state=RANDOM_STATE)\n', (3487, 3543), False, 'from sklearn.manifold import TSNE\n'), ((413, 423), 'numpy.diff', 'np.diff', (['u'], {}), '(u)\n', (420, 423), True, 'import numpy as np\n')]
''' This module performs a few early syntax check on the input AST. It checks the conformance of the input code to Pythran specific constraints. ''' from pythran.tables import MODULES from pythran.intrinsic import Class from pythran.typing import Tuple, List, Set, Dict from pythran.utils import isstr import beniget import gast as ast import logging import numpy as np logger = logging.getLogger('pythran') # NB: this purposely ignores OpenMP metadata class ExtendedDefUseChains(beniget.DefUseChains): def __init__(self, ancestors): super(ExtendedDefUseChains, self).__init__() self.unbounds = dict() self.ancestors = ancestors def unbound_identifier(self, name, node): for n in reversed(self.ancestors.parents(node)): if hasattr(n, 'lineno'): break self.unbounds.setdefault(name, []).append(n) class PythranSyntaxError(SyntaxError): def __init__(self, msg, node=None): SyntaxError.__init__(self, msg) if node: self.filename = getattr(node, 'filename', None) self.lineno = node.lineno self.offset = node.col_offset def __str__(self): if self.filename and self.lineno and self.offset: with open(self.filename) as f: for i in range(self.lineno - 1): f.readline() # and drop it extra = '{}\n{}'.format(f.readline().rstrip(), " " * (self.offset) + "^~~~ (o_0)") else: extra = None r = "{}:{}:{} error: {}\n".format(self.filename or "<unknown>", self.lineno, self.offset, self.args[0]) if extra is not None: r += "----\n" r += extra r += "\n----\n" return r class SyntaxChecker(ast.NodeVisitor): """ Visit an AST and raise a PythranSyntaxError upon unsupported construct. Attributes ---------- attributes : {str} Possible attributes from Pythonic modules/submodules. """ def __init__(self): """ Gather attributes from MODULES content. """ self.attributes = set() def save_attribute(module): """ Recursively save Pythonic keywords as possible attributes. """ self.attributes.update(module.keys()) for signature in module.values(): if isinstance(signature, dict): save_attribute(signature) elif isinstance(signature, Class): save_attribute(signature.fields) for module in MODULES.values(): save_attribute(module) def visit_Module(self, node): err = ("Top level statements can only be assignments, strings," "functions, comments, or imports") WhiteList = ast.FunctionDef, ast.Import, ast.ImportFrom, ast.Assign for n in node.body: if isinstance(n, ast.Expr) and isstr(n.value): continue if isinstance(n, WhiteList): continue raise PythranSyntaxError(err, n) ancestors = beniget.Ancestors() ancestors.visit(node) duc = ExtendedDefUseChains(ancestors) duc.visit(node) for k, v in duc.unbounds.items(): raise PythranSyntaxError("Unbound identifier {}".format(k), v[0]) self.generic_visit(node) def visit_Interactive(self, node): raise PythranSyntaxError("Interactive session not supported", node) def visit_Expression(self, node): raise PythranSyntaxError("Interactive expressions not supported", node) def visit_Suite(self, node): raise PythranSyntaxError( "Suites are specific to Jython and not supported", node) def visit_ClassDef(self, _): raise PythranSyntaxError("Classes not supported") def visit_Print(self, node): self.generic_visit(node) if node.dest: raise PythranSyntaxError( "Printing to a specific stream not supported", node.dest) def visit_With(self, node): raise PythranSyntaxError("With statements not supported", node) def visit_Starred(self, node): raise PythranSyntaxError("Call with star arguments not supported", node) def visit_keyword(self, node): if node.arg is None: raise PythranSyntaxError("Call with kwargs not supported", node) def visit_Call(self, node): self.generic_visit(node) def visit_Constant(self, node): if node.value is Ellipsis: if hasattr(node, 'lineno'): args = [node] else: args = [] raise PythranSyntaxError("Ellipsis are not supported", *args) iinfo = np.iinfo(int) if isinstance(node.value, int) and not (iinfo.min <= node.value <= iinfo.max): raise PythranSyntaxError("large int not supported", node) def visit_FunctionDef(self, node): if node.decorator_list: raise PythranSyntaxError("decorators not supported", node) if node.args.vararg: raise PythranSyntaxError("Varargs not supported", node) if node.args.kwarg: raise PythranSyntaxError("Keyword arguments not supported", node) self.generic_visit(node) def visit_Raise(self, node): self.generic_visit(node) if node.cause: raise PythranSyntaxError( "Cause in raise statements not supported", node) def visit_Attribute(self, node): self.generic_visit(node) if node.attr not in self.attributes: raise PythranSyntaxError( "Attribute '{0}' unknown".format(node.attr), node) def visit_NamedExpr(self, node): raise PythranSyntaxError( "named expression are not supported yet, please open an issue :-)", node) def visit_Import(self, node): """ Check if imported module exists in MODULES. """ for alias in node.names: current_module = MODULES # Recursive check for submodules for path in alias.name.split('.'): if path not in current_module: raise PythranSyntaxError( "Module '{0}' unknown.".format(alias.name), node) else: current_module = current_module[path] def visit_ImportFrom(self, node): """ Check validity of imported functions. Check: - no level specific value are provided. - a module is provided - module/submodule exists in MODULES - imported function exists in the given module/submodule """ if node.level: raise PythranSyntaxError("Relative import not supported", node) if not node.module: raise PythranSyntaxError("import from without module", node) module = node.module current_module = MODULES # Check if module exists for path in module.split('.'): if path not in current_module: raise PythranSyntaxError( "Module '{0}' unknown.".format(module), node) else: current_module = current_module[path] # Check if imported functions exist for alias in node.names: if alias.name == '*': continue elif alias.name not in current_module: raise PythranSyntaxError( "identifier '{0}' not found in module '{1}'".format( alias.name, module), node) def visit_Exec(self, node): raise PythranSyntaxError("'exec' statements are not supported", node) def visit_Global(self, node): raise PythranSyntaxError("'global' statements are not supported", node) def check_syntax(node): '''Does nothing but raising PythranSyntaxError when needed''' SyntaxChecker().visit(node) def check_specs(specs, types): ''' Does nothing but raising PythranSyntaxError if specs are incompatible with the actual code ''' from pythran.types.tog import unify, clone, tr from pythran.types.tog import Function, TypeVariable, InferenceError for fname, signatures in specs.functions.items(): ftype = types[fname] for signature in signatures: sig_type = Function([tr(p) for p in signature], TypeVariable()) try: unify(clone(sig_type), clone(ftype)) except InferenceError: raise PythranSyntaxError( "Specification for `{}` does not match inferred type:\n" "expected `{}`\n" "got `Callable[[{}], ...]`".format( fname, ftype, ", ".join(map(str, sig_type.types[:-1]))) ) def check_exports(pm, mod, specs): ''' Does nothing but raising PythranSyntaxError if specs references an undefined global ''' from pythran.analyses.argument_effects import ArgumentEffects mod_functions = {node.name: node for node in mod.body if isinstance(node, ast.FunctionDef)} argument_effects = pm.gather(ArgumentEffects, mod) for fname, signatures in specs.functions.items(): try: fnode = mod_functions[fname] except KeyError: raise PythranSyntaxError( "Invalid spec: exporting undefined function `{}`" .format(fname)) ae = argument_effects[fnode] for signature in signatures: args_count = len(fnode.args.args) if len(signature) > args_count: raise PythranSyntaxError( "Too many arguments when exporting `{}`" .format(fname)) elif len(signature) < args_count - len(fnode.args.defaults): raise PythranSyntaxError( "Not enough arguments when exporting `{}`" .format(fname)) for i, ty in enumerate(signature): if ae[i] and isinstance(ty, (List, Tuple, Dict, Set)): logger.warning( ("Exporting function '{}' that modifies its {} " "argument. Beware that this argument won't be " "modified at Python call site").format( fname, ty.__class__.__qualname__), )
[ "pythran.utils.isstr", "numpy.iinfo", "logging.getLogger", "beniget.Ancestors", "pythran.types.tog.TypeVariable", "pythran.types.tog.tr", "pythran.types.tog.clone", "pythran.tables.MODULES.values" ]
[((382, 410), 'logging.getLogger', 'logging.getLogger', (['"""pythran"""'], {}), "('pythran')\n", (399, 410), False, 'import logging\n'), ((2716, 2732), 'pythran.tables.MODULES.values', 'MODULES.values', ([], {}), '()\n', (2730, 2732), False, 'from pythran.tables import MODULES\n'), ((3245, 3264), 'beniget.Ancestors', 'beniget.Ancestors', ([], {}), '()\n', (3262, 3264), False, 'import beniget\n'), ((4922, 4935), 'numpy.iinfo', 'np.iinfo', (['int'], {}), '(int)\n', (4930, 4935), True, 'import numpy as np\n'), ((3073, 3087), 'pythran.utils.isstr', 'isstr', (['n.value'], {}), '(n.value)\n', (3078, 3087), False, 'from pythran.utils import isstr\n'), ((8833, 8847), 'pythran.types.tog.TypeVariable', 'TypeVariable', ([], {}), '()\n', (8845, 8847), False, 'from pythran.types.tog import Function, TypeVariable, InferenceError\n'), ((8806, 8811), 'pythran.types.tog.tr', 'tr', (['p'], {}), '(p)\n', (8808, 8811), False, 'from pythran.types.tog import unify, clone, tr\n'), ((8888, 8903), 'pythran.types.tog.clone', 'clone', (['sig_type'], {}), '(sig_type)\n', (8893, 8903), False, 'from pythran.types.tog import unify, clone, tr\n'), ((8905, 8917), 'pythran.types.tog.clone', 'clone', (['ftype'], {}), '(ftype)\n', (8910, 8917), False, 'from pythran.types.tog import unify, clone, tr\n')]
from __future__ import print_function import numpy as np import testing as tm import unittest import pytest import xgboost as xgb try: from sklearn.linear_model import ElasticNet from sklearn.preprocessing import scale from regression_test_utilities import run_suite, parameter_combinations except ImportError: None def is_float(s): try: float(s) return 1 except ValueError: return 0 def xgb_get_weights(bst): return np.array([float(s) for s in bst.get_dump()[0].split() if is_float(s)]) def assert_regression_result(results, tol): regression_results = [r for r in results if r["param"]["objective"] == "reg:squarederror"] for res in regression_results: X = scale(res["dataset"].X, with_mean=isinstance(res["dataset"].X, np.ndarray)) y = res["dataset"].y reg_alpha = res["param"]["alpha"] reg_lambda = res["param"]["lambda"] pred = res["bst"].predict(xgb.DMatrix(X)) weights = xgb_get_weights(res["bst"])[1:] enet = ElasticNet(alpha=reg_alpha + reg_lambda, l1_ratio=reg_alpha / (reg_alpha + reg_lambda)) enet.fit(X, y) enet_pred = enet.predict(X) assert np.isclose(weights, enet.coef_, rtol=tol, atol=tol).all(), (weights, enet.coef_) assert np.isclose(enet_pred, pred, rtol=tol, atol=tol).all(), ( res["dataset"].name, enet_pred[:5], pred[:5]) # TODO: More robust classification tests def assert_classification_result(results): classification_results = [r for r in results if r["param"]["objective"] != "reg:squarederror"] for res in classification_results: # Check accuracy is reasonable assert res["eval"][-1] < 0.5, (res["dataset"].name, res["eval"][-1]) class TestLinear(unittest.TestCase): datasets = ["Boston", "Digits", "Cancer", "Sparse regression", "Boston External Memory"] @pytest.mark.skipif(**tm.no_sklearn()) def test_coordinate(self): variable_param = {'booster': ['gblinear'], 'updater': ['coord_descent'], 'eta': [0.5], 'top_k': [10], 'tolerance': [1e-5], 'nthread': [2], 'alpha': [.005, .1], 'lambda': [.005], 'feature_selector': ['cyclic', 'shuffle', 'greedy', 'thrifty']} for param in parameter_combinations(variable_param): results = run_suite(param, 150, self.datasets, scale_features=True) assert_regression_result(results, 1e-2) assert_classification_result(results) @pytest.mark.skipif(**tm.no_sklearn()) def test_shotgun(self): variable_param = {'booster': ['gblinear'], 'updater': ['shotgun'], 'eta': [0.5], 'top_k': [10], 'tolerance': [1e-5], 'nthread': [2], 'alpha': [.005, .1], 'lambda': [.005], 'feature_selector': ['cyclic', 'shuffle']} for param in parameter_combinations(variable_param): results = run_suite(param, 200, self.datasets, True) assert_regression_result(results, 1e-2) assert_classification_result(results)
[ "sklearn.linear_model.ElasticNet", "testing.no_sklearn", "numpy.isclose", "regression_test_utilities.parameter_combinations", "xgboost.DMatrix", "regression_test_utilities.run_suite" ]
[((1106, 1197), 'sklearn.linear_model.ElasticNet', 'ElasticNet', ([], {'alpha': '(reg_alpha + reg_lambda)', 'l1_ratio': '(reg_alpha / (reg_alpha + reg_lambda))'}), '(alpha=reg_alpha + reg_lambda, l1_ratio=reg_alpha / (reg_alpha +\n reg_lambda))\n', (1116, 1197), False, 'from sklearn.linear_model import ElasticNet\n'), ((2548, 2586), 'regression_test_utilities.parameter_combinations', 'parameter_combinations', (['variable_param'], {}), '(variable_param)\n', (2570, 2586), False, 'from regression_test_utilities import run_suite, parameter_combinations\n'), ((3190, 3228), 'regression_test_utilities.parameter_combinations', 'parameter_combinations', (['variable_param'], {}), '(variable_param)\n', (3212, 3228), False, 'from regression_test_utilities import run_suite, parameter_combinations\n'), ((1025, 1039), 'xgboost.DMatrix', 'xgb.DMatrix', (['X'], {}), '(X)\n', (1036, 1039), True, 'import xgboost as xgb\n'), ((2610, 2667), 'regression_test_utilities.run_suite', 'run_suite', (['param', '(150)', 'self.datasets'], {'scale_features': '(True)'}), '(param, 150, self.datasets, scale_features=True)\n', (2619, 2667), False, 'from regression_test_utilities import run_suite, parameter_combinations\n'), ((2078, 2093), 'testing.no_sklearn', 'tm.no_sklearn', ([], {}), '()\n', (2091, 2093), True, 'import testing as tm\n'), ((3252, 3294), 'regression_test_utilities.run_suite', 'run_suite', (['param', '(200)', 'self.datasets', '(True)'], {}), '(param, 200, self.datasets, True)\n', (3261, 3294), False, 'from regression_test_utilities import run_suite, parameter_combinations\n'), ((2797, 2812), 'testing.no_sklearn', 'tm.no_sklearn', ([], {}), '()\n', (2810, 2812), True, 'import testing as tm\n'), ((1294, 1345), 'numpy.isclose', 'np.isclose', (['weights', 'enet.coef_'], {'rtol': 'tol', 'atol': 'tol'}), '(weights, enet.coef_, rtol=tol, atol=tol)\n', (1304, 1345), True, 'import numpy as np\n'), ((1416, 1463), 'numpy.isclose', 'np.isclose', (['enet_pred', 'pred'], {'rtol': 'tol', 'atol': 'tol'}), '(enet_pred, pred, rtol=tol, atol=tol)\n', (1426, 1463), True, 'import numpy as np\n')]
from __future__ import absolute_import import os.path import numpy as np from skimage import draw import cv2 from ocrd_modelfactory import page_from_file from ocrd_models.ocrd_page import ( to_xml, CoordsType, TextLineType, TextRegionType, SeparatorRegionType, PageType ) from ocrd import Processor from ocrd_utils import ( getLogger, concat_padded, coordinates_of_segment, coordinates_for_segment, points_from_polygon, MIMETYPE_PAGE ) from .. import get_ocrd_tool from . import common from .ocrolib import midrange from .ocrolib import morph from .ocrolib import sl from .common import ( pil2array, array2pil, # binarize, compute_line_labels ) TOOL = 'ocrd-cis-ocropy-segment' LOG = getLogger('processor.OcropySegment') def segment(line_labels, region_bin, region_id): """Convert label masks into polygon coordinates. Given a Numpy array of background labels ``line_labels``, and a Numpy array of the foreground ``region_bin``, iterate through all labels (except zero and those labels which do not correspond to any foreground at all) to find their outer contours. Each contour part which is not too small and gives a (simplified) polygon of at least 4 points becomes a polygon. Return a list of all such polygons concatenated. """ lines = [] for label in np.unique(line_labels): if not label: # ignore if background continue line_mask = np.array(line_labels == label, np.uint8) if not np.count_nonzero(line_mask * region_bin): # ignore if missing foreground continue # find outer contour (parts): contours, _ = cv2.findContours(line_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # determine areas of parts: areas = [cv2.contourArea(contour) for contour in contours] total_area = sum(areas) if not total_area: # ignore if too small continue for i, contour in enumerate(contours): area = areas[i] if area / total_area < 0.1: LOG.warning('Line label %d contour %d is too small (%d/%d) in region "%s"', label, i, area, total_area, region_id) continue # simplify shape: polygon = cv2.approxPolyDP(contour, 2, False)[:, 0, ::] # already ordered x,y if len(polygon) < 4: LOG.warning('Line label %d contour %d has less than 4 points for region "%s"', label, i, region_id) continue lines.append(polygon) return lines class OcropySegment(Processor): def __init__(self, *args, **kwargs): self.ocrd_tool = get_ocrd_tool() kwargs['ocrd_tool'] = self.ocrd_tool['tools'][TOOL] kwargs['version'] = self.ocrd_tool['version'] super(OcropySegment, self).__init__(*args, **kwargs) def process(self): """Segment pages into text regions or text regions into text lines. Open and deserialise PAGE input files and their respective images, then iterate over the element hierarchy down to the requested level. Next, get each element image according to the layout annotation (from the alternative image of the page/region, or by cropping via coordinates into the higher-level image), binarize it (without deskewing), and compute a new line segmentation for that (as a label mask). If ``level-of-operation`` is ``page``, aggregate text lines to text regions heuristically, and also detect all horizontal and up to ``maxseps`` vertical rulers (foreground separators), as well as up to ``maxcolseps`` column dividers (background separators). Then for each resulting segment label, convert its background mask into polygon outlines by finding the outer contours consistent with the element's polygon outline. Annotate the result by adding it as a new TextLine/TextRegion: If ``level-of-operation`` is ``region``, then (unless ``overwrite_lines`` is False) remove any existing TextLine elements, and append the new lines to the region. If however it is ``page``, then (unless ``overwrite_regions`` is False) remove any existing TextRegion elements, and append the new regions to the page. Produce a new output file by serialising the resulting hierarchy. """ # FIXME: attempt detecting or allow passing reading order / textline order # FIXME: lines2regions has very coarse rules, needs bbox clustering # FIXME: also annotate lines already computed when level=page overwrite_lines = self.parameter['overwrite_lines'] overwrite_regions = self.parameter['overwrite_regions'] oplevel = self.parameter['level-of-operation'] for (n, input_file) in enumerate(self.input_files): LOG.info("INPUT FILE %i / %s", n, input_file.pageId or input_file.ID) pcgts = page_from_file(self.workspace.download_file(input_file)) page_id = pcgts.pcGtsId or input_file.pageId or input_file.ID # (PageType has no id) page = pcgts.get_Page() page_image, page_xywh, page_image_info = self.workspace.image_from_page( page, page_id) if page_image_info.resolution != 1: dpi = page_image_info.resolution if page_image_info.resolutionUnit == 'cm': dpi = round(dpi * 2.54) LOG.info('Page "%s" uses %d DPI', page_id, dpi) zoom = 300.0/dpi else: zoom = 1 regions = page.get_TextRegion() if oplevel == 'page': if regions: if overwrite_regions: LOG.info('removing existing TextRegions in page "%s"', page_id) page.set_TextRegion([]) page.set_ReadingOrder(None) else: LOG.warning('keeping existing TextRegions in page "%s"', page_id) self._process_element(page, page_image, page_xywh, page_id, zoom) else: if not regions: LOG.warning('Page "%s" contains no text regions', page_id) for region in regions: if region.get_TextLine(): if overwrite_lines: LOG.info('removing existing TextLines in page "%s" region "%s"', page_id, region.id) region.set_TextLine([]) else: LOG.warning('keeping existing TextLines in page "%s" region "%s"', page_id, region.id) region_image, region_xywh = self.workspace.image_from_segment( region, page_image, page_xywh) self._process_element(region, region_image, region_xywh, region.id, zoom) # update METS (add the PAGE file): file_id = input_file.ID.replace(self.input_file_grp, self.output_file_grp) if file_id == input_file.ID: file_id = concat_padded(self.output_file_grp, n) file_path = os.path.join(self.output_file_grp, file_id + '.xml') out = self.workspace.add_file( ID=file_id, file_grp=self.output_file_grp, pageId=input_file.pageId, local_filename=file_path, mimetype=MIMETYPE_PAGE, content=to_xml(pcgts)) LOG.info('created file ID: %s, file_grp: %s, path: %s', file_id, self.output_file_grp, out.local_filename) def _process_element(self, element, image, xywh, element_id, zoom): """Add PAGE layout elements by segmenting an image. Given a PageType or TextRegionType ``element``, and a corresponding PIL.Image object ``image`` with its bounding box ``xywh``, run ad-hoc binarization with Ocropy on the image (in case it was still raw), then a line segmentation with Ocropy. If operating on the full page, aggregate lines to regions. Add the resulting sub-segments to the parent ``element``. """ # ad-hoc binarization: element_array = pil2array(image) element_array, _ = common.binarize(element_array, maxskew=0) # just in case still raw element_bin = np.array(element_array <= midrange(element_array), np.uint8) try: line_labels, hlines, vlines, colseps = compute_line_labels( element_array, zoom=zoom, fullpage=isinstance(element, PageType), spread_dist=round(self.parameter['spread']/zoom*300/72), # in pt maxcolseps=self.parameter['maxcolseps'], maxseps=self.parameter['maxseps']) except Exception as err: if isinstance(element, TextRegionType): LOG.warning('Cannot line-segment region "%s": %s', element_id, err) # as a fallback, add a single text line comprising the whole region: element.add_TextLine(TextLineType(id=element_id + "_line", Coords=element.get_Coords())) else: LOG.error('Cannot line-segment page "%s": %s', element_id, err) return #DSAVE('line labels', line_labels) if isinstance(element, PageType): # aggregate text lines to text regions: region_labels = self._lines2regions(line_labels, element_id) # find contours around region labels (can be non-contiguous): region_polygons = segment(region_labels, element_bin, element_id) for region_no, polygon in enumerate(region_polygons): region_id = element_id + "_region%04d" % region_no # convert back to absolute (page) coordinates: region_polygon = coordinates_for_segment(polygon, image, xywh) # annotate result: element.add_TextRegion(TextRegionType(id=region_id, Coords=CoordsType( points=points_from_polygon(region_polygon)))) # split rulers into separator regions: hline_labels, _ = morph.label(hlines) vline_labels, _ = morph.label(vlines) # find contours around region labels (can be non-contiguous): hline_polygons = segment(hline_labels, element_bin, element_id) vline_polygons = segment(vline_labels, element_bin, element_id) for region_no, polygon in enumerate(hline_polygons + vline_polygons): region_id = element_id + "_sep%04d" % region_no # convert back to absolute (page) coordinates: region_polygon = coordinates_for_segment(polygon, image, xywh) # annotate result: element.add_SeparatorRegion(SeparatorRegionType(id=region_id, Coords=CoordsType( points=points_from_polygon(region_polygon)))) else: # get mask from region polygon: region_polygon = coordinates_of_segment(element, image, xywh) region_mask = np.zeros_like(element_array) region_mask[draw.polygon(region_polygon[:, 1], region_polygon[:, 0], region_mask.shape)] = 1 # ensure the new line labels do not extrude from the region: line_labels = line_labels * region_mask # find contours around labels (can be non-contiguous): line_polygons = segment(line_labels, element_bin, element_id) for line_no, polygon in enumerate(line_polygons): line_id = element_id + "_line%04d" % line_no # convert back to absolute (page) coordinates: line_polygon = coordinates_for_segment(polygon, image, xywh) # annotate result: element.add_TextLine(TextLineType(id=line_id, Coords=CoordsType( points=points_from_polygon(line_polygon)))) def _lines2regions(self, line_labels, page_id): """Aggregate text lines to text regions. Given a Numpy array of text lines ``line_labels``, find direct neighbours that match in height and are consistent in horizontal position. Merge these into larger region labels. Then morphologically close them to fill the background between lines. Merge regions that now contain each other. Return a Numpy array of text region labels. Horizontal consistency rules (in 2 passes): - first, aggregate pairs that flush left _and_ right - second, add remainders that are indented left or rugged right """ objects = [None] + morph.find_objects(line_labels) scale = int(np.median(np.array([sl.height(obj) for obj in objects if obj]))) num_labels = np.max(line_labels)+1 relabel = np.arange(num_labels) # first determine which label pairs are adjacent: neighbours = np.zeros((num_labels,num_labels), np.uint8) for x in range(line_labels.shape[1]): labels = line_labels[:,x] # one column labels = labels[labels>0] # no background _, lind = np.unique(labels, return_index=True) labels = labels[lind] # without repetition neighbours[labels[:-1], labels[1:]] += 1 # successors neighbours[labels, labels] += 1 # identities # remove transitive pairs (jumping over 2 other pairs): for y, x in zip(*neighbours.nonzero()): if y == x: continue if np.any(neighbours[y, y+1:x]) and np.any(neighbours[y+1:x, x]): neighbours[y, x] = 0 # now merge lines if possible (in 2 passes: # - first, aggregate pairs that flush left and right # - second, add remainders that are indented left or rugged right): for pass_ in ['pairs', 'remainders']: for label1 in range(1, num_labels - 1): if not neighbours[label1, label1]: continue # not a label for label2 in range(label1 + 1, num_labels): if not neighbours[label1, label2]: continue # not neighbours (or transitive) if relabel[label1] == relabel[label2]: continue # already merged (in previous pass) object1 = objects[label1] object2 = objects[label2] LOG.debug('page "%s" candidate lines %d (%s) vs %d (%s)', page_id, label1, str(sl.raster(object1)), label2, str(sl.raster(object2))) height = max(sl.height(object1), sl.height(object2)) #width = max(sl.width(object1), sl.width(object2)) width = line_labels.shape[1] if not ( # similar height (e.g. discount headings from paragraph): abs(sl.height(object1) - sl.height(object2)) < height * 0.2 and # vertically not too far away: (object2[0].start - object1[0].stop) < height * 1.0 and # horizontally consistent: ( # flush with each other on the left: abs(object1[1].start - object2[1].start) < width * 0.1 or # object1 = line indented left, object2 = block (pass_ == 'remainders' and np.count_nonzero(relabel == label1) == 1 and - width * 0.1 < object1[1].start - object2[1].start < width * 0.8) ) and ( # flush with each other on the right: abs(object1[1].stop - object2[1].stop) < width * 0.1 or # object1 = block, object2 = line ragged right (pass_ == 'pairs' and np.count_nonzero(relabel == label2) == 1 and - width * 0.1 < object1[1].stop - object2[1].stop < width * 0.8) )): continue LOG.debug('page "%s" joining lines %d and %d', page_id, label1, label2) label1 = relabel[label1] label2 = relabel[label2] relabel[label2] = label1 relabel[relabel == label2] = label1 region_labels = relabel[line_labels] #DSAVE('region labels', region_labels) # finally, close regions: labels = np.unique(region_labels) labels = labels[labels > 0] for label in labels: region = np.array(region_labels == label) region_count = np.count_nonzero(region) if not region_count: continue LOG.debug('label %d: %d pixels', label, region_count) # close region between lines: region = morph.r_closing(region, (scale, 1)) # extend region to background: region_labels = np.where(region_labels > 0, region_labels, region*label) # extend region to other labels that are contained in it: for label2 in labels[labels != label]: region2 = region_labels == label2 region2_count = np.count_nonzero(region2) #if np.all(region2 <= region): # or be even more tolerant to avoid strange contours? if np.count_nonzero(region2 > region) < region2_count * 0.1: LOG.debug('%d contains %d', label, label2) region_labels[region2] = label #DSAVE('region labels closed', region_labels) return region_labels
[ "cv2.approxPolyDP", "numpy.arange", "numpy.unique", "cv2.contourArea", "numpy.zeros_like", "ocrd_utils.coordinates_of_segment", "ocrd_utils.points_from_polygon", "numpy.max", "ocrd_utils.getLogger", "skimage.draw.polygon", "ocrd_models.ocrd_page.to_xml", "ocrd_utils.concat_padded", "ocrd_uti...
[((744, 780), 'ocrd_utils.getLogger', 'getLogger', (['"""processor.OcropySegment"""'], {}), "('processor.OcropySegment')\n", (753, 780), False, 'from ocrd_utils import getLogger, concat_padded, coordinates_of_segment, coordinates_for_segment, points_from_polygon, MIMETYPE_PAGE\n'), ((1376, 1398), 'numpy.unique', 'np.unique', (['line_labels'], {}), '(line_labels)\n', (1385, 1398), True, 'import numpy as np\n'), ((1498, 1538), 'numpy.array', 'np.array', (['(line_labels == label)', 'np.uint8'], {}), '(line_labels == label, np.uint8)\n', (1506, 1538), True, 'import numpy as np\n'), ((1720, 1791), 'cv2.findContours', 'cv2.findContours', (['line_mask', 'cv2.RETR_EXTERNAL', 'cv2.CHAIN_APPROX_SIMPLE'], {}), '(line_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n', (1736, 1791), False, 'import cv2\n'), ((13327, 13348), 'numpy.arange', 'np.arange', (['num_labels'], {}), '(num_labels)\n', (13336, 13348), True, 'import numpy as np\n'), ((13428, 13472), 'numpy.zeros', 'np.zeros', (['(num_labels, num_labels)', 'np.uint8'], {}), '((num_labels, num_labels), np.uint8)\n', (13436, 13472), True, 'import numpy as np\n'), ((17259, 17283), 'numpy.unique', 'np.unique', (['region_labels'], {}), '(region_labels)\n', (17268, 17283), True, 'import numpy as np\n'), ((1554, 1594), 'numpy.count_nonzero', 'np.count_nonzero', (['(line_mask * region_bin)'], {}), '(line_mask * region_bin)\n', (1570, 1594), True, 'import numpy as np\n'), ((1845, 1869), 'cv2.contourArea', 'cv2.contourArea', (['contour'], {}), '(contour)\n', (1860, 1869), False, 'import cv2\n'), ((11418, 11462), 'ocrd_utils.coordinates_of_segment', 'coordinates_of_segment', (['element', 'image', 'xywh'], {}), '(element, image, xywh)\n', (11440, 11462), False, 'from ocrd_utils import getLogger, concat_padded, coordinates_of_segment, coordinates_for_segment, points_from_polygon, MIMETYPE_PAGE\n'), ((11489, 11517), 'numpy.zeros_like', 'np.zeros_like', (['element_array'], {}), '(element_array)\n', (11502, 11517), True, 'import numpy as np\n'), ((13287, 13306), 'numpy.max', 'np.max', (['line_labels'], {}), '(line_labels)\n', (13293, 13306), True, 'import numpy as np\n'), ((13645, 13681), 'numpy.unique', 'np.unique', (['labels'], {'return_index': '(True)'}), '(labels, return_index=True)\n', (13654, 13681), True, 'import numpy as np\n'), ((17370, 17402), 'numpy.array', 'np.array', (['(region_labels == label)'], {}), '(region_labels == label)\n', (17378, 17402), True, 'import numpy as np\n'), ((17430, 17454), 'numpy.count_nonzero', 'np.count_nonzero', (['region'], {}), '(region)\n', (17446, 17454), True, 'import numpy as np\n'), ((17749, 17807), 'numpy.where', 'np.where', (['(region_labels > 0)', 'region_labels', '(region * label)'], {}), '(region_labels > 0, region_labels, region * label)\n', (17757, 17807), True, 'import numpy as np\n'), ((2360, 2395), 'cv2.approxPolyDP', 'cv2.approxPolyDP', (['contour', '(2)', '(False)'], {}), '(contour, 2, False)\n', (2376, 2395), False, 'import cv2\n'), ((7391, 7429), 'ocrd_utils.concat_padded', 'concat_padded', (['self.output_file_grp', 'n'], {}), '(self.output_file_grp, n)\n', (7404, 7429), False, 'from ocrd_utils import getLogger, concat_padded, coordinates_of_segment, coordinates_for_segment, points_from_polygon, MIMETYPE_PAGE\n'), ((10234, 10279), 'ocrd_utils.coordinates_for_segment', 'coordinates_for_segment', (['polygon', 'image', 'xywh'], {}), '(polygon, image, xywh)\n', (10257, 10279), False, 'from ocrd_utils import getLogger, concat_padded, coordinates_of_segment, coordinates_for_segment, points_from_polygon, MIMETYPE_PAGE\n'), ((11087, 11132), 'ocrd_utils.coordinates_for_segment', 'coordinates_for_segment', (['polygon', 'image', 'xywh'], {}), '(polygon, image, xywh)\n', (11110, 11132), False, 'from ocrd_utils import getLogger, concat_padded, coordinates_of_segment, coordinates_for_segment, points_from_polygon, MIMETYPE_PAGE\n'), ((11542, 11617), 'skimage.draw.polygon', 'draw.polygon', (['region_polygon[:, 1]', 'region_polygon[:, 0]', 'region_mask.shape'], {}), '(region_polygon[:, 1], region_polygon[:, 0], region_mask.shape)\n', (11554, 11617), False, 'from skimage import draw\n'), ((12180, 12225), 'ocrd_utils.coordinates_for_segment', 'coordinates_for_segment', (['polygon', 'image', 'xywh'], {}), '(polygon, image, xywh)\n', (12203, 12225), False, 'from ocrd_utils import getLogger, concat_padded, coordinates_of_segment, coordinates_for_segment, points_from_polygon, MIMETYPE_PAGE\n'), ((14035, 14065), 'numpy.any', 'np.any', (['neighbours[y, y + 1:x]'], {}), '(neighbours[y, y + 1:x])\n', (14041, 14065), True, 'import numpy as np\n'), ((14068, 14098), 'numpy.any', 'np.any', (['neighbours[y + 1:x, x]'], {}), '(neighbours[y + 1:x, x])\n', (14074, 14098), True, 'import numpy as np\n'), ((18009, 18034), 'numpy.count_nonzero', 'np.count_nonzero', (['region2'], {}), '(region2)\n', (18025, 18034), True, 'import numpy as np\n'), ((7810, 7823), 'ocrd_models.ocrd_page.to_xml', 'to_xml', (['pcgts'], {}), '(pcgts)\n', (7816, 7823), False, 'from ocrd_models.ocrd_page import to_xml, CoordsType, TextLineType, TextRegionType, SeparatorRegionType, PageType\n'), ((18171, 18205), 'numpy.count_nonzero', 'np.count_nonzero', (['(region2 > region)'], {}), '(region2 > region)\n', (18187, 18205), True, 'import numpy as np\n'), ((10429, 10464), 'ocrd_utils.points_from_polygon', 'points_from_polygon', (['region_polygon'], {}), '(region_polygon)\n', (10448, 10464), False, 'from ocrd_utils import getLogger, concat_padded, coordinates_of_segment, coordinates_for_segment, points_from_polygon, MIMETYPE_PAGE\n'), ((11292, 11327), 'ocrd_utils.points_from_polygon', 'points_from_polygon', (['region_polygon'], {}), '(region_polygon)\n', (11311, 11327), False, 'from ocrd_utils import getLogger, concat_padded, coordinates_of_segment, coordinates_for_segment, points_from_polygon, MIMETYPE_PAGE\n'), ((12369, 12402), 'ocrd_utils.points_from_polygon', 'points_from_polygon', (['line_polygon'], {}), '(line_polygon)\n', (12388, 12402), False, 'from ocrd_utils import getLogger, concat_padded, coordinates_of_segment, coordinates_for_segment, points_from_polygon, MIMETYPE_PAGE\n'), ((16090, 16125), 'numpy.count_nonzero', 'np.count_nonzero', (['(relabel == label1)'], {}), '(relabel == label1)\n', (16106, 16125), True, 'import numpy as np\n'), ((16625, 16660), 'numpy.count_nonzero', 'np.count_nonzero', (['(relabel == label2)'], {}), '(relabel == label2)\n', (16641, 16660), True, 'import numpy as np\n')]
from functools import lru_cache import numpy as np from scipy import stats from .utils import check_args, seaborn_plt, call_shortcut __all__ = ["CorrelatedTTest", "two_on_single"] class Posterior: """ The posterior distribution of differences on a single data set. Args: mean (float): the mean difference var (float): the variance df (float): degrees of freedom rope (float): rope (default: 0) meanx (float): mean score of the first classifier; shown in a plot meany (float): mean score of the second classifier; shown in a plot names (tuple of str): names of classifiers; shown in a plot nsamples (int): the number of samples; used only in property `sample`, not in computation of probabilities or plotting (default: 50000) """ def __init__(self, mean, var, df, rope=0, meanx=None, meany=None, *, names=None, nsamples=50000): self.meanx = meanx self.meany = meany self.mean = mean self.var = var self.df = df self.rope = rope self.names = names self.nsamples = nsamples @property @lru_cache(1) def sample(self): """ A sample of differences as 1-dimensional array. Like posteriors for comparison on multiple data sets, an instance of this class will always return the same sample. This sample is not used by other methods. """ if self.var == 0: return np.full((self.nsamples, ), self.mean) return self.mean + \ np.sqrt(self.var) * np.random.standard_t(self.df, self.nsamples) def probs(self): """ Compute and return probabilities Probabilities are not computed from a sample posterior but from cumulative Student distribution. Returns: `(p_left, p_rope, p_right)` if `rope > 0`; otherwise `(p_left, p_right)`. """ t_parameters = self.df, self.mean, np.sqrt(self.var) if self.rope == 0: if self.var == 0: pr = (self.mean > 0) + 0.5 * (self.mean == 0) else: pr = 1 - stats.t.cdf(0, *t_parameters) return 1 - pr, pr else: if self.var == 0: pl = float(self.mean < -self.rope) pr = float(self.mean > self.rope) else: pl = stats.t.cdf(-self.rope, *t_parameters) pr = 1 - stats.t.cdf(self.rope, *t_parameters) return pl, 1 - pl - pr, pr def plot(self, names=None): """ Plot the posterior Student distribution as a histogram. Args: names (tuple of str): names of classifiers Returns: matplotlib figure """ with seaborn_plt() as plt: names = names or self.names or ("C1", "C2") fig, ax = plt.subplots() ax.grid(True) label = "difference" if self.meanx is not None and self.meany is not None: label += " ({}: {:.3f}, {}: {:.3f})".format( names[0], self.meanx, names[1], self.meany) ax.set_xlabel(label) ax.get_yaxis().set_ticklabels([]) ax.axvline(x=-self.rope, color="#ffad2f", linewidth=2, label="rope") ax.axvline(x=self.rope, color="#ffad2f", linewidth=2) targs = (self.df, self.mean, np.sqrt(self.var)) xs = np.linspace(min(stats.t.ppf(0.005, *targs), -1.05 * self.rope), max(stats.t.ppf(0.995, *targs), 1.05 * self.rope), 100) ys = stats.t.pdf(xs, *targs) ax.plot(xs, ys, color="#2f56e0", linewidth=2, label="pdf") ax.fill_between(xs, ys, np.zeros(100), color="#34ccff") ax.legend() return fig class CorrelatedTTest: """ Compute and plot a Bayesian correlated t-test """ def __new__(cls, x, y, rope=0, runs=1, *, names=None, nsamples=50000): check_args(x, y, rope) if not int(runs) == runs > 0: raise ValueError('Number of runs must be a positive integer') if len(x) % round(runs) != 0: raise ValueError("Number of measurements is not divisible by number of runs") mean, var, df = cls.compute_statistics(x, y, runs) return Posterior(mean, var, df, rope, np.mean(x), np.mean(y), names=names, nsamples=nsamples) @classmethod def compute_statistics(cls, x, y, runs=1): """ Compute statistics (mean, variance) from the differences. The number of runs is needed to compute the Nadeau-Bengio correction for underestimated variance. Args: x (np.array): a vector of scores for the first model y (np.array): a vector of scores for the second model runs (int): number of repetitions of cross validation (default: 1) Returns: mean, var, degrees_of_freedom """ diff = y - x n = len(diff) nfolds = n / runs mean = np.mean(diff) var = np.var(diff, ddof=1) var *= 1 / n + 1 / (nfolds - 1) # Nadeau-Bengio's correction return mean, var, n - 1 @classmethod def sample(cls, x, y, runs=1, *, nsamples=50000): """ Return a sample of posterior distribution for the given data Args: x (np.array): a vector of scores for the first model y (np.array): a vector of scores for the second model runs (int): number of repetitions of cross validation (default: 1) nsamples (int): the number of samples (default: 50000) Returns: mean, var, degrees_of_freedom """ return cls(x, y, runs=runs, nsamples=nsamples).sample @classmethod def probs(cls, x, y, rope=0, runs=1): """ Compute and return probabilities Probabilities are not computed from a sample posterior but from cumulative Student distribution. Args: x (np.array): a vector of scores for the first model y (np.array): a vector of scores for the second model rope (float): the width of the region of practical equivalence (default: 0) runs (int): number of repetitions of cross validation (default: 1) Returns: `(p_left, p_rope, p_right)` if `rope > 0`; otherwise `(p_left, p_right)`. """ # new returns an instance of Test, not CorrelatedTTest # pylint: disable=no-value-for-parameter return cls(x, y, rope, runs).probs() @classmethod def plot(cls, x, y, rope=0, runs=1, *, names=None): """ Plot the posterior Student distribution as a histogram. Args: x (np.array): a vector of scores for the first model y (np.array): a vector of scores for the second model rope (float): the width of the region of practical equivalence (default: 0) names (tuple of str): names of classifiers Returns: matplotlib figure """ # new returns an instance of Test, not CorrelatedTTest # pylint: disable=no-value-for-parameter return cls(x, y, rope, runs).plot(names) def two_on_single(x, y, rope=0, runs=1, *, names=None, plot=False): """ Compute probabilities using a Bayesian correlated t-test and, optionally, draw a histogram. The test assumes that the classifiers were evaluated using cross validation. Argument `runs` gives the number of repetitions of cross-validation. For more details, see :obj:`CorrelatedTTest` Args: x (np.array): a vector of scores for the first model y (np.array): a vector of scores for the second model rope (float): the width of the region of practical equivalence (default: 0) runs (int): the number of repetitions of cross validation (default: 1) nsamples (int): the number of samples (default: 50000) plot (bool): if `True`, the function also return a histogram (default: False) names (tuple of str): names of classifiers (ignored if `plot` is `False`) Returns: `(p_left, p_rope, p_right)` if `rope > 0`; otherwise `(p_left, p_right)`. If `plot=True`, the function also returns a matplotlib figure, that is, `((p_left, p_rope, p_right), fig)` """ return call_shortcut(CorrelatedTTest, x, y, rope, plot=plot, names=names, runs=runs)
[ "numpy.full", "numpy.random.standard_t", "numpy.zeros", "scipy.stats.t.ppf", "numpy.mean", "scipy.stats.t.pdf", "functools.lru_cache", "numpy.var", "scipy.stats.t.cdf", "numpy.sqrt" ]
[((1179, 1191), 'functools.lru_cache', 'lru_cache', (['(1)'], {}), '(1)\n', (1188, 1191), False, 'from functools import lru_cache\n'), ((5206, 5219), 'numpy.mean', 'np.mean', (['diff'], {}), '(diff)\n', (5213, 5219), True, 'import numpy as np\n'), ((5234, 5254), 'numpy.var', 'np.var', (['diff'], {'ddof': '(1)'}), '(diff, ddof=1)\n', (5240, 5254), True, 'import numpy as np\n'), ((1523, 1559), 'numpy.full', 'np.full', (['(self.nsamples,)', 'self.mean'], {}), '((self.nsamples,), self.mean)\n', (1530, 1559), True, 'import numpy as np\n'), ((2030, 2047), 'numpy.sqrt', 'np.sqrt', (['self.var'], {}), '(self.var)\n', (2037, 2047), True, 'import numpy as np\n'), ((3708, 3731), 'scipy.stats.t.pdf', 'stats.t.pdf', (['xs', '*targs'], {}), '(xs, *targs)\n', (3719, 3731), False, 'from scipy import stats\n'), ((4486, 4496), 'numpy.mean', 'np.mean', (['x'], {}), '(x)\n', (4493, 4496), True, 'import numpy as np\n'), ((4498, 4508), 'numpy.mean', 'np.mean', (['y'], {}), '(y)\n', (4505, 4508), True, 'import numpy as np\n'), ((1605, 1622), 'numpy.sqrt', 'np.sqrt', (['self.var'], {}), '(self.var)\n', (1612, 1622), True, 'import numpy as np\n'), ((1625, 1669), 'numpy.random.standard_t', 'np.random.standard_t', (['self.df', 'self.nsamples'], {}), '(self.df, self.nsamples)\n', (1645, 1669), True, 'import numpy as np\n'), ((2454, 2492), 'scipy.stats.t.cdf', 'stats.t.cdf', (['(-self.rope)', '*t_parameters'], {}), '(-self.rope, *t_parameters)\n', (2465, 2492), False, 'from scipy import stats\n'), ((3477, 3494), 'numpy.sqrt', 'np.sqrt', (['self.var'], {}), '(self.var)\n', (3484, 3494), True, 'import numpy as np\n'), ((3839, 3852), 'numpy.zeros', 'np.zeros', (['(100)'], {}), '(100)\n', (3847, 3852), True, 'import numpy as np\n'), ((2210, 2239), 'scipy.stats.t.cdf', 'stats.t.cdf', (['(0)', '*t_parameters'], {}), '(0, *t_parameters)\n', (2221, 2239), False, 'from scipy import stats\n'), ((2518, 2555), 'scipy.stats.t.cdf', 'stats.t.cdf', (['self.rope', '*t_parameters'], {}), '(self.rope, *t_parameters)\n', (2529, 2555), False, 'from scipy import stats\n'), ((3529, 3555), 'scipy.stats.t.ppf', 'stats.t.ppf', (['(0.005)', '*targs'], {}), '(0.005, *targs)\n', (3540, 3555), False, 'from scipy import stats\n'), ((3610, 3636), 'scipy.stats.t.ppf', 'stats.t.ppf', (['(0.995)', '*targs'], {}), '(0.995, *targs)\n', (3621, 3636), False, 'from scipy import stats\n')]
import os import numpy as np import scipy.io as sio from PIL import Image from deephar.utils import * def load_mpii_mat_annotation(filename): mat = sio.loadmat(filename) annot_tr = mat['annot_tr'] annot_val = mat['annot_val'] # Respect the order of TEST (0), TRAIN (1), and VALID (2) rectidxs = [None, annot_tr[0,:], annot_val[0,:]] images = [None, annot_tr[1,:], annot_val[1,:]] annorect = [None, annot_tr[2,:], annot_val[2,:]] return rectidxs, images, annorect def serialize_annorect(rectidxs, annorect): assert len(rectidxs) == len(annorect) sample_list = [] for i in range(len(rectidxs)): rec = rectidxs[i] for j in range(rec.size): idx = rec[j,0]-1 # Convert idx from Matlab ann = annorect[i][idx,0] annot = {} annot['head'] = ann['head'][0,0][0] annot['objpos'] = ann['objpos'][0,0][0] annot['scale'] = ann['scale'][0,0][0,0] annot['pose'] = ann['pose'][0,0] annot['imgidx'] = i sample_list.append(annot) return sample_list def calc_head_size(head_annot): head = np.array([float(head_annot[0]), float(head_annot[1]), float(head_annot[2]), float(head_annot[3])]) return 0.6 * np.linalg.norm(head[0:2] - head[2:4]) class MpiiSinglePerson(object): """Implementation of the MPII dataset for single person. """ def __init__(self, dataset_path, dataconf, poselayout=pa16j2d, remove_outer_joints=True): self.dataset_path = dataset_path self.dataconf = dataconf self.poselayout = poselayout self.remove_outer_joints = remove_outer_joints self.load_annotations(os.path.join(dataset_path, 'annotations.mat')) def load_annotations(self, filename): try: rectidxs, images, annorect = load_mpii_mat_annotation(filename) self.samples = {} self.samples[TEST_MODE] = [] # No samples for test self.samples[TRAIN_MODE] = serialize_annorect( rectidxs[TRAIN_MODE], annorect[TRAIN_MODE]) self.samples[VALID_MODE] = serialize_annorect( rectidxs[VALID_MODE], annorect[VALID_MODE]) self.images = images except: warning('Error loading the MPII dataset!') raise def load_image(self, key, mode): try: annot = self.samples[mode][key] image = self.images[mode][annot['imgidx']][0] imgt = T(Image.open(os.path.join( self.dataset_path, 'images', image))) except: warning('Error loading sample key/mode: %d/%d' % (key, mode)) raise return imgt def get_data(self, key, mode, fast_crop=False): output = {} if mode == TRAIN_MODE: dconf = self.dataconf.random_data_generator() else: dconf = self.dataconf.get_fixed_config() imgt = self.load_image(key, mode) annot = self.samples[mode][key] scale = 1.25*annot['scale'] objpos = np.array([annot['objpos'][0], annot['objpos'][1] + 12*scale]) objpos += scale * np.array([dconf['transx'], dconf['transy']]) winsize = 200 * dconf['scale'] * scale winsize = (winsize, winsize) output['bbox'] = objposwin_to_bbox(objpos, winsize) if fast_crop: """Slightly faster method, but gives lower precision.""" imgt.crop_resize_rotate(objpos, winsize, self.dataconf.crop_resolution, dconf['angle']) else: imgt.rotate_crop(dconf['angle'], objpos, winsize) imgt.resize(self.dataconf.crop_resolution) if dconf['hflip'] == 1: imgt.horizontal_flip() imgt.normalize_affinemap() output['frame'] = normalize_channels(imgt.asarray(), channel_power=dconf['chpower']) p = np.empty((self.poselayout.num_joints, self.poselayout.dim)) p[:] = np.nan head = annot['head'] p[self.poselayout.map_to_mpii, 0:2] = \ transform_2d_points(imgt.afmat, annot['pose'].T, transpose=True) if imgt.hflip: p = p[self.poselayout.map_hflip, :] # Set invalid joints and NaN values as an invalid value p[np.isnan(p)] = -1e9 v = np.expand_dims(get_visible_joints(p[:,0:2]), axis=-1) if self.remove_outer_joints: p[(v==0)[:,0],:] = -1e9 output['pose'] = np.concatenate((p, v), axis=-1) output['headsize'] = calc_head_size(annot['head']) output['afmat'] = imgt.afmat.copy() return output def get_shape(self, dictkey): if dictkey == 'frame': return self.dataconf.input_shape if dictkey == 'pose': return (self.poselayout.num_joints, self.poselayout.dim+1) if dictkey == 'headsize': return (1,) if dictkey == 'afmat': return (3, 3) raise Exception('Invalid dictkey on get_shape!') def get_length(self, mode): return len(self.samples[mode])
[ "scipy.io.loadmat", "numpy.empty", "numpy.isnan", "numpy.array", "numpy.linalg.norm", "os.path.join", "numpy.concatenate" ]
[((156, 177), 'scipy.io.loadmat', 'sio.loadmat', (['filename'], {}), '(filename)\n', (167, 177), True, 'import scipy.io as sio\n'), ((1281, 1318), 'numpy.linalg.norm', 'np.linalg.norm', (['(head[0:2] - head[2:4])'], {}), '(head[0:2] - head[2:4])\n', (1295, 1318), True, 'import numpy as np\n'), ((3129, 3192), 'numpy.array', 'np.array', (["[annot['objpos'][0], annot['objpos'][1] + 12 * scale]"], {}), "([annot['objpos'][0], annot['objpos'][1] + 12 * scale])\n", (3137, 3192), True, 'import numpy as np\n'), ((3975, 4034), 'numpy.empty', 'np.empty', (['(self.poselayout.num_joints, self.poselayout.dim)'], {}), '((self.poselayout.num_joints, self.poselayout.dim))\n', (3983, 4034), True, 'import numpy as np\n'), ((4547, 4578), 'numpy.concatenate', 'np.concatenate', (['(p, v)'], {'axis': '(-1)'}), '((p, v), axis=-1)\n', (4561, 4578), True, 'import numpy as np\n'), ((1738, 1783), 'os.path.join', 'os.path.join', (['dataset_path', '"""annotations.mat"""'], {}), "(dataset_path, 'annotations.mat')\n", (1750, 1783), False, 'import os\n'), ((3217, 3261), 'numpy.array', 'np.array', (["[dconf['transx'], dconf['transy']]"], {}), "([dconf['transx'], dconf['transy']])\n", (3225, 3261), True, 'import numpy as np\n'), ((4362, 4373), 'numpy.isnan', 'np.isnan', (['p'], {}), '(p)\n', (4370, 4373), True, 'import numpy as np\n'), ((2565, 2613), 'os.path.join', 'os.path.join', (['self.dataset_path', '"""images"""', 'image'], {}), "(self.dataset_path, 'images', image)\n", (2577, 2613), False, 'import os\n')]
#!/usr/bin/env python3 # Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import math from collections import Counter from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Union import numpy as np from ax.core.generator_run import GeneratorRun from ax.core.observation import Observation, ObservationFeatures from ax.core.parameter import ChoiceParameter, FixedParameter, RangeParameter from ax.core.types import TParameterization from ax.modelbridge.base import ModelBridge from ax.modelbridge.prediction_utils import predict_at_point from ax.modelbridge.transforms.ivw import IVW from ax.plot.base import DECIMALS, PlotData, PlotInSampleArm, PlotOutOfSampleArm, Z from ax.utils.common.logger import get_logger from ax.utils.common.typeutils import not_none logger = get_logger(__name__) # Typing alias RawData = List[Dict[str, Union[str, float]]] TNullableGeneratorRunsDict = Optional[Dict[str, GeneratorRun]] def extend_range( lower: float, upper: float, percent: int = 10, log_scale: bool = False ) -> Tuple[float, float]: """Given a range of minimum and maximum values taken by values on a given axis, extend it in both directions by a given percentage to have some margin within the plot around its meaningful part. """ if upper <= lower: raise ValueError( f"`upper` should be greater than `lower`, got: {upper} (<= {lower})." ) if log_scale: raise NotImplementedError("Log scale not yet supported.") margin = (upper - lower) * percent / 100 return lower - margin, upper + margin def _format_dict(param_dict: TParameterization, name: str = "Parameterization") -> str: """Format a dictionary for labels. Args: param_dict: Dictionary to be formatted name: String name of the thing being formatted. Returns: stringified blob. """ if len(param_dict) >= 10: blob = "{} has too many items to render on hover ({}).".format( name, len(param_dict) ) else: blob = "<br><em>{}:</em><br>{}".format( name, "<br>".join("{}: {}".format(n, v) for n, v in param_dict.items()) ) return blob def _wrap_metric(metric_name: str) -> str: """Put a newline on "::" for metric names. Args: metric_name: metric name. Returns: wrapped metric name. """ if "::" in metric_name: return "<br>".join(metric_name.split("::")) else: return metric_name def _format_CI(estimate: float, sd: float, relative: bool, zval: float = Z) -> str: """Format confidence intervals given estimate and standard deviation. Args: estimate: point estimate. sd: standard deviation of point estimate. relative: if True, '%' is appended. zval: z-value associated with desired CI (e.g. 1.96 for 95% CIs) Returns: formatted confidence interval. """ return "[{lb:.{digits}f}{perc}, {ub:.{digits}f}{perc}]".format( lb=estimate - zval * sd, ub=estimate + zval * sd, digits=DECIMALS, perc="%" if relative else "", ) def arm_name_to_tuple(arm_name: str) -> Union[Tuple[int, int], Tuple[int]]: tup = arm_name.split("_") if len(tup) == 2: try: return (int(tup[0]), int(tup[1])) except ValueError: return (0,) return (0,) def arm_name_to_sort_key(arm_name: str) -> Tuple[str, int, int]: """Parses arm name into tuple suitable for reverse sorting by key Example: arm_names = ["0_0", "1_10", "1_2", "10_0", "control"] sorted(arm_names, key=arm_name_to_sort_key, reverse=True) ["control", "0_0", "1_2", "1_10", "10_0"] """ try: trial_index, arm_index = arm_name.split("_") return ("", -int(trial_index), -int(arm_index)) except (ValueError, IndexError): return (arm_name, 0, 0) def resize_subtitles(figure: Dict[str, Any], size: int): for ant in figure["layout"]["annotations"]: ant["font"].update(size=size) return figure def _filter_dict( param_dict: TParameterization, subset_keys: List[str] ) -> TParameterization: """Filter a dictionary to keys present in a given list.""" return {k: v for k, v in param_dict.items() if k in subset_keys} def _get_in_sample_arms( model: ModelBridge, metric_names: Set[str], fixed_features: Optional[ObservationFeatures] = None, data_selector: Optional[Callable[[Observation], bool]] = None, ) -> Tuple[Dict[str, PlotInSampleArm], RawData, Dict[str, TParameterization]]: """Get in-sample arms from a model with observed and predicted values for specified metrics. Returns a PlotInSampleArm object in which repeated observations are merged with IVW, and a RawData object in which every observation is listed. Fixed features input can be used to override fields of the insample arms when making model predictions. Args: model: An instance of the model bridge. metric_names: Restrict predictions to these metrics. If None, uses all metrics in the model. fixed_features: Features that should be fixed in the arms this function will obtain predictions for. data_selector: Function for selecting observations for plotting. Returns: A tuple containing - Map from arm name to PlotInSampleArm. - List of the data for each observation like:: {'metric_name': 'likes', 'arm_name': '0_0', 'mean': 1., 'sem': 0.1} - Map from arm name to parameters """ observations = model.get_training_data() training_in_design = model.training_in_design if data_selector is not None: observations = [obs for obs in observations if data_selector(obs)] training_in_design = [ model.training_in_design[i] for i, obs in enumerate(observations) if data_selector(obs) ] trial_selector = None if fixed_features is not None: trial_selector = fixed_features.trial_index # Calculate raw data raw_data = [] arm_name_to_parameters = {} for obs in observations: arm_name_to_parameters[obs.arm_name] = obs.features.parameters for j, metric_name in enumerate(obs.data.metric_names): if metric_name in metric_names: raw_data.append( { "metric_name": metric_name, "arm_name": obs.arm_name, "mean": obs.data.means[j], "sem": np.sqrt(obs.data.covariance[j, j]), } ) # Check that we have one ObservationFeatures per arm name since we # key by arm name and the model is not Multi-task. # If "TrialAsTask" is present, one of the arms is chosen based on the selected # trial index in the fixed_features. if ("TrialAsTask" not in model.transforms.keys() or trial_selector is None) and ( len(arm_name_to_parameters) != len(observations) ): logger.error( "Have observations of arms with different features but same" " name. Arbitrary one will be plotted." ) # Merge multiple measurements within each Observation with IVW to get # un-modeled prediction t = IVW(None, [], []) obs_data = t.transform_observation_data([obs.data for obs in observations], []) # Start filling in plot data in_sample_plot: Dict[str, PlotInSampleArm] = {} for i, obs in enumerate(observations): if obs.arm_name is None: raise ValueError("Observation must have arm name for plotting.") # Extract raw measurement obs_y = {} # Observed metric means. obs_se = {} # Observed metric standard errors. # Use the IVW data, not obs.data for j, metric_name in enumerate(obs_data[i].metric_names): if metric_name in metric_names: obs_y[metric_name] = obs_data[i].means[j] obs_se[metric_name] = np.sqrt(obs_data[i].covariance[j, j]) if training_in_design[i]: # Update with the input fixed features features = obs.features if fixed_features is not None: features.update_features(fixed_features) # Make a prediction. pred_y, pred_se = predict_at_point(model, features, metric_names) elif (trial_selector is not None) and ( obs.features.trial_index != trial_selector ): # check whether the observation is from the right trial # need to use raw data in the selected trial for out-of-design points continue else: pred_y = obs_y pred_se = obs_se in_sample_plot[not_none(obs.arm_name)] = PlotInSampleArm( name=not_none(obs.arm_name), y=obs_y, se=obs_se, parameters=obs.features.parameters, y_hat=pred_y, se_hat=pred_se, context_stratum=None, ) return in_sample_plot, raw_data, arm_name_to_parameters def _get_out_of_sample_arms( model: ModelBridge, generator_runs_dict: Dict[str, GeneratorRun], metric_names: Set[str], fixed_features: Optional[ObservationFeatures] = None, ) -> Dict[str, Dict[str, PlotOutOfSampleArm]]: """Get out-of-sample predictions from a model given a dict of generator runs. Fixed features input can be used to override fields of the candidate arms when making model predictions. Args: model: The model. generator_runs_dict: a mapping from generator run name to generator run. metric_names: metrics to include in the plot. Returns: A mapping from name to a mapping from arm name to plot. """ out_of_sample_plot: Dict[str, Dict[str, PlotOutOfSampleArm]] = {} for generator_run_name, generator_run in generator_runs_dict.items(): out_of_sample_plot[generator_run_name] = {} for arm in generator_run.arms: # This assumes context is None obsf = ObservationFeatures.from_arm(arm) if fixed_features is not None: obsf.update_features(fixed_features) # Make a prediction try: pred_y, pred_se = predict_at_point(model, obsf, metric_names) except Exception: # Check if it is an out-of-design arm. if not model.model_space.check_membership(obsf.parameters): # Skip this point continue else: # It should have worked raise arm_name = arm.name_or_short_signature out_of_sample_plot[generator_run_name][arm_name] = PlotOutOfSampleArm( name=arm_name, parameters=obsf.parameters, y_hat=pred_y, se_hat=pred_se, context_stratum=None, ) return out_of_sample_plot def get_plot_data( model: ModelBridge, generator_runs_dict: Dict[str, GeneratorRun], metric_names: Optional[Set[str]] = None, fixed_features: Optional[ObservationFeatures] = None, data_selector: Optional[Callable[[Observation], bool]] = None, ) -> Tuple[PlotData, RawData, Dict[str, TParameterization]]: """Format data object with metrics for in-sample and out-of-sample arms. Calculate both observed and predicted metrics for in-sample arms. Calculate predicted metrics for out-of-sample arms passed via the `generator_runs_dict` argument. In PlotData, in-sample observations are merged with IVW. In RawData, they are left un-merged and given as a list of dictionaries, one for each observation and having keys 'arm_name', 'mean', and 'sem'. Args: model: The model. generator_runs_dict: a mapping from generator run name to generator run. metric_names: Restrict predictions to this set. If None, all metrics in the model will be returned. fixed_features: Fixed features to use when making model predictions. data_selector: Function for selecting observations for plotting. Returns: A tuple containing - PlotData object with in-sample and out-of-sample predictions. - List of observations like:: {'metric_name': 'likes', 'arm_name': '0_1', 'mean': 1., 'sem': 0.1}. - Mapping from arm name to parameters. """ metrics_plot = model.metric_names if metric_names is None else metric_names in_sample_plot, raw_data, cond_name_to_parameters = _get_in_sample_arms( model=model, metric_names=metrics_plot, fixed_features=fixed_features, data_selector=data_selector, ) out_of_sample_plot = _get_out_of_sample_arms( model=model, generator_runs_dict=generator_runs_dict, metric_names=metrics_plot, fixed_features=fixed_features, ) status_quo_name = None if model.status_quo is None else model.status_quo.arm_name plot_data = PlotData( metrics=list(metrics_plot), in_sample=in_sample_plot, out_of_sample=out_of_sample_plot, status_quo_name=status_quo_name, ) return plot_data, raw_data, cond_name_to_parameters def get_range_parameter(model: ModelBridge, param_name: str) -> RangeParameter: """ Get the range parameter with the given name from the model. Throws if parameter doesn't exist or is not a range parameter. Args: model: The model. param_name: The name of the RangeParameter to be found. Returns: The RangeParameter named `param_name`. """ range_param = model.model_space.parameters.get(param_name) if range_param is None: raise ValueError(f"Parameter `{param_name}` does not exist.") if not isinstance(range_param, RangeParameter): raise ValueError(f"{param_name} is not a RangeParameter") return range_param def get_range_parameters(model: ModelBridge) -> List[RangeParameter]: """ Get a list of range parameters from a model. Args: model: The model. Returns: List of RangeParameters. """ return [ parameter for parameter in model.model_space.parameters.values() if isinstance(parameter, RangeParameter) ] def get_grid_for_parameter(parameter: RangeParameter, density: int) -> np.ndarray: """Get a grid of points along the range of the parameter. Will be a log-scale grid if parameter is log scale. Args: parameter: Parameter for which to generate grid. density: Number of points in the grid. """ is_log = parameter.log_scale if is_log: grid = np.linspace( np.log10(parameter.lower), np.log10(parameter.upper), density ) grid = 10 ** grid else: grid = np.linspace(parameter.lower, parameter.upper, density) return grid def get_fixed_values( model: ModelBridge, slice_values: Optional[Dict[str, Any]] = None, trial_index: Optional[int] = None, ) -> TParameterization: """Get fixed values for parameters in a slice plot. If there is an in-design status quo, those values will be used. Otherwise, the mean of RangeParameters or the mode of ChoiceParameters is used. Any value in slice_values will override the above. Args: model: ModelBridge being used for plotting slice_values: Map from parameter name to value at which is should be fixed. Returns: Map from parameter name to fixed value. """ if trial_index is not None: if slice_values is None: slice_values = {} slice_values["TRIAL_PARAM"] = str(trial_index) # Check if status_quo is in design if model.status_quo is not None and model.model_space.check_membership( model.status_quo.features.parameters ): setx = model.status_quo.features.parameters else: observations = model.get_training_data() setx = {} for p_name, parameter in model.model_space.parameters.items(): # Exclude out of design status quo (no parameters) vals = [ obs.features.parameters[p_name] for obs in observations if ( len(obs.features.parameters) > 0 and parameter.validate(obs.features.parameters[p_name]) ) ] if isinstance(parameter, FixedParameter): setx[p_name] = parameter.value elif isinstance(parameter, ChoiceParameter): setx[p_name] = Counter(vals).most_common(1)[0][0] elif isinstance(parameter, RangeParameter): setx[p_name] = parameter.cast(np.mean(vals)) if slice_values is not None: # slice_values has type Dictionary[str, Any] setx.update(slice_values) return setx # Utility methods ported from JS def contour_config_to_trace(config): # Load from config arm_data = config["arm_data"] density = config["density"] grid_x = config["grid_x"] grid_y = config["grid_y"] f = config["f"] lower_is_better = config["lower_is_better"] metric = config["metric"] rel = config["rel"] sd = config["sd"] xvar = config["xvar"] yvar = config["yvar"] green_scale = config["green_scale"] green_pink_scale = config["green_pink_scale"] blue_scale = config["blue_scale"] # format data res = relativize_data(f, sd, rel, arm_data, metric) f_final = res[0] sd_final = res[1] # calculate max of abs(outcome), used for colorscale f_absmax = max(abs(min(f_final)), max(f_final)) # transform to nested array f_plt = [] for ind in range(0, len(f_final), density): f_plt.append(f_final[ind : ind + density]) sd_plt = [] for ind in range(0, len(sd_final), density): sd_plt.append(sd_final[ind : ind + density]) CONTOUR_CONFIG = { "autocolorscale": False, "autocontour": True, "contours": {"coloring": "heatmap"}, "hoverinfo": "x+y+z", "ncontours": int(density / 2), "type": "contour", "x": grid_x, "y": grid_y, } if rel: f_scale = reversed(green_pink_scale) if lower_is_better else green_pink_scale else: f_scale = green_scale f_trace = { "colorbar": { "x": 0.45, "y": 0.5, "ticksuffix": "%" if rel else "", "tickfont": {"size": 8}, }, "colorscale": [(i / (len(f_scale) - 1), rgb(v)) for i, v in enumerate(f_scale)], "xaxis": "x", "yaxis": "y", "z": f_plt, # zmax and zmin are ignored if zauto is true "zauto": not rel, "zmax": f_absmax, "zmin": -f_absmax, } sd_trace = { "colorbar": { "x": 1, "y": 0.5, "ticksuffix": "%" if rel else "", "tickfont": {"size": 8}, }, "colorscale": [ (i / (len(blue_scale) - 1), rgb(v)) for i, v in enumerate(blue_scale) ], "xaxis": "x2", "yaxis": "y2", "z": sd_plt, } f_trace.update(CONTOUR_CONFIG) sd_trace.update(CONTOUR_CONFIG) # get in-sample arms arm_names = list(arm_data["in_sample"].keys()) arm_x = [ arm_data["in_sample"][arm_name]["parameters"][xvar] for arm_name in arm_names ] arm_y = [ arm_data["in_sample"][arm_name]["parameters"][yvar] for arm_name in arm_names ] arm_text = [] for arm_name in arm_names: atext = f"Arm {arm_name}" params = arm_data["in_sample"][arm_name]["parameters"] ys = arm_data["in_sample"][arm_name]["y"] ses = arm_data["in_sample"][arm_name]["se"] for yname in ys.keys(): sem_str = f"{ses[yname]}" if ses[yname] is None else f"{ses[yname]:.6g}" y_str = f"{ys[yname]}" if ys[yname] is None else f"{ys[yname]:.6g}" atext += f"<br>{yname}: {y_str} (SEM: {sem_str})" for pname in params.keys(): pval = params[pname] pstr = f"{pval:.6g}" if isinstance(pval, float) else f"{pval}" atext += f"<br>{pname}: {pstr}" arm_text.append(atext) # configs for in-sample arms base_in_sample_arm_config = { "hoverinfo": "text", "legendgroup": "In-sample", "marker": {"color": "black", "symbol": 1, "opacity": 0.5}, "mode": "markers", "name": "In-sample", "text": arm_text, "type": "scatter", "x": arm_x, "y": arm_y, } f_in_sample_arm_trace = {"xaxis": "x", "yaxis": "y"} sd_in_sample_arm_trace = {"showlegend": False, "xaxis": "x2", "yaxis": "y2"} f_in_sample_arm_trace.update(base_in_sample_arm_config) sd_in_sample_arm_trace.update(base_in_sample_arm_config) traces = [f_trace, sd_trace, f_in_sample_arm_trace, sd_in_sample_arm_trace] # iterate over out-of-sample arms for i, generator_run_name in enumerate(arm_data["out_of_sample"].keys()): symbol = i + 2 # symbols starts from 2 for candidate markers ax = [] ay = [] atext = [] for arm_name in arm_data["out_of_sample"][generator_run_name].keys(): ax.append( arm_data["out_of_sample"][generator_run_name][arm_name]["parameters"][ xvar ] ) ay.append( arm_data["out_of_sample"][generator_run_name][arm_name]["parameters"][ yvar ] ) atext.append("<em>Candidate " + arm_name + "</em>") traces.append( { "hoverinfo": "text", "legendgroup": generator_run_name, "marker": {"color": "black", "symbol": symbol, "opacity": 0.5}, "mode": "markers", "name": generator_run_name, "text": atext, "type": "scatter", "xaxis": "x", "x": ax, "yaxis": "y", "y": ay, } ) traces.append( { "hoverinfo": "text", "legendgroup": generator_run_name, "marker": {"color": "black", "symbol": symbol, "opacity": 0.5}, "mode": "markers", "name": "In-sample", "showlegend": False, "text": atext, "type": "scatter", "x": ax, "xaxis": "x2", "y": ay, "yaxis": "y2", } ) return traces def axis_range(grid: List[float], is_log: bool) -> List[float]: if is_log: return [math.log10(min(grid)), math.log10(max(grid))] else: return [min(grid), max(grid)] def relativize(m_t: float, sem_t: float, m_c: float, sem_c: float) -> List[float]: r_hat = (m_t - m_c) / abs(m_c) - sem_c ** 2 * m_t / abs(m_c) ** 3 variance = (sem_t ** 2 + (m_t / m_c * sem_c) ** 2) / m_c ** 2 return [r_hat, math.sqrt(variance)] def relativize_data( f: List[float], sd: List[float], rel: bool, arm_data: Dict[Any, Any], metric: str ) -> List[List[float]]: # if relative, extract status quo & compute ratio f_final = [] if rel else f sd_final = [] if rel else sd if rel: f_sq = arm_data["in_sample"][arm_data["status_quo_name"]]["y"][metric] sd_sq = arm_data["in_sample"][arm_data["status_quo_name"]]["se"][metric] for i in range(len(f)): res = relativize(f[i], sd[i], f_sq, sd_sq) f_final.append(100 * res[0]) sd_final.append(100 * res[1]) return [f_final, sd_final] def rgb(arr: List[int]) -> str: return "rgb({},{},{})".format(*arr) def infer_is_relative( model: ModelBridge, metrics: List[str], non_constraint_rel: bool ) -> Dict[str, bool]: """Determine whether or not to relativize a metric. Metrics that are constraints will get this decision from their `relative` flag. Other metrics will use the `default_rel`. Args: model: model fit on metrics. metrics: list of metric names. non_constraint_rel: whether or not to relativize non-constraint metrics Returns: Dict[str, bool] containing whether or not to relativize each input metric. """ relative = {} constraint_relativity = {} if model._optimization_config: constraints = not_none(model._optimization_config).outcome_constraints constraint_relativity = { constraint.metric.name: constraint.relative for constraint in constraints } for metric in metrics: if metric not in constraint_relativity: relative[metric] = non_constraint_rel else: relative[metric] = constraint_relativity[metric] return relative def slice_config_to_trace( arm_data, arm_name_to_parameters, f, fit_data, grid, metric, param, rel, setx, sd, is_log, visible, ): # format data res = relativize_data(f, sd, rel, arm_data, metric) f_final = res[0] sd_final = res[1] # get data for standard deviation fill plot sd_upper = [] sd_lower = [] for i in range(len(sd)): sd_upper.append(f_final[i] + 2 * sd_final[i]) sd_lower.append(f_final[i] - 2 * sd_final[i]) grid_rev = list(reversed(grid)) sd_lower_rev = list(reversed(sd_lower)) sd_x = grid + grid_rev sd_y = sd_upper + sd_lower_rev # get data for observed arms and error bars arm_x = [] arm_y = [] arm_sem = [] for row in fit_data: parameters = arm_name_to_parameters[row["arm_name"]] plot = True for p in setx.keys(): if p != param and parameters[p] != setx[p]: plot = False if plot: arm_x.append(parameters[param]) arm_y.append(row["mean"]) arm_sem.append(row["sem"]) arm_res = relativize_data(arm_y, arm_sem, rel, arm_data, metric) arm_y_final = arm_res[0] arm_sem_final = [x * 2 if x is not None else None for x in arm_res[1]] # create traces f_trace = { "x": grid, "y": f_final, "showlegend": False, "hoverinfo": "x+y", "line": {"color": "rgba(128, 177, 211, 1)"}, "visible": visible, } arms_trace = { "x": arm_x, "y": arm_y_final, "mode": "markers", "error_y": { "type": "data", "array": arm_sem_final, "visible": True, "color": "black", }, "line": {"color": "black"}, "showlegend": False, "hoverinfo": "x+y", "visible": visible, } sd_trace = { "x": sd_x, "y": sd_y, "fill": "toself", "fillcolor": "rgba(128, 177, 211, 0.2)", "line": {"color": "rgba(128, 177, 211, 0.0)"}, "showlegend": False, "hoverinfo": "none", "visible": visible, } traces = [sd_trace, f_trace, arms_trace] # iterate over out-of-sample arms for i, generator_run_name in enumerate(arm_data["out_of_sample"].keys()): ax = [] ay = [] asem = [] atext = [] for arm_name in arm_data["out_of_sample"][generator_run_name].keys(): parameters = arm_data["out_of_sample"][generator_run_name][arm_name][ "parameters" ] plot = True for p in setx.keys(): if p != param and parameters[p] != setx[p]: plot = False if plot: ax.append(parameters[param]) ay.append( arm_data["out_of_sample"][generator_run_name][arm_name]["y_hat"][ metric ] ) asem.append( arm_data["out_of_sample"][generator_run_name][arm_name]["se_hat"][ metric ] ) atext.append("<em>Candidate " + arm_name + "</em>") out_of_sample_arm_res = relativize_data(ay, asem, rel, arm_data, metric) ay_final = out_of_sample_arm_res[0] asem_final = [x * 2 for x in out_of_sample_arm_res[1]] traces.append( { "hoverinfo": "text", "legendgroup": generator_run_name, "marker": {"color": "black", "symbol": i + 1, "opacity": 0.5}, "mode": "markers", "error_y": { "type": "data", "array": asem_final, "visible": True, "color": "black", }, "name": generator_run_name, "text": atext, "type": "scatter", "xaxis": "x", "x": ax, "yaxis": "y", "y": ay_final, "visible": visible, } ) return traces def build_filter_trial(keep_trial_indices: List[int]) -> Callable[[Observation], bool]: """Creates a callable that filters observations based on trial_index""" def trial_filter(obs: Observation) -> bool: return obs.features.trial_index in keep_trial_indices return trial_filter def compose_annotation( caption: str, x: float = 0.0, y: float = -0.15 ) -> List[Dict[str, Any]]: if not caption: return [] return [ { "showarrow": False, "text": caption, "x": x, "xanchor": "left", "xref": "paper", "y": y, "yanchor": "top", "yref": "paper", "align": "left", }, ]
[ "math.sqrt", "collections.Counter", "ax.core.observation.ObservationFeatures.from_arm", "numpy.mean", "numpy.linspace", "ax.modelbridge.transforms.ivw.IVW", "numpy.log10", "ax.utils.common.logger.get_logger", "ax.modelbridge.prediction_utils.predict_at_point", "ax.utils.common.typeutils.not_none",...
[((914, 934), 'ax.utils.common.logger.get_logger', 'get_logger', (['__name__'], {}), '(__name__)\n', (924, 934), False, 'from ax.utils.common.logger import get_logger\n'), ((7452, 7469), 'ax.modelbridge.transforms.ivw.IVW', 'IVW', (['None', '[]', '[]'], {}), '(None, [], [])\n', (7455, 7469), False, 'from ax.modelbridge.transforms.ivw import IVW\n'), ((15066, 15120), 'numpy.linspace', 'np.linspace', (['parameter.lower', 'parameter.upper', 'density'], {}), '(parameter.lower, parameter.upper, density)\n', (15077, 15120), True, 'import numpy as np\n'), ((23375, 23394), 'math.sqrt', 'math.sqrt', (['variance'], {}), '(variance)\n', (23384, 23394), False, 'import math\n'), ((8498, 8545), 'ax.modelbridge.prediction_utils.predict_at_point', 'predict_at_point', (['model', 'features', 'metric_names'], {}), '(model, features, metric_names)\n', (8514, 8545), False, 'from ax.modelbridge.prediction_utils import predict_at_point\n'), ((8924, 8946), 'ax.utils.common.typeutils.not_none', 'not_none', (['obs.arm_name'], {}), '(obs.arm_name)\n', (8932, 8946), False, 'from ax.utils.common.typeutils import not_none\n'), ((10248, 10281), 'ax.core.observation.ObservationFeatures.from_arm', 'ObservationFeatures.from_arm', (['arm'], {}), '(arm)\n', (10276, 10281), False, 'from ax.core.observation import Observation, ObservationFeatures\n'), ((10940, 11057), 'ax.plot.base.PlotOutOfSampleArm', 'PlotOutOfSampleArm', ([], {'name': 'arm_name', 'parameters': 'obsf.parameters', 'y_hat': 'pred_y', 'se_hat': 'pred_se', 'context_stratum': 'None'}), '(name=arm_name, parameters=obsf.parameters, y_hat=pred_y,\n se_hat=pred_se, context_stratum=None)\n', (10958, 11057), False, 'from ax.plot.base import DECIMALS, PlotData, PlotInSampleArm, PlotOutOfSampleArm, Z\n'), ((14943, 14968), 'numpy.log10', 'np.log10', (['parameter.lower'], {}), '(parameter.lower)\n', (14951, 14968), True, 'import numpy as np\n'), ((14970, 14995), 'numpy.log10', 'np.log10', (['parameter.upper'], {}), '(parameter.upper)\n', (14978, 14995), True, 'import numpy as np\n'), ((24778, 24814), 'ax.utils.common.typeutils.not_none', 'not_none', (['model._optimization_config'], {}), '(model._optimization_config)\n', (24786, 24814), False, 'from ax.utils.common.typeutils import not_none\n'), ((8176, 8213), 'numpy.sqrt', 'np.sqrt', (['obs_data[i].covariance[j, j]'], {}), '(obs_data[i].covariance[j, j])\n', (8183, 8213), True, 'import numpy as np\n'), ((8984, 9006), 'ax.utils.common.typeutils.not_none', 'not_none', (['obs.arm_name'], {}), '(obs.arm_name)\n', (8992, 9006), False, 'from ax.utils.common.typeutils import not_none\n'), ((10462, 10505), 'ax.modelbridge.prediction_utils.predict_at_point', 'predict_at_point', (['model', 'obsf', 'metric_names'], {}), '(model, obsf, metric_names)\n', (10478, 10505), False, 'from ax.modelbridge.prediction_utils import predict_at_point\n'), ((6707, 6741), 'numpy.sqrt', 'np.sqrt', (['obs.data.covariance[j, j]'], {}), '(obs.data.covariance[j, j])\n', (6714, 6741), True, 'import numpy as np\n'), ((16983, 16996), 'numpy.mean', 'np.mean', (['vals'], {}), '(vals)\n', (16990, 16996), True, 'import numpy as np\n'), ((16846, 16859), 'collections.Counter', 'Counter', (['vals'], {}), '(vals)\n', (16853, 16859), False, 'from collections import Counter\n')]
""" Validate calculation bfield calculation from line segments ================================================================= """ import numpy as np import matplotlib.pyplot as plt import time as t from bfieldtools.line_magnetics import magnetic_field """ Bfield calculation from circular current loops using elliptic integrals """ def double_factorial(n): if n <= 0: return 1 else: return n * double_factorial(n - 2) def bfield_iterative(x, y, z, x_c, y_c, z_c, r, I, n): """Compute b field of a current loop using an iterative method to estimate elliptic integrals. Parameters: x, y, z: Evaluation points in 3D space. Accepts matrices and integers. x_c, y_c, z_c: Coordinates of the center point of the current loop. r: Radius of the current loop. I: Current of the current loop. n: Number of terms in the serie expansion. Returns: bfiels (N_points, 3) at evaluation points. This calculation is based on paper by <NAME>, Jr (General Relation for the Vector Magnetic Field of aCircular Current Loop: A Closer Look). DOI: 10.1109/TMAG.2003.808597 """ st2 = t.time() np.seterr(divide="ignore", invalid="ignore") u0 = 4 * np.pi * 1e-7 Y = u0 * I / (2 * np.pi) # Change to cylideric coordinates rc = np.sqrt(np.power(x - x_c, 2) + np.power(y - y_c, 2)) # Coefficients for estimating elliptic integrals with nth degree series # expansion using Legendre polynomials m = 4 * r * rc / (np.power((rc + r), 2) + np.power((z - z_c), 2)) K = 1 E = 1 for i in range(1, n + 1): K = K + np.square( double_factorial(2 * i - 1) / double_factorial(2 * i) ) * np.power(m, i) E = E - np.square( double_factorial(2 * i - 1) / double_factorial(2 * i) ) * np.power(m, i) / (2 * i - 1) K = K * np.pi / 2 E = E * np.pi / 2 # Calculation of radial and axial components of B-field Brc = ( Y * (z - z_c) / (rc * np.sqrt(np.power((rc + r), 2) + np.power((z - z_c), 2))) * ( -K + E * (np.power(rc, 2) + np.power(r, 2) + np.power((z - z_c), 2)) / (np.power((rc - r), 2) + np.power((z - z_c), 2)) ) ) Bz = ( Y / (np.sqrt(np.power((rc + r), 2) + np.power((z - z_c), 2))) * ( K - E * (np.power(rc, 2) - np.power(r, 2) + np.power((z - z_c), 2)) / (np.power((rc - r), 2) + np.power((z - z_c), 2)) ) ) # Set nan and inf values to 0 Brc[np.isinf(Brc)] = 0 Bz[np.isnan(Bz)] = 0 Brc[np.isnan(Brc)] = 0 Bz[np.isinf(Bz)] = 0 # Change back to cartesian coordinates Bx = Brc * (x - x_c) / rc By = Brc * (y - y_c) / rc # Change nan values from coordinate transfer to 0 Bx[np.isnan(Bx)] = 0 By[np.isnan(By)] = 0 B = np.zeros((3, X.size), dtype=np.float64) B[0] = Bx.flatten() B[1] = By.flatten() B[2] = Bz.flatten() et2 = t.time() print("Execution time for iterative method is:", et2 - st2) return B.T """ Plot field of a circular current path """ x = np.linspace(-1, 1, 100) Ntheta = 10000 theta = np.linspace(0, 2 * np.pi, Ntheta) vertices = np.zeros((Ntheta, 3), dtype=np.float64) vertices[:, 0] = np.cos(theta) * 0.1 vertices[:, 1] = np.sin(theta) * 0.1 vertices[:, 2] = 0.2 X, Y = np.meshgrid(x, x, indexing="ij") Z = np.zeros((x.size, x.size)) points = np.zeros((3, X.size), dtype=np.float64) points[0] = X.flatten() points[1] = Y.flatten() b1 = magnetic_field(vertices, points.T) # Calculates discretised bfield b2 = bfield_iterative(X, Y, Z, 0, 0, 0.2, 0.1, 1, 25) # Calculates bfield iteratively # Error between two calculation methods. berr = (b2 - b1) / b1 * 100 BE = berr.T[2] # By changing the index, errors in different components can be obtained ind = np.where(np.abs(BE) > 0.1) # The limit for significant error is set to 0.1% bpoints = points.T[ind] from mayavi import mlab mlab.figure(1) q = mlab.quiver3d(*points, *b1.T) q.glyph.glyph_source.glyph_position = "center" mlab.plot3d(*vertices.T) mlab.figure(2) q = mlab.quiver3d(*points, *b2.T) q.glyph.glyph_source.glyph_position = "center" mlab.plot3d(*vertices.T) plt.figure(3) plt.hist(berr.T[2], bins=50, density=True, histtype="bar") plt.title("Histogram of error between calculation methods.") plt.xlabel("%") #%% Plot the b-field vectors exceeding the error limit if len(bpoints > 0): from mayavi import mlab mlab.figure(3) q = mlab.quiver3d(*bpoints.T, *b1[ind].T) q.glyph.glyph_source.glyph_position = "center" mlab.plot3d(*vertices.T) q = mlab.quiver3d(*bpoints.T, *b2[ind].T) q.glyph.glyph_source.glyph_position = "center"
[ "matplotlib.pyplot.title", "mayavi.mlab.figure", "numpy.abs", "numpy.isnan", "matplotlib.pyplot.figure", "numpy.sin", "numpy.meshgrid", "mayavi.mlab.quiver3d", "numpy.power", "numpy.linspace", "bfieldtools.line_magnetics.magnetic_field", "numpy.isinf", "numpy.cos", "mayavi.mlab.plot3d", ...
[((3209, 3232), 'numpy.linspace', 'np.linspace', (['(-1)', '(1)', '(100)'], {}), '(-1, 1, 100)\n', (3220, 3232), True, 'import numpy as np\n'), ((3256, 3289), 'numpy.linspace', 'np.linspace', (['(0)', '(2 * np.pi)', 'Ntheta'], {}), '(0, 2 * np.pi, Ntheta)\n', (3267, 3289), True, 'import numpy as np\n'), ((3301, 3340), 'numpy.zeros', 'np.zeros', (['(Ntheta, 3)'], {'dtype': 'np.float64'}), '((Ntheta, 3), dtype=np.float64)\n', (3309, 3340), True, 'import numpy as np\n'), ((3444, 3476), 'numpy.meshgrid', 'np.meshgrid', (['x', 'x'], {'indexing': '"""ij"""'}), "(x, x, indexing='ij')\n", (3455, 3476), True, 'import numpy as np\n'), ((3481, 3507), 'numpy.zeros', 'np.zeros', (['(x.size, x.size)'], {}), '((x.size, x.size))\n', (3489, 3507), True, 'import numpy as np\n'), ((3518, 3557), 'numpy.zeros', 'np.zeros', (['(3, X.size)'], {'dtype': 'np.float64'}), '((3, X.size), dtype=np.float64)\n', (3526, 3557), True, 'import numpy as np\n'), ((3612, 3646), 'bfieldtools.line_magnetics.magnetic_field', 'magnetic_field', (['vertices', 'points.T'], {}), '(vertices, points.T)\n', (3626, 3646), False, 'from bfieldtools.line_magnetics import magnetic_field\n'), ((4058, 4072), 'mayavi.mlab.figure', 'mlab.figure', (['(1)'], {}), '(1)\n', (4069, 4072), False, 'from mayavi import mlab\n'), ((4077, 4106), 'mayavi.mlab.quiver3d', 'mlab.quiver3d', (['*points', '*b1.T'], {}), '(*points, *b1.T)\n', (4090, 4106), False, 'from mayavi import mlab\n'), ((4154, 4178), 'mayavi.mlab.plot3d', 'mlab.plot3d', (['*vertices.T'], {}), '(*vertices.T)\n', (4165, 4178), False, 'from mayavi import mlab\n'), ((4180, 4194), 'mayavi.mlab.figure', 'mlab.figure', (['(2)'], {}), '(2)\n', (4191, 4194), False, 'from mayavi import mlab\n'), ((4199, 4228), 'mayavi.mlab.quiver3d', 'mlab.quiver3d', (['*points', '*b2.T'], {}), '(*points, *b2.T)\n', (4212, 4228), False, 'from mayavi import mlab\n'), ((4276, 4300), 'mayavi.mlab.plot3d', 'mlab.plot3d', (['*vertices.T'], {}), '(*vertices.T)\n', (4287, 4300), False, 'from mayavi import mlab\n'), ((4302, 4315), 'matplotlib.pyplot.figure', 'plt.figure', (['(3)'], {}), '(3)\n', (4312, 4315), True, 'import matplotlib.pyplot as plt\n'), ((4316, 4374), 'matplotlib.pyplot.hist', 'plt.hist', (['berr.T[2]'], {'bins': '(50)', 'density': '(True)', 'histtype': '"""bar"""'}), "(berr.T[2], bins=50, density=True, histtype='bar')\n", (4324, 4374), True, 'import matplotlib.pyplot as plt\n'), ((4375, 4435), 'matplotlib.pyplot.title', 'plt.title', (['"""Histogram of error between calculation methods."""'], {}), "('Histogram of error between calculation methods.')\n", (4384, 4435), True, 'import matplotlib.pyplot as plt\n'), ((4436, 4451), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""%"""'], {}), "('%')\n", (4446, 4451), True, 'import matplotlib.pyplot as plt\n'), ((1178, 1186), 'time.time', 't.time', ([], {}), '()\n', (1184, 1186), True, 'import time as t\n'), ((1191, 1235), 'numpy.seterr', 'np.seterr', ([], {'divide': '"""ignore"""', 'invalid': '"""ignore"""'}), "(divide='ignore', invalid='ignore')\n", (1200, 1235), True, 'import numpy as np\n'), ((2945, 2984), 'numpy.zeros', 'np.zeros', (['(3, X.size)'], {'dtype': 'np.float64'}), '((3, X.size), dtype=np.float64)\n', (2953, 2984), True, 'import numpy as np\n'), ((3068, 3076), 'time.time', 't.time', ([], {}), '()\n', (3074, 3076), True, 'import time as t\n'), ((3358, 3371), 'numpy.cos', 'np.cos', (['theta'], {}), '(theta)\n', (3364, 3371), True, 'import numpy as np\n'), ((3395, 3408), 'numpy.sin', 'np.sin', (['theta'], {}), '(theta)\n', (3401, 3408), True, 'import numpy as np\n'), ((4563, 4577), 'mayavi.mlab.figure', 'mlab.figure', (['(3)'], {}), '(3)\n', (4574, 4577), False, 'from mayavi import mlab\n'), ((4586, 4623), 'mayavi.mlab.quiver3d', 'mlab.quiver3d', (['*bpoints.T', '*b1[ind].T'], {}), '(*bpoints.T, *b1[ind].T)\n', (4599, 4623), False, 'from mayavi import mlab\n'), ((4679, 4703), 'mayavi.mlab.plot3d', 'mlab.plot3d', (['*vertices.T'], {}), '(*vertices.T)\n', (4690, 4703), False, 'from mayavi import mlab\n'), ((4713, 4750), 'mayavi.mlab.quiver3d', 'mlab.quiver3d', (['*bpoints.T', '*b2[ind].T'], {}), '(*bpoints.T, *b2[ind].T)\n', (4726, 4750), False, 'from mayavi import mlab\n'), ((2631, 2644), 'numpy.isinf', 'np.isinf', (['Brc'], {}), '(Brc)\n', (2639, 2644), True, 'import numpy as np\n'), ((2657, 2669), 'numpy.isnan', 'np.isnan', (['Bz'], {}), '(Bz)\n', (2665, 2669), True, 'import numpy as np\n'), ((2683, 2696), 'numpy.isnan', 'np.isnan', (['Brc'], {}), '(Brc)\n', (2691, 2696), True, 'import numpy as np\n'), ((2709, 2721), 'numpy.isinf', 'np.isinf', (['Bz'], {}), '(Bz)\n', (2717, 2721), True, 'import numpy as np\n'), ((2893, 2905), 'numpy.isnan', 'np.isnan', (['Bx'], {}), '(Bx)\n', (2901, 2905), True, 'import numpy as np\n'), ((2918, 2930), 'numpy.isnan', 'np.isnan', (['By'], {}), '(By)\n', (2926, 2930), True, 'import numpy as np\n'), ((3940, 3950), 'numpy.abs', 'np.abs', (['BE'], {}), '(BE)\n', (3946, 3950), True, 'import numpy as np\n'), ((1347, 1367), 'numpy.power', 'np.power', (['(x - x_c)', '(2)'], {}), '(x - x_c, 2)\n', (1355, 1367), True, 'import numpy as np\n'), ((1370, 1390), 'numpy.power', 'np.power', (['(y - y_c)', '(2)'], {}), '(y - y_c, 2)\n', (1378, 1390), True, 'import numpy as np\n'), ((1534, 1553), 'numpy.power', 'np.power', (['(rc + r)', '(2)'], {}), '(rc + r, 2)\n', (1542, 1553), True, 'import numpy as np\n'), ((1558, 1578), 'numpy.power', 'np.power', (['(z - z_c)', '(2)'], {}), '(z - z_c, 2)\n', (1566, 1578), True, 'import numpy as np\n'), ((1737, 1751), 'numpy.power', 'np.power', (['m', 'i'], {}), '(m, i)\n', (1745, 1751), True, 'import numpy as np\n'), ((1857, 1871), 'numpy.power', 'np.power', (['m', 'i'], {}), '(m, i)\n', (1865, 1871), True, 'import numpy as np\n'), ((2239, 2258), 'numpy.power', 'np.power', (['(rc - r)', '(2)'], {}), '(rc - r, 2)\n', (2247, 2258), True, 'import numpy as np\n'), ((2263, 2283), 'numpy.power', 'np.power', (['(z - z_c)', '(2)'], {}), '(z - z_c, 2)\n', (2271, 2283), True, 'import numpy as np\n'), ((2344, 2363), 'numpy.power', 'np.power', (['(rc + r)', '(2)'], {}), '(rc + r, 2)\n', (2352, 2363), True, 'import numpy as np\n'), ((2368, 2388), 'numpy.power', 'np.power', (['(z - z_c)', '(2)'], {}), '(z - z_c, 2)\n', (2376, 2388), True, 'import numpy as np\n'), ((2524, 2543), 'numpy.power', 'np.power', (['(rc - r)', '(2)'], {}), '(rc - r, 2)\n', (2532, 2543), True, 'import numpy as np\n'), ((2548, 2568), 'numpy.power', 'np.power', (['(z - z_c)', '(2)'], {}), '(z - z_c, 2)\n', (2556, 2568), True, 'import numpy as np\n'), ((2058, 2077), 'numpy.power', 'np.power', (['(rc + r)', '(2)'], {}), '(rc + r, 2)\n', (2066, 2077), True, 'import numpy as np\n'), ((2082, 2102), 'numpy.power', 'np.power', (['(z - z_c)', '(2)'], {}), '(z - z_c, 2)\n', (2090, 2102), True, 'import numpy as np\n'), ((2200, 2220), 'numpy.power', 'np.power', (['(z - z_c)', '(2)'], {}), '(z - z_c, 2)\n', (2208, 2220), True, 'import numpy as np\n'), ((2485, 2505), 'numpy.power', 'np.power', (['(z - z_c)', '(2)'], {}), '(z - z_c, 2)\n', (2493, 2505), True, 'import numpy as np\n'), ((2165, 2180), 'numpy.power', 'np.power', (['rc', '(2)'], {}), '(rc, 2)\n', (2173, 2180), True, 'import numpy as np\n'), ((2183, 2197), 'numpy.power', 'np.power', (['r', '(2)'], {}), '(r, 2)\n', (2191, 2197), True, 'import numpy as np\n'), ((2450, 2465), 'numpy.power', 'np.power', (['rc', '(2)'], {}), '(rc, 2)\n', (2458, 2465), True, 'import numpy as np\n'), ((2468, 2482), 'numpy.power', 'np.power', (['r', '(2)'], {}), '(r, 2)\n', (2476, 2482), True, 'import numpy as np\n')]
import numpy as np import tempfile import logging import pandas as pd from sklearn.metrics import jaccard_score import rpGraph ###################################################################################################################### ############################################## UTILITIES ############################################################# ###################################################################################################################### ## Compute the Jaccard index similarity coefficient score between two MIRIAM dicts # 1.0 is a perfect match and 0.0 is a complete miss # We assume that the meas has the "complete" information and simulated has the incomplete info #TODO: interchange meas and sim since actually the measured has inclomple info and sim has more info def jaccardMIRIAM(meas_miriam, sim_miriam): values = list(set([ x for y in list(meas_miriam.values())+list(sim_miriam.values()) for x in y])) meas_data = {} sim_data = {} for key in set(list(meas_miriam.keys())+list(sim_miriam.keys())): tmp_meas_row = [] tmp_sim_row = [] for value in values: if key in meas_miriam: if value in meas_miriam[key]: tmp_meas_row.append(1) else: tmp_meas_row.append(0) else: tmp_meas_row.append(0) if key in sim_miriam: if value in sim_miriam[key]: tmp_sim_row.append(1) else: tmp_sim_row.append(0) else: tmp_sim_row.append(0) meas_data[key] = tmp_meas_row sim_data[key] = tmp_sim_row meas_dataf = pd.DataFrame(meas_data, index=values) sim_dataf = pd.DataFrame(sim_data, index=values) #return meas_dataf, sim_dataf, jaccard_score(meas_dataf, sim_dataf, average='weighted') return jaccard_score(meas_dataf, sim_dataf, average='weighted') ## Function to find the unique species # # pd_matrix is organised such that the rows are the simulated species and the columns are the measured ones # def findUniqueRowColumn(pd_matrix): logging.debug(pd_matrix) to_ret = {} ######################## filter by the global top values ################ logging.debug('################ Filter best #############') #transform to np.array x = pd_matrix.values #resolve the rouding issues to find the max x = np.around(x, decimals=5) #first round involves finding the highest values and if found set to 0.0 the rows and columns (if unique) top = np.where(x==np.max(x)) #as long as its unique keep looping if np.count_nonzero(x)==0: return to_ret while len(top[0])==1 and len(top[1])==1: if np.count_nonzero(x)==0: return to_ret pd_entry = pd_matrix.iloc[[top[0][0]],[top[1][0]]] row_name = str(pd_entry.index[0]) col_name = str(pd_entry.columns[0]) if col_name in to_ret: logging.debug('Overwriting (1): '+str(col_name)) logging.debug(x) to_ret[col_name] = [row_name] #delete the rows and the columns logging.debug('==================') logging.debug('Column: '+str(col_name)) logging.debug('Row: '+str(row_name)) pd_matrix.loc[:, col_name] = 0.0 pd_matrix.loc[row_name, :] = 0.0 x = pd_matrix.values x = np.around(x, decimals=5) top = np.where(x==np.max(x)) logging.debug(pd_matrix) logging.debug(top) logging.debug('==================') #################### filter by columns (measured) top values ############## logging.debug('################ Filter by column best ############') x = pd_matrix.values x = np.around(x, decimals=5) if np.count_nonzero(x)==0: return to_ret reloop = True while reloop: if np.count_nonzero(x)==0: return to_ret reloop = False for col in range(len(x[0])): if np.count_nonzero(x[:,col])==0: continue top_row = np.where(x[:,col]==np.max(x[:,col]))[0] if len(top_row)==1: top_row = top_row[0] #if top_row==0.0: # continue #check to see if any other measured pathways have the same or larger score (accross) row = list(x[top_row, :]) #remove current score consideration row.pop(col) if max(row)>=x[top_row, col]: logging.warning('For col '+str(col)+' there are either better or equal values: '+str(row)) logging.warning(x) continue #if you perform any changes on the rows and columns, then you can perform the loop again reloop = True pd_entry = pd_matrix.iloc[[top_row],[col]] logging.debug('==================') row_name = pd_entry.index[0] col_name = pd_entry.columns[0] logging.debug('Column: '+str(col_name)) logging.debug('Row: '+str(row_name)) if col_name in to_ret: logging.debug('Overwriting (2): '+str(col_name)) logging.debug(pd_matrix.values) to_ret[col_name] = [row_name] #delete the rows and the columns pd_matrix.loc[:, col_name] = 0.0 pd_matrix.loc[row_name, :] = 0.0 x = pd_matrix.values x = np.around(x, decimals=5) logging.debug(pd_matrix) logging.debug('==================') ################## laslty if there are multiple values that are not 0.0 then account for that ###### logging.debug('################# get the rest ##########') x = pd_matrix.values x = np.around(x, decimals=5) if np.count_nonzero(x)==0: return to_ret for col in range(len(x[0])): if not np.count_nonzero(x[:,col])==0: top_rows = np.where(x[:,col]==np.max(x[:,col]))[0] if len(top_rows)==1: top_row = top_rows[0] pd_entry = pd_matrix.iloc[[top_row],[col]] row_name = pd_entry.index[0] col_name = pd_entry.columns[0] if not col_name in to_ret: to_ret[col_name] = [row_name] else: logging.warning('At this point should never have only one: '+str(x[:,col])) logging.warning(x) else: for top_row in top_rows: pd_entry = pd_matrix.iloc[[top_row],[col]] row_name = pd_entry.index[0] col_name = pd_entry.columns[0] if not col_name in to_ret: to_ret[col_name] = [] to_ret[col_name].append(row_name) logging.debug(pd_matrix) logging.debug('###################') return to_ret ###################################################################################################################### ############################################### SPECIES ############################################################## ###################################################################################################################### ## Match all the measured chemical species to the simulated chemical species between two SBML # # TODO: for all the measured species compare with the simualted one. Then find the measured and simulated species that match the best and exclude the # simulated species from potentially matching with another # def compareSpecies(measured_rpsbml, sim_rpsbml, measured_comp_id=None, sim_comp_id=None): ############## compare species ################### meas_sim = {} sim_meas = {} species_match = {} for measured_species in measured_rpsbml.model.getListOfSpecies(): #skip the species that are not in the right compartmennt, if specified if measured_comp_id and not measured_species.getCompartment()==measured_comp_id: continue logging.debug('--- Trying to match chemical species: '+str(measured_species.getId())+' ---') meas_sim[measured_species.getId()] = {} species_match[measured_species.getId()] = {} #species_match[measured_species.getId()] = {'id': None, 'score': 0.0, 'found': False} #TODO: need to exclude from the match if a simulated chemical species is already matched with a higher score to another measured species for sim_species in sim_rpsbml.model.getListOfSpecies(): #skip the species that are not in the right compartmennt, if specified if sim_comp_id and not sim_species.getCompartment()==sim_comp_id: continue meas_sim[measured_species.getId()][sim_species.getId()] = {'score': 0.0, 'found': False} if not sim_species.getId() in sim_meas: sim_meas[sim_species.getId()] = {} sim_meas[sim_species.getId()][measured_species.getId()] = {'score': 0.0, 'found': False} measured_brsynth_annot = sim_rpsbml.readBRSYNTHAnnotation(measured_species.getAnnotation()) sim_rpsbml_brsynth_annot = sim_rpsbml.readBRSYNTHAnnotation(sim_species.getAnnotation()) measured_miriam_annot = sim_rpsbml.readMIRIAMAnnotation(measured_species.getAnnotation()) sim_miriam_annot = sim_rpsbml.readMIRIAMAnnotation(sim_species.getAnnotation()) #### MIRIAM #### if sim_rpsbml.compareMIRIAMAnnotations(measured_species.getAnnotation(), sim_species.getAnnotation()): logging.debug('--> Matched MIRIAM: '+str(sim_species.getId())) #meas_sim[measured_species.getId()][sim_species.getId()]['score'] += 0.4 meas_sim[measured_species.getId()][sim_species.getId()]['score'] += 0.2+0.2*jaccardMIRIAM(sim_miriam_annot, measured_miriam_annot) meas_sim[measured_species.getId()][sim_species.getId()]['found'] = True ##### InChIKey ########## #find according to the inchikey -- allow partial matches #compare either inchikey in brsynth annnotation or MIRIAM annotation #NOTE: here we prioritise the BRSynth annotation inchikey over the MIRIAM measured_inchikey_split = None sim_rpsbml_inchikey_split = None if 'inchikey' in measured_brsynth_annot: measured_inchikey_split = measured_brsynth_annot['inchikey'].split('-') elif 'inchikey' in measured_miriam_annot: if not len(measured_miriam_annot['inchikey'])==1: #TODO: handle mutliple inchikey with mutliple compare and the highest comparison value kept logging.warning('There are multiple inchikey values, taking the first one: '+str(measured_miriam_annot['inchikey'])) measured_inchikey_split = measured_miriam_annot['inchikey'][0].split('-') if 'inchikey' in sim_rpsbml_brsynth_annot: sim_rpsbml_inchikey_split = sim_rpsbml_brsynth_annot['inchikey'].split('-') elif 'inchikey' in sim_miriam_annot: if not len(sim_miriam_annot['inchikey'])==1: #TODO: handle mutliple inchikey with mutliple compare and the highest comparison value kept logging.warning('There are multiple inchikey values, taking the first one: '+str(sim_rpsbml_brsynth_annot['inchikey'])) sim_rpsbml_inchikey_split = sim_miriam_annot['inchikey'][0].split('-') if measured_inchikey_split and sim_rpsbml_inchikey_split: if measured_inchikey_split[0]==sim_rpsbml_inchikey_split[0]: logging.debug('Matched first layer InChIkey: ('+str(measured_inchikey_split)+' -- '+str(sim_rpsbml_inchikey_split)+')') meas_sim[measured_species.getId()][sim_species.getId()]['score'] += 0.2 if measured_inchikey_split[1]==sim_rpsbml_inchikey_split[1]: logging.debug('Matched second layer InChIkey: ('+str(measured_inchikey_split)+' -- '+str(sim_rpsbml_inchikey_split)+')') meas_sim[measured_species.getId()][sim_species.getId()]['score'] += 0.2 meas_sim[measured_species.getId()][sim_species.getId()]['found'] = True if measured_inchikey_split[2]==sim_rpsbml_inchikey_split[2]: logging.debug('Matched third layer InChIkey: ('+str(measured_inchikey_split)+' -- '+str(sim_rpsbml_inchikey_split)+')') meas_sim[measured_species.getId()][sim_species.getId()]['score'] += 0.2 meas_sim[measured_species.getId()][sim_species.getId()]['found'] = True sim_meas[sim_species.getId()][measured_species.getId()]['score'] = meas_sim[measured_species.getId()][sim_species.getId()]['score'] sim_meas[sim_species.getId()][measured_species.getId()]['found'] = meas_sim[measured_species.getId()][sim_species.getId()]['found'] #build the matrix to send meas_sim_mat = {} for i in meas_sim: meas_sim_mat[i] = {} for y in meas_sim[i]: meas_sim_mat[i][y] = meas_sim[i][y]['score'] unique = findUniqueRowColumn(pd.DataFrame(meas_sim_mat)) logging.debug('findUniqueRowColumn:') logging.debug(unique) for meas in meas_sim: if meas in unique: species_match[meas] = {} for unique_spe in unique[meas]: species_match[meas][unique_spe] = round(meas_sim[meas][unique[meas][0]]['score'], 5) else: logging.warning('Cannot find a species match for the measured species: '+str(meas)) logging.debug('#########################') logging.debug('species_match:') logging.debug(species_match) logging.debug('-----------------------') return species_match ###################################################################################################################### ############################################# REACTION ############################################################### ###################################################################################################################### ## # Compare that all the measured species of a reactions are found within sim species to match with a reaction. # We assume that there cannot be two reactions that have the same species and reactants. This is maintained by SBML # Compare also by EC number, from the third ec to the full EC # TODO: need to remove from the list reactions simulated reactions that have matched def compareReactions(measured_rpsbml, sim_rpsbml, species_match, pathway_id='rp_pathway'): ############## compare the reactions ####################### #construct sim reactions with species logging.debug('------ Comparing reactions --------') #match the reactants and products conversion to sim species tmp_reaction_match = {} meas_sim = {} sim_meas = {} for measured_reaction_id in measured_rpsbml.readRPpathwayIDs(pathway_id): logging.debug('Species match of measured reaction: '+str(measured_reaction_id)) measured_reaction = measured_rpsbml.model.getReaction(measured_reaction_id) measured_reaction_miriam = measured_rpsbml.readMIRIAMAnnotation(measured_reaction.getAnnotation()) ################ construct the dict transforming the species ####### meas_sim[measured_reaction_id] = {} tmp_reaction_match[measured_reaction_id] = {} for sim_reaction_id in sim_rpsbml.readRPpathwayIDs(pathway_id): if not sim_reaction_id in sim_meas: sim_meas[sim_reaction_id] = {} sim_meas[sim_reaction_id][measured_reaction_id] = {} meas_sim[measured_reaction_id][sim_reaction_id] = {} logging.debug('\t=========== '+str(sim_reaction_id)+' ==========') logging.debug('\t+++++++ Species match +++++++') tmp_reaction_match[measured_reaction_id][sim_reaction_id] = {'reactants': {}, 'reactants_score': 0.0, 'products': {}, 'products_score': 0.0, 'species_score': 0.0, 'species_std': 0.0, 'species_reaction': None, 'ec_score': 0.0, 'ec_reaction': None, 'score': 0.0, 'found': False} sim_reaction = sim_rpsbml.model.getReaction(sim_reaction_id) sim_reactants_id = [reactant.species for reactant in sim_reaction.getListOfReactants()] sim_products_id = [product.species for product in sim_reaction.getListOfProducts()] ############ species ############ logging.debug('\tspecies_match: '+str(species_match)) logging.debug('\tspecies_match: '+str(species_match.keys())) logging.debug('\tsim_reactants_id: '+str(sim_reactants_id)) logging.debug('\tmeasured_reactants_id: '+str([i.species for i in measured_reaction.getListOfReactants()])) logging.debug('\tsim_products_id: '+str(sim_products_id)) logging.debug('\tmeasured_products_id: '+str([i.species for i in measured_reaction.getListOfProducts()])) #ensure that the match is 1:1 #1)Here we assume that a reaction cannot have twice the same species cannotBeSpecies = [] #if there is a match then we loop again since removing it from the list of potential matches would be appropriate keep_going = True while keep_going: logging.debug('\t\t----------------------------') keep_going = False for reactant in measured_reaction.getListOfReactants(): logging.debug('\t\tReactant: '+str(reactant.species)) #if a species match has been found AND if such a match has been found founReaIDs = [tmp_reaction_match[measured_reaction_id][sim_reaction_id]['reactants'][i]['id'] for i in tmp_reaction_match[measured_reaction_id][sim_reaction_id]['reactants'] if not tmp_reaction_match[measured_reaction_id][sim_reaction_id]['reactants'][i]['id']==None] logging.debug('\t\tfounReaIDs: '+str(founReaIDs)) if reactant.species and reactant.species in species_match and not list(species_match[reactant.species].keys())==[] and not reactant.species in founReaIDs: #return all the similat entries ''' speMatch = list(set(species_match[reactant.species].keys())&set(sim_reactants_id)) speMatch = list(set(speMatch)-set(cannotBeSpecies)) logging.debug('\t\tspeMatch: '+str(speMatch)) if len(speMatch)==1: tmp_reaction_match[measured_reaction_id][sim_reaction_id]['reactants'][reactant.species] = {'id': speMatch[0], 'score': species_match[reactant.species]['score'], 'found': True} cannotBeSpecies.append(speMatch[0]) keep_going = True logging.debug('\t\tMatched measured reactant species: '+str(reactant.species)+' with simulated species: '+str(speMatch[0])) elif not reactant.species in tmp_reaction_match[measured_reaction_id][sim_reaction_id]['reactants']: tmp_reaction_match[measured_reaction_id][sim_reaction_id]['reactants'][reactant.species] = {'id': None, 'score': 0.0, 'found': False} #logging.debug('\t\tCould not find the folowing measured reactant in the currrent reaction: '+str(reactant.species)) ''' best_spe = [k for k, v in sorted(species_match[reactant.species].items(), key=lambda item: item[1], reverse=True)][0] tmp_reaction_match[measured_reaction_id][sim_reaction_id]['reactants'][reactant.species] = {'id': best_spe, 'score': species_match[reactant.species][best_spe], 'found': True} cannotBeSpecies.append(best_spe) elif not reactant.species in tmp_reaction_match[measured_reaction_id][sim_reaction_id]['reactants']: logging.warning('\t\tCould not find the following measured reactant in the matched species: '+str(reactant.species)) tmp_reaction_match[measured_reaction_id][sim_reaction_id]['reactants'][reactant.species] = {'id': None, 'score': 0.0, 'found': False} for product in measured_reaction.getListOfProducts(): logging.debug('\t\tProduct: '+str(product.species)) foundProIDs = [tmp_reaction_match[measured_reaction_id][sim_reaction_id]['products'][i]['id'] for i in tmp_reaction_match[measured_reaction_id][sim_reaction_id]['products'] if not tmp_reaction_match[measured_reaction_id][sim_reaction_id]['products'][i]['id']==None] logging.debug('\t\tfoundProIDs: '+str(foundProIDs)) if product.species and product.species in species_match and not list(species_match[product.species].keys())==[] and not product.species in foundProIDs: ''' #return all the similat entries speMatch = list(set(species_match[product.species]['id'])&set(sim_products_id)) speMatch = list(set(speMatch)-set(cannotBeSpecies)) logging.debug('\t\tspeMatch: '+str(speMatch)) if len(speMatch)==1: tmp_reaction_match[measured_reaction_id][sim_reaction_id]['products'][product.species] = {'id': speMatch[0], 'score': species_match[product.species]['score'], 'found': True} cannotBeSpecies.append(speMatch[0]) keep_going = True logging.debug('\t\tMatched measured product species: '+str(product.species)+' with simulated species: '+str(speMatch[0])) elif not product.species in tmp_reaction_match[measured_reaction_id][sim_reaction_id]['products']: tmp_reaction_match[measured_reaction_id][sim_reaction_id]['products'][product.species] = {'id': None, 'score': 0.0, 'found': False} #logging.debug('\t\tCould not find the following measured product in the matched species: '+str(product.species)) ''' best_spe = [k for k, v in sorted(species_match[product.species].items(), key=lambda item: item[1], reverse=True)][0] tmp_reaction_match[measured_reaction_id][sim_reaction_id]['reactants'][product.species] = {'id': best_spe, 'score': species_match[product.species][best_spe], 'found': True} cannotBeSpecies.append(best_spe) elif not product.species in tmp_reaction_match[measured_reaction_id][sim_reaction_id]['products']: logging.warning('\t\tCould not find the following measured product in the matched species: '+str(product.species)) tmp_reaction_match[measured_reaction_id][sim_reaction_id]['products'][product.species] = {'id': None, 'score': 0.0, 'found': False} logging.debug('\t\tcannotBeSpecies: '+str(cannotBeSpecies)) reactants_score = [tmp_reaction_match[measured_reaction_id][sim_reaction_id]['reactants'][i]['score'] for i in tmp_reaction_match[measured_reaction_id][sim_reaction_id]['reactants']] reactants_found = [tmp_reaction_match[measured_reaction_id][sim_reaction_id]['reactants'][i]['found'] for i in tmp_reaction_match[measured_reaction_id][sim_reaction_id]['reactants']] tmp_reaction_match[measured_reaction_id][sim_reaction_id]['reactants_score'] = np.mean(reactants_score) products_score = [tmp_reaction_match[measured_reaction_id][sim_reaction_id]['products'][i]['score'] for i in tmp_reaction_match[measured_reaction_id][sim_reaction_id]['products']] products_found = [tmp_reaction_match[measured_reaction_id][sim_reaction_id]['products'][i]['found'] for i in tmp_reaction_match[measured_reaction_id][sim_reaction_id]['products']] tmp_reaction_match[measured_reaction_id][sim_reaction_id]['products_score'] = np.mean(products_score) ### calculate pathway species score tmp_reaction_match[measured_reaction_id][sim_reaction_id]['species_score'] = np.mean(reactants_score+products_score) tmp_reaction_match[measured_reaction_id][sim_reaction_id]['species_std'] = np.std(reactants_score+products_score) tmp_reaction_match[measured_reaction_id][sim_reaction_id]['species_reaction'] = sim_reaction_id tmp_reaction_match[measured_reaction_id][sim_reaction_id]['found'] = all(reactants_found+products_found) #tmp_reaction_match[measured_reaction_id][sim_reaction_id]['found'] = True #break #only if we assume that one match is all that can happen TODO: calculate all matches and take the highest scoring one #continue #if you want the match to be more continuous ########## EC number ############ #Warning we only match a single reaction at a time -- assume that there cannot be more than one to match at a given time logging.debug('\t+++++ EC match +++++++') if 'ec-code' in measured_reaction_miriam: sim_reaction = sim_rpsbml.model.getReaction(sim_reaction_id) sim_reaction_miriam = sim_rpsbml.readMIRIAMAnnotation(sim_reaction.getAnnotation()) if 'ec-code' in sim_reaction_miriam: #we only need one match here measured_ec = [i for i in measured_reaction_miriam['ec-code']] sim_ec = [i for i in sim_reaction_miriam['ec-code']] #perfect match - one can have multiple ec score per reaction - keep the score for the highest matching one logging.debug('\t~~~~~~~~~~~~~~~~~~~~') logging.debug('\tMeasured EC: '+str(measured_ec)) logging.debug('\tSimulated EC: '+str(sim_ec)) measured_frac_ec = [[y for y in ec.split('.') if not y=='-'] for ec in measured_reaction_miriam['ec-code']] sim_frac_ec = [[y for y in ec.split('.') if not y=='-'] for ec in sim_reaction_miriam['ec-code']] #complete the ec numbers with None to be length of 4 for i in range(len(measured_frac_ec)): for y in range(len(measured_frac_ec[i]),4): measured_frac_ec[i].append(None) for i in range(len(sim_frac_ec)): for y in range(len(sim_frac_ec[i]),4): sim_frac_ec[i].append(None) logging.debug('\t'+str(measured_frac_ec)) logging.debug('\t'+str(sim_frac_ec)) best_ec_compare = {'meas_ec': [], 'sim_ec': [], 'score': 0.0, 'found': False} for ec_m in measured_frac_ec: for ec_s in sim_frac_ec: tmp_score = 0.0 for i in range(4): if not ec_m[i]==None and not ec_s[i]==None: if ec_m[i]==ec_s[i]: tmp_score += 0.25 if i==2: best_ec_compare['found'] = True else: break if tmp_score>best_ec_compare['score']: best_ec_compare['meas_ec'] = ec_m best_ec_compare['sim_ec'] = ec_s best_ec_compare['score'] = tmp_score logging.debug('\t'+str(best_ec_compare)) if best_ec_compare['found']: tmp_reaction_match[measured_reaction_id][sim_reaction_id]['found'] = True tmp_reaction_match[measured_reaction_id][sim_reaction_id]['ec_reaction'] = sim_reaction_id tmp_reaction_match[measured_reaction_id][sim_reaction_id]['ec_score'] = best_ec_compare['score'] logging.debug('\t~~~~~~~~~~~~~~~~~~~~') #WRNING: Here 80% for species match and 20% for ec match tmp_reaction_match[measured_reaction_id][sim_reaction_id]['score'] = np.average([tmp_reaction_match[measured_reaction_id][sim_reaction_id]['species_score'], tmp_reaction_match[measured_reaction_id][sim_reaction_id]['ec_score']], weights=[0.8, 0.2]) sim_meas[sim_reaction_id][measured_reaction_id] = tmp_reaction_match[measured_reaction_id][sim_reaction_id]['score'] meas_sim[measured_reaction_id][sim_reaction_id] = tmp_reaction_match[measured_reaction_id][sim_reaction_id]['score'] ### matrix compare ##### unique = findUniqueRowColumn(pd.DataFrame(meas_sim)) logging.debug('findUniqueRowColumn') logging.debug(unique) reaction_match = {} for meas in meas_sim: reaction_match[meas] = {'id': None, 'score': 0.0, 'found': False} if meas in unique: #if len(unique[meas])>1: # logging.debug('Multiple values may match, choosing the first arbitrarily') reaction_match[meas]['id'] = unique[meas] reaction_match[meas]['score'] = round(tmp_reaction_match[meas][unique[meas][0]]['score'], 5) reaction_match[meas]['found'] = tmp_reaction_match[meas][unique[meas][0]]['found'] #### compile a reaction score based on the ec and species scores logging.debug(tmp_reaction_match) logging.debug(reaction_match) logging.debug('-------------------------------') return reaction_match, tmp_reaction_match ## Compare individual reactions and see if the measured pathway is contained within the simulated one # # Note that we assure that the match is 1:1 between species using the species match # def compareReaction_graph(species_match, meas_reac, sim_reac): scores = [] all_match = True ########### reactants ####### ignore_reactants = [] for meas_reactant in meas_reac.getListOfReactants(): if meas_reactant.species in species_match: spe_found = False for sim_reactant in sim_reac.getListOfReactants(): if sim_reactant.species in species_match[meas_reactant.species] and not sim_reactant.species in ignore_reactants: scores.append(species_match[meas_reactant.species][sim_reactant.species]) ignore_reactants.append(sim_reactant.species) spe_found = True break if not spe_found: scores.append(0.0) all_match = False else: logging.debug('Cannot find the measured species '+str(meas_reactant.species)+' in the the matched species: '+str(species_match)) scores.append(0.0) all_match = False #products ignore_products = [] for meas_product in meas_reac.getListOfProducts(): if meas_product.species in species_match: pro_found = False for sim_product in sim_reac.getListOfProducts(): if sim_product.species in species_match[meas_product.species] and not sim_product.species in ignore_products: scores.append(species_match[meas_product.species][sim_product.species]) ignore_products.append(sim_product.species) pro_found = True break if not pro_found: scores.append(0.0) all_match = False else: logging.debug('Cannot find the measured species '+str(meas_product.species)+' in the the matched species: '+str(species_match)) scores.append(0.0) all_match = False return np.mean(scores), all_match ###################################################################################################################### ############################################### EC NUMBER ############################################################ ###################################################################################################################### def compareEC(meas_reac_miriam, sim_reac_miriam): #Warning we only match a single reaction at a time -- assume that there cannot be more than one to match at a given time if 'ec-code' in meas_reac_miriam and 'ec-code' in sim_reac_miriam: measured_frac_ec = [[y for y in ec.split('.') if not y=='-'] for ec in meas_reac_miriam['ec-code']] sim_frac_ec = [[y for y in ec.split('.') if not y=='-'] for ec in sim_reac_miriam['ec-code']] #complete the ec numbers with None to be length of 4 for i in range(len(measured_frac_ec)): for y in range(len(measured_frac_ec[i]), 4): measured_frac_ec[i].append(None) for i in range(len(sim_frac_ec)): for y in range(len(sim_frac_ec[i]), 4): sim_frac_ec[i].append(None) logging.debug('Measured: ') logging.debug(measured_frac_ec) logging.debug('Simulated: ') logging.debug(sim_frac_ec) best_ec_compare = {'meas_ec': [], 'sim_ec': [], 'score': 0.0, 'found': False} for ec_m in measured_frac_ec: for ec_s in sim_frac_ec: tmp_score = 0.0 for i in range(4): if not ec_m[i]==None and not ec_s[i]==None: if ec_m[i]==ec_s[i]: tmp_score += 0.25 if i==2: best_ec_compare['found'] = True else: break if tmp_score>best_ec_compare['score']: best_ec_compare['meas_ec'] = ec_m best_ec_compare['sim_ec'] = ec_s best_ec_compare['score'] = tmp_score return best_ec_compare['score'] else: logging.warning('One of the two reactions does not have any EC entries.\nMeasured: '+str(meas_reac_miriam)+' \nSimulated: '+str(sim_reac_miriam)) return 0.0 ###################################################################################################################### ################################################# PATHWAYS ########################################################### ###################################################################################################################### ## # # Note: remember that we are trying to find the measured species equivalent # def compareOrderedPathways(measured_rpsbml, sim_rpsbml, pathway_id='rp_pathway', species_group_id='central_species'): measured_rpgraph = rpGraph.rpGraph(measured_rpsbml, pathway_id, species_group_id) sim_rpgraph = rpGraph.rpGraph(sim_rpsbml, pathway_id, species_group_id) measured_ordered_reac = measured_rpgraph.orderedRetroReactions() sim_ordered_reac = sim_rpgraph.orderedRetroReactions() species_match = compareSpecies(measured_rpsbml, sim_rpsbml) scores = [] if len(measured_ordered_reac)>len(sim_ordered_reac): for i in range(len(sim_ordered_reac)): logging.debug('measured_ordered_reac['+str(i)+']: '+str(measured_ordered_reac)) logging.debug('sim_ordered_reac['+str(i)+']: '+str(sim_ordered_reac)) spe_score, is_full_match = compareReaction_graph(species_match, measured_rpsbml.model.getReaction(measured_ordered_reac[i]), sim_rpsbml.model.getReaction(sim_ordered_reac[i])) ec_score = compareEC(measured_rpsbml.readMIRIAMAnnotation(measured_rpsbml.model.getReaction(measured_ordered_reac[i]).getAnnotation()), sim_rpsbml.readMIRIAMAnnotation(sim_rpsbml.model.getReaction(sim_ordered_reac[i]).getAnnotation())) scores.append(np.average([spe_score, ec_score], weights=[0.8, 0.2])) return np.mean(scores)*( 1.0-np.abs(len(measured_ordered_reac)-len(sim_ordered_reac))/len(measured_ordered_reac) ), False elif len(measured_ordered_reac)<len(sim_ordered_reac): for i in range(len(measured_ordered_reac)): logging.debug('measured_ordered_reac['+str(i)+']: '+str(measured_ordered_reac)) logging.debug('sim_ordered_reac['+str(i)+']: '+str(sim_ordered_reac)) spe_score, is_full_match = compareReaction_graph(species_match, measured_rpsbml.model.getReaction(measured_ordered_reac[i]), sim_rpsbml.model.getReaction(sim_ordered_reac[i])) ec_score = compareEC(measured_rpsbml.readMIRIAMAnnotation(measured_rpsbml.model.getReaction(measured_ordered_reac[i]).getAnnotation()), sim_rpsbml.readMIRIAMAnnotation(sim_rpsbml.model.getReaction(sim_ordered_reac[i]).getAnnotation())) scores.append(np.average([spe_score, ec_score], weights=[0.8, 0.2])) return np.mean(scores)*( 1.0-np.abs(len(measured_ordered_reac)-len(sim_ordered_reac))/len(sim_ordered_reac) ), False #if the pathways are of the same length is the only time when the match may be perfect elif len(measured_ordered_reac)==len(sim_ordered_reac): perfect_match = True for i in range(len(sim_ordered_reac)): logging.debug('measured_ordered_reac['+str(i)+']: '+str(measured_ordered_reac)) logging.debug('sim_ordered_reac['+str(i)+']: '+str(sim_ordered_reac)) spe_score, is_full_match = compareReaction_graph(species_match, measured_rpsbml.model.getReaction(measured_ordered_reac[i]), sim_rpsbml.model.getReaction(sim_ordered_reac[i])) ec_score = compareEC(measured_rpsbml.readMIRIAMAnnotation(measured_rpsbml.model.getReaction(measured_ordered_reac[i]).getAnnotation()), sim_rpsbml.readMIRIAMAnnotation(sim_rpsbml.model.getReaction(sim_ordered_reac[i]).getAnnotation())) scores.append(np.average([spe_score, ec_score], weights=[0.8, 0.2])) if ec_score==0.0 and not is_full_match: prefect_match = False return np.mean(scores), perfect_match ## Compare a measured to sim rpSBML pathway # # Works by trying to find a measured pathway contained within a simulated one. Does not perform perfect match! Since # simulated ones contain full cofactors while the measured ones have impefect information def compareUnorderedpathways(measured_rpsbml, sim_rpsbml, pathway_id='rp_pathway'): logging.debug('##################### '+str(sim_rpsbml.model.getId())+' ######################') penalty_length = 1.0 #calculate the penatly score for the legnth of the pathways not being the same length meas_path_length = len(measured_rpsbml.readRPpathwayIDs(pathway_id)) sim_path_length = len(sim_rpsbml.readRPpathwayIDs(pathway_id)) #add a penatly to the length only if the simulated pathway is longer than the measured one #if its smaller then we will not be able to retreive all reactions and the scor will not be good in any case #if meas_path_length<sim_path_length: if meas_path_length>sim_path_length: penalty_length = 1.0-np.abs(meas_path_length-sim_path_length)/meas_path_length elif meas_path_length<=sim_path_length: penalty_length = 1.0-np.abs(meas_path_length-sim_path_length)/sim_path_length species_match = compareSpecies(measured_rpsbml, sim_rpsbml) reaction_match, all_rection_match_info = compareReactions(measured_rpsbml, sim_rpsbml, species_match, pathway_id) logging.debug(penalty_length) logging.debug([reaction_match[i]['score'] for i in reaction_match]) logging.debug([reaction_match[i]['found'] for i in reaction_match]) global_score = np.mean([reaction_match[i]['score'] for i in reaction_match]) global_found = [reaction_match[i]['found'] for i in reaction_match] return np.mean(global_score)*penalty_length, all(global_found)
[ "pandas.DataFrame", "logging.debug", "numpy.count_nonzero", "numpy.average", "numpy.abs", "numpy.std", "logging.warning", "sklearn.metrics.jaccard_score", "numpy.around", "numpy.mean", "numpy.max", "rpGraph.rpGraph" ]
[((1729, 1766), 'pandas.DataFrame', 'pd.DataFrame', (['meas_data'], {'index': 'values'}), '(meas_data, index=values)\n', (1741, 1766), True, 'import pandas as pd\n'), ((1783, 1819), 'pandas.DataFrame', 'pd.DataFrame', (['sim_data'], {'index': 'values'}), '(sim_data, index=values)\n', (1795, 1819), True, 'import pandas as pd\n'), ((1923, 1979), 'sklearn.metrics.jaccard_score', 'jaccard_score', (['meas_dataf', 'sim_dataf'], {'average': '"""weighted"""'}), "(meas_dataf, sim_dataf, average='weighted')\n", (1936, 1979), False, 'from sklearn.metrics import jaccard_score\n'), ((2173, 2197), 'logging.debug', 'logging.debug', (['pd_matrix'], {}), '(pd_matrix)\n', (2186, 2197), False, 'import logging\n'), ((2296, 2355), 'logging.debug', 'logging.debug', (['"""################ Filter best #############"""'], {}), "('################ Filter best #############')\n", (2309, 2355), False, 'import logging\n'), ((2464, 2488), 'numpy.around', 'np.around', (['x'], {'decimals': '(5)'}), '(x, decimals=5)\n', (2473, 2488), True, 'import numpy as np\n'), ((3688, 3756), 'logging.debug', 'logging.debug', (['"""################ Filter by column best ############"""'], {}), "('################ Filter by column best ############')\n", (3701, 3756), False, 'import logging\n'), ((3790, 3814), 'numpy.around', 'np.around', (['x'], {'decimals': '(5)'}), '(x, decimals=5)\n', (3799, 3814), True, 'import numpy as np\n'), ((5825, 5883), 'logging.debug', 'logging.debug', (['"""################# get the rest ##########"""'], {}), "('################# get the rest ##########')\n", (5838, 5883), False, 'import logging\n'), ((5917, 5941), 'numpy.around', 'np.around', (['x'], {'decimals': '(5)'}), '(x, decimals=5)\n', (5926, 5941), True, 'import numpy as np\n'), ((6982, 7006), 'logging.debug', 'logging.debug', (['pd_matrix'], {}), '(pd_matrix)\n', (6995, 7006), False, 'import logging\n'), ((7011, 7047), 'logging.debug', 'logging.debug', (['"""###################"""'], {}), "('###################')\n", (7024, 7047), False, 'import logging\n'), ((13474, 13511), 'logging.debug', 'logging.debug', (['"""findUniqueRowColumn:"""'], {}), "('findUniqueRowColumn:')\n", (13487, 13511), False, 'import logging\n'), ((13516, 13537), 'logging.debug', 'logging.debug', (['unique'], {}), '(unique)\n', (13529, 13537), False, 'import logging\n'), ((13887, 13929), 'logging.debug', 'logging.debug', (['"""#########################"""'], {}), "('#########################')\n", (13900, 13929), False, 'import logging\n'), ((13934, 13965), 'logging.debug', 'logging.debug', (['"""species_match:"""'], {}), "('species_match:')\n", (13947, 13965), False, 'import logging\n'), ((13970, 13998), 'logging.debug', 'logging.debug', (['species_match'], {}), '(species_match)\n', (13983, 13998), False, 'import logging\n'), ((14003, 14043), 'logging.debug', 'logging.debug', (['"""-----------------------"""'], {}), "('-----------------------')\n", (14016, 14043), False, 'import logging\n'), ((15007, 15059), 'logging.debug', 'logging.debug', (['"""------ Comparing reactions --------"""'], {}), "('------ Comparing reactions --------')\n", (15020, 15059), False, 'import logging\n'), ((30006, 30042), 'logging.debug', 'logging.debug', (['"""findUniqueRowColumn"""'], {}), "('findUniqueRowColumn')\n", (30019, 30042), False, 'import logging\n'), ((30047, 30068), 'logging.debug', 'logging.debug', (['unique'], {}), '(unique)\n', (30060, 30068), False, 'import logging\n'), ((30677, 30710), 'logging.debug', 'logging.debug', (['tmp_reaction_match'], {}), '(tmp_reaction_match)\n', (30690, 30710), False, 'import logging\n'), ((30715, 30744), 'logging.debug', 'logging.debug', (['reaction_match'], {}), '(reaction_match)\n', (30728, 30744), False, 'import logging\n'), ((30749, 30797), 'logging.debug', 'logging.debug', (['"""-------------------------------"""'], {}), "('-------------------------------')\n", (30762, 30797), False, 'import logging\n'), ((35971, 36033), 'rpGraph.rpGraph', 'rpGraph.rpGraph', (['measured_rpsbml', 'pathway_id', 'species_group_id'], {}), '(measured_rpsbml, pathway_id, species_group_id)\n', (35986, 36033), False, 'import rpGraph\n'), ((36052, 36109), 'rpGraph.rpGraph', 'rpGraph.rpGraph', (['sim_rpsbml', 'pathway_id', 'species_group_id'], {}), '(sim_rpsbml, pathway_id, species_group_id)\n', (36067, 36109), False, 'import rpGraph\n'), ((41143, 41172), 'logging.debug', 'logging.debug', (['penalty_length'], {}), '(penalty_length)\n', (41156, 41172), False, 'import logging\n'), ((41177, 41244), 'logging.debug', 'logging.debug', (["[reaction_match[i]['score'] for i in reaction_match]"], {}), "([reaction_match[i]['score'] for i in reaction_match])\n", (41190, 41244), False, 'import logging\n'), ((41249, 41316), 'logging.debug', 'logging.debug', (["[reaction_match[i]['found'] for i in reaction_match]"], {}), "([reaction_match[i]['found'] for i in reaction_match])\n", (41262, 41316), False, 'import logging\n'), ((41336, 41397), 'numpy.mean', 'np.mean', (["[reaction_match[i]['score'] for i in reaction_match]"], {}), "([reaction_match[i]['score'] for i in reaction_match])\n", (41343, 41397), True, 'import numpy as np\n'), ((2679, 2698), 'numpy.count_nonzero', 'np.count_nonzero', (['x'], {}), '(x)\n', (2695, 2698), True, 'import numpy as np\n'), ((3186, 3221), 'logging.debug', 'logging.debug', (['"""=================="""'], {}), "('==================')\n", (3199, 3221), False, 'import logging\n'), ((3438, 3462), 'numpy.around', 'np.around', (['x'], {'decimals': '(5)'}), '(x, decimals=5)\n', (3447, 3462), True, 'import numpy as np\n'), ((3508, 3532), 'logging.debug', 'logging.debug', (['pd_matrix'], {}), '(pd_matrix)\n', (3521, 3532), False, 'import logging\n'), ((3541, 3559), 'logging.debug', 'logging.debug', (['top'], {}), '(top)\n', (3554, 3559), False, 'import logging\n'), ((3568, 3603), 'logging.debug', 'logging.debug', (['"""=================="""'], {}), "('==================')\n", (3581, 3603), False, 'import logging\n'), ((3822, 3841), 'numpy.count_nonzero', 'np.count_nonzero', (['x'], {}), '(x)\n', (3838, 3841), True, 'import numpy as np\n'), ((5949, 5968), 'numpy.count_nonzero', 'np.count_nonzero', (['x'], {}), '(x)\n', (5965, 5968), True, 'import numpy as np\n'), ((13442, 13468), 'pandas.DataFrame', 'pd.DataFrame', (['meas_sim_mat'], {}), '(meas_sim_mat)\n', (13454, 13468), True, 'import pandas as pd\n'), ((29978, 30000), 'pandas.DataFrame', 'pd.DataFrame', (['meas_sim'], {}), '(meas_sim)\n', (29990, 30000), True, 'import pandas as pd\n'), ((32972, 32987), 'numpy.mean', 'np.mean', (['scores'], {}), '(scores)\n', (32979, 32987), True, 'import numpy as np\n'), ((34175, 34202), 'logging.debug', 'logging.debug', (['"""Measured: """'], {}), "('Measured: ')\n", (34188, 34202), False, 'import logging\n'), ((34211, 34242), 'logging.debug', 'logging.debug', (['measured_frac_ec'], {}), '(measured_frac_ec)\n', (34224, 34242), False, 'import logging\n'), ((34251, 34279), 'logging.debug', 'logging.debug', (['"""Simulated: """'], {}), "('Simulated: ')\n", (34264, 34279), False, 'import logging\n'), ((34288, 34314), 'logging.debug', 'logging.debug', (['sim_frac_ec'], {}), '(sim_frac_ec)\n', (34301, 34314), False, 'import logging\n'), ((2621, 2630), 'numpy.max', 'np.max', (['x'], {}), '(x)\n', (2627, 2630), True, 'import numpy as np\n'), ((2782, 2801), 'numpy.count_nonzero', 'np.count_nonzero', (['x'], {}), '(x)\n', (2798, 2801), True, 'import numpy as np\n'), ((3081, 3097), 'logging.debug', 'logging.debug', (['x'], {}), '(x)\n', (3094, 3097), False, 'import logging\n'), ((3915, 3934), 'numpy.count_nonzero', 'np.count_nonzero', (['x'], {}), '(x)\n', (3931, 3934), True, 'import numpy as np\n'), ((16108, 16156), 'logging.debug', 'logging.debug', (['"""\t+++++++ Species match +++++++"""'], {}), "('\\t+++++++ Species match +++++++')\n", (16121, 16156), False, 'import logging\n'), ((24686, 24710), 'numpy.mean', 'np.mean', (['reactants_score'], {}), '(reactants_score)\n', (24693, 24710), True, 'import numpy as np\n'), ((25185, 25208), 'numpy.mean', 'np.mean', (['products_score'], {}), '(products_score)\n', (25192, 25208), True, 'import numpy as np\n'), ((25346, 25387), 'numpy.mean', 'np.mean', (['(reactants_score + products_score)'], {}), '(reactants_score + products_score)\n', (25353, 25387), True, 'import numpy as np\n'), ((25473, 25513), 'numpy.std', 'np.std', (['(reactants_score + products_score)'], {}), '(reactants_score + products_score)\n', (25479, 25513), True, 'import numpy as np\n'), ((26219, 26260), 'logging.debug', 'logging.debug', (['"""\t+++++ EC match +++++++"""'], {}), "('\\t+++++ EC match +++++++')\n", (26232, 26260), False, 'import logging\n'), ((29478, 29667), 'numpy.average', 'np.average', (["[tmp_reaction_match[measured_reaction_id][sim_reaction_id]['species_score'],\n tmp_reaction_match[measured_reaction_id][sim_reaction_id]['ec_score']]"], {'weights': '[0.8, 0.2]'}), "([tmp_reaction_match[measured_reaction_id][sim_reaction_id][\n 'species_score'], tmp_reaction_match[measured_reaction_id][\n sim_reaction_id]['ec_score']], weights=[0.8, 0.2])\n", (29488, 29667), True, 'import numpy as np\n'), ((41481, 41502), 'numpy.mean', 'np.mean', (['global_score'], {}), '(global_score)\n', (41488, 41502), True, 'import numpy as np\n'), ((3489, 3498), 'numpy.max', 'np.max', (['x'], {}), '(x)\n', (3495, 3498), True, 'import numpy as np\n'), ((4040, 4067), 'numpy.count_nonzero', 'np.count_nonzero', (['x[:, col]'], {}), '(x[:, col])\n', (4056, 4067), True, 'import numpy as np\n'), ((4950, 4985), 'logging.debug', 'logging.debug', (['"""=================="""'], {}), "('==================')\n", (4963, 4985), False, 'import logging\n'), ((5598, 5622), 'numpy.around', 'np.around', (['x'], {'decimals': '(5)'}), '(x, decimals=5)\n', (5607, 5622), True, 'import numpy as np\n'), ((5639, 5663), 'logging.debug', 'logging.debug', (['pd_matrix'], {}), '(pd_matrix)\n', (5652, 5663), False, 'import logging\n'), ((5680, 5715), 'logging.debug', 'logging.debug', (['"""=================="""'], {}), "('==================')\n", (5693, 5715), False, 'import logging\n'), ((6043, 6070), 'numpy.count_nonzero', 'np.count_nonzero', (['x[:, col]'], {}), '(x[:, col])\n', (6059, 6070), True, 'import numpy as np\n'), ((18368, 18417), 'logging.debug', 'logging.debug', (['"""\t\t----------------------------"""'], {}), "('\\t\\t----------------------------')\n", (18381, 18417), False, 'import logging\n'), ((37215, 37268), 'numpy.average', 'np.average', (['[spe_score, ec_score]'], {'weights': '[0.8, 0.2]'}), '([spe_score, ec_score], weights=[0.8, 0.2])\n', (37225, 37268), True, 'import numpy as np\n'), ((37285, 37300), 'numpy.mean', 'np.mean', (['scores'], {}), '(scores)\n', (37292, 37300), True, 'import numpy as np\n'), ((40769, 40811), 'numpy.abs', 'np.abs', (['(meas_path_length - sim_path_length)'], {}), '(meas_path_length - sim_path_length)\n', (40775, 40811), True, 'import numpy as np\n'), ((4692, 4710), 'logging.warning', 'logging.warning', (['x'], {}), '(x)\n', (4707, 4710), False, 'import logging\n'), ((5315, 5346), 'logging.debug', 'logging.debug', (['pd_matrix.values'], {}), '(pd_matrix.values)\n', (5328, 5346), False, 'import logging\n'), ((6590, 6608), 'logging.warning', 'logging.warning', (['x'], {}), '(x)\n', (6605, 6608), False, 'import logging\n'), ((26897, 26936), 'logging.debug', 'logging.debug', (['"""\t~~~~~~~~~~~~~~~~~~~~"""'], {}), "('\\t~~~~~~~~~~~~~~~~~~~~')\n", (26910, 26936), False, 'import logging\n'), ((29288, 29327), 'logging.debug', 'logging.debug', (['"""\t~~~~~~~~~~~~~~~~~~~~"""'], {}), "('\\t~~~~~~~~~~~~~~~~~~~~')\n", (29301, 29327), False, 'import logging\n'), ((38304, 38357), 'numpy.average', 'np.average', (['[spe_score, ec_score]'], {'weights': '[0.8, 0.2]'}), '([spe_score, ec_score], weights=[0.8, 0.2])\n', (38314, 38357), True, 'import numpy as np\n'), ((38374, 38389), 'numpy.mean', 'np.mean', (['scores'], {}), '(scores)\n', (38381, 38389), True, 'import numpy as np\n'), ((39664, 39679), 'numpy.mean', 'np.mean', (['scores'], {}), '(scores)\n', (39671, 39679), True, 'import numpy as np\n'), ((40900, 40942), 'numpy.abs', 'np.abs', (['(meas_path_length - sim_path_length)'], {}), '(meas_path_length - sim_path_length)\n', (40906, 40942), True, 'import numpy as np\n'), ((4137, 4154), 'numpy.max', 'np.max', (['x[:, col]'], {}), '(x[:, col])\n', (4143, 4154), True, 'import numpy as np\n'), ((6116, 6133), 'numpy.max', 'np.max', (['x[:, col]'], {}), '(x[:, col])\n', (6122, 6133), True, 'import numpy as np\n'), ((39504, 39557), 'numpy.average', 'np.average', (['[spe_score, ec_score]'], {'weights': '[0.8, 0.2]'}), '([spe_score, ec_score], weights=[0.8, 0.2])\n', (39514, 39557), True, 'import numpy as np\n')]