code
stringlengths
31
1.05M
apis
list
extract_api
stringlengths
97
1.91M
import numpy as np class ADMM: def __init__(self, lamb, n_blocks, block_size, rho, S, rho_update_func=None): self.lamb = lamb self.n_blocks = n_blocks self.block_size = block_size self.rho = float(rho) self.S = S self.rho_update_func = rho_update_func self.status = None self.x = None self.z = None self.u = None @property def prob_size(self): return self.n_blocks * self.block_size @property def length(self): return int(self.prob_size * (self.prob_size + 1) / 2) @property def theta(self): return self.upper_to_full(self.x, eps=0) def initialize(self): self.x = np.zeros(self.length) self.z = np.zeros(self.length) self.u = np.zeros(self.length) self.status = 'Initialized' @staticmethod def ij_to_symmetric(i, j, size): return int((size * (size + 1)) / 2 - (size - i) * (size - i + 1) / 2 + j - i) @staticmethod def upper_to_full(a, eps=0): if eps is not None: mask = (a < eps) & (a > -eps) a[mask] = 0 n = int((-1 + np.sqrt(1 + 8 * a.shape[0])) / 2) A = np.zeros([n, n]) A[np.triu_indices(n)] = a temp = A.diagonal() A = np.asarray((A + A.T) - np.diag(temp)) return A @staticmethod def prox_logdet(S, A, eta): d, q = np.linalg.eigh(eta * A - S) q = np.matrix(q) X_var = (1 / (2 * float(eta))) * q * (np.diag(d + np.sqrt(np.square(d) + (4 * eta) * np.ones(d.shape)))) * q.T x_var = X_var[np.triu_indices(S.shape[1])] # extract upper triangular part as update variable return np.matrix(x_var).T def update_x(self): a = self.z - self.u A = self.upper_to_full(a, eps=None) eta = self.rho x_update = self.prox_logdet(self.S, A, eta) self.x = np.array(x_update).T.reshape(-1) def update_z(self, index_penalty=1): a = self.x + self.u prob_size = self.n_blocks * self.block_size z_update = np.zeros(self.length) # TODO: can we parallelize these? for i in range(self.n_blocks): elems = (2 * self.n_blocks - 2 * i) / 2 if i else self.n_blocks # i=0 is diagonal for j in range(self.block_size): for k in range(0 if i else j, self.block_size): loc_list = [((l + i) * self.block_size + j, l * self.block_size + k) for l in range(int(elems))] if i == 0: lam_sum = sum(self.lamb[loc1, loc2] for (loc1, loc2) in loc_list) indices = [self.ij_to_symmetric(loc1, loc2, prob_size) for (loc1, loc2) in loc_list] else: lam_sum = sum(self.lamb[loc2, loc1] for (loc1, loc2) in loc_list) indices = [self.ij_to_symmetric(loc2, loc1, prob_size) for (loc1, loc2) in loc_list] point_sum = a[indices].sum() rho_point_sum = self.rho * point_sum # Calculate soft threshold ans = 0 # If answer is positive if rho_point_sum > lam_sum: ans = max((rho_point_sum - lam_sum) / (self.rho * elems), 0) elif rho_point_sum < -1 * lam_sum: ans = min((rho_point_sum + lam_sum) / (self.rho * elems), 0) z_update[indices] = ans self.z = z_update def update_u(self): u_update = self.u + self.x - self.z self.u = u_update def check_convergence(self, z_old, e_abs, e_rel, verbose): # Returns True if convergence criteria have been satisfied # eps_abs = eps_rel = 0.01 # r = x - z # s = rho * (z - z_old) # e_pri = sqrt(length) * e_abs + e_rel * max(||x||, ||z||) # e_dual = sqrt(length) * e_abs + e_rel * ||rho * u|| # Should stop if (||r|| <= e_pri) and (||s|| <= e_dual) # Returns (boolean shouldStop, primal residual value, primal threshold, # dual residual value, dual threshold) norm = np.linalg.norm r = self.x - self.z s = self.rho * (self.z - z_old) # Primal and dual thresholds. Add .0001 to prevent the case of 0. e_pri = np.sqrt(self.length) * e_abs + e_rel * max(norm(self.x), norm(self.z)) + .0001 e_dual = np.sqrt(self.length) * e_abs + e_rel * norm(self.rho * self.u) + .0001 # Primal and dual residuals res_pri = norm(r) res_dual = norm(s) if verbose: # Debugging information to print(convergence criteria values) print('\tr:', res_pri) print('\te_pri:', e_pri) print('\ts:', res_dual) print('\te_dual:', e_dual) stop = (res_pri <= e_pri) and (res_dual <= e_dual) return stop, res_pri, e_pri, res_dual, e_dual def run(self, max_iters, eps_abs, eps_rel, verbose): self.initialize() for i in range(max_iters): z_old = np.copy(self.z) self.update_x() self.update_z() self.update_u() if i != 0: stop, res_pri, e_pri, res_dual, e_dual = self.check_convergence(z_old, eps_abs, eps_rel, verbose) if stop: self.status = 'Optimal' return self if self.rho_update_func: new_rho = self.rho_update_func(self.rho, res_pri, e_pri, res_dual, e_dual) else: new_rho = self.rho scale = self.rho / new_rho self.rho = new_rho self.u = scale * self.u if verbose: # Debugging information prints current iteration # print('Iteration %d' % i) self.status = 'Incomplete: max iterations reached' return self
[ "numpy.copy", "numpy.sqrt", "numpy.triu_indices", "numpy.ones", "numpy.diag", "numpy.square", "numpy.array", "numpy.zeros", "numpy.linalg.eigh", "numpy.matrix" ]
[((714, 735), 'numpy.zeros', 'np.zeros', (['self.length'], {}), '(self.length)\n', (722, 735), True, 'import numpy as np\n'), ((753, 774), 'numpy.zeros', 'np.zeros', (['self.length'], {}), '(self.length)\n', (761, 774), True, 'import numpy as np\n'), ((792, 813), 'numpy.zeros', 'np.zeros', (['self.length'], {}), '(self.length)\n', (800, 813), True, 'import numpy as np\n'), ((1206, 1222), 'numpy.zeros', 'np.zeros', (['[n, n]'], {}), '([n, n])\n', (1214, 1222), True, 'import numpy as np\n'), ((1418, 1445), 'numpy.linalg.eigh', 'np.linalg.eigh', (['(eta * A - S)'], {}), '(eta * A - S)\n', (1432, 1445), True, 'import numpy as np\n'), ((1458, 1470), 'numpy.matrix', 'np.matrix', (['q'], {}), '(q)\n', (1467, 1470), True, 'import numpy as np\n'), ((2090, 2111), 'numpy.zeros', 'np.zeros', (['self.length'], {}), '(self.length)\n', (2098, 2111), True, 'import numpy as np\n'), ((1233, 1251), 'numpy.triu_indices', 'np.triu_indices', (['n'], {}), '(n)\n', (1248, 1251), True, 'import numpy as np\n'), ((1612, 1639), 'numpy.triu_indices', 'np.triu_indices', (['S.shape[1]'], {}), '(S.shape[1])\n', (1627, 1639), True, 'import numpy as np\n'), ((1708, 1724), 'numpy.matrix', 'np.matrix', (['x_var'], {}), '(x_var)\n', (1717, 1724), True, 'import numpy as np\n'), ((5121, 5136), 'numpy.copy', 'np.copy', (['self.z'], {}), '(self.z)\n', (5128, 5136), True, 'import numpy as np\n'), ((1320, 1333), 'numpy.diag', 'np.diag', (['temp'], {}), '(temp)\n', (1327, 1333), True, 'import numpy as np\n'), ((1160, 1187), 'numpy.sqrt', 'np.sqrt', (['(1 + 8 * a.shape[0])'], {}), '(1 + 8 * a.shape[0])\n', (1167, 1187), True, 'import numpy as np\n'), ((1916, 1934), 'numpy.array', 'np.array', (['x_update'], {}), '(x_update)\n', (1924, 1934), True, 'import numpy as np\n'), ((4371, 4391), 'numpy.sqrt', 'np.sqrt', (['self.length'], {}), '(self.length)\n', (4378, 4391), True, 'import numpy as np\n'), ((4467, 4487), 'numpy.sqrt', 'np.sqrt', (['self.length'], {}), '(self.length)\n', (4474, 4487), True, 'import numpy as np\n'), ((1537, 1549), 'numpy.square', 'np.square', (['d'], {}), '(d)\n', (1546, 1549), True, 'import numpy as np\n'), ((1564, 1580), 'numpy.ones', 'np.ones', (['d.shape'], {}), '(d.shape)\n', (1571, 1580), True, 'import numpy as np\n')]
#!/usr/bin/env python """Topic Extraction using NLTK RakeKeywordExtractor CERN Webfest 2017 This file contains routines for - Summarization - Representative Messages """ import networkx as nx import numpy as np from nltk import sent_tokenize from sklearn.feature_extraction.text import TfidfTransformer, CountVectorizer from sklearn.metrics.pairwise import cosine_similarity from utils import load_sample def textrank(document, tokenize=True, num_msgs=5): if tokenize: sentences = sent_tokenize(document) else: sentences = document bow_matrix = CountVectorizer().fit_transform(sentences) normalized = TfidfTransformer().fit_transform(bow_matrix) # similarity_graph = normalized * normalized.T # nx_graph = nx.from_scipy_sparse_matrix(similarity_graph) similarity_graph = cosine_similarity(normalized) nx_graph = nx.from_numpy_matrix(similarity_graph) scores = nx.pagerank(nx_graph) sentence_array = sorted(((scores[i], s, i) for i, s in enumerate(sentences)), reverse=True) sentence_array = np.asarray(sentence_array) # print(sentence_array[:10]) fmax = float(sentence_array[0][0]) fmin = float(sentence_array[len(sentence_array) - 1][0]) temp_array = [] # Normalization for i in range(0, len(sentence_array)): if fmax - fmin == 0: temp_array.append(0) else: temp_array.append((float(sentence_array[i][0]) - fmin) / (fmax - fmin)) threshold = (sum(temp_array) / len(temp_array)) + 0.2 # print(temp_array[:10]) sentence_list = [] for i in range(0, len(temp_array)): if temp_array[i] > threshold: sentence_list.append(sentence_array[i][1]) # print(sentence_list[:10]) sentence_list = sentence_list[:num_msgs] seq_list = [] positions = [] for sentence, position in zip(sentences, range(len(sentences))): if sentence in sentence_list: seq_list.append(sentence) positions.append(position) return seq_list, positions def representative_msgs_textrank(messages, num_msgs=5): contents = [d['content'] for d in messages] sentences, positions = textrank(contents, tokenize=False, num_msgs=num_msgs) return [messages[i] for i in positions] if __name__ == '__main__': messages = load_sample() for m in representative_msgs_textrank(load_sample()): print(m) pass
[ "sklearn.feature_extraction.text.TfidfTransformer", "sklearn.metrics.pairwise.cosine_similarity", "sklearn.feature_extraction.text.CountVectorizer", "numpy.asarray", "nltk.sent_tokenize", "utils.load_sample", "networkx.from_numpy_matrix", "networkx.pagerank" ]
[((836, 865), 'sklearn.metrics.pairwise.cosine_similarity', 'cosine_similarity', (['normalized'], {}), '(normalized)\n', (853, 865), False, 'from sklearn.metrics.pairwise import cosine_similarity\n'), ((881, 919), 'networkx.from_numpy_matrix', 'nx.from_numpy_matrix', (['similarity_graph'], {}), '(similarity_graph)\n', (901, 919), True, 'import networkx as nx\n'), ((934, 955), 'networkx.pagerank', 'nx.pagerank', (['nx_graph'], {}), '(nx_graph)\n', (945, 955), True, 'import networkx as nx\n'), ((1074, 1100), 'numpy.asarray', 'np.asarray', (['sentence_array'], {}), '(sentence_array)\n', (1084, 1100), True, 'import numpy as np\n'), ((2336, 2349), 'utils.load_sample', 'load_sample', ([], {}), '()\n', (2347, 2349), False, 'from utils import load_sample\n'), ((511, 534), 'nltk.sent_tokenize', 'sent_tokenize', (['document'], {}), '(document)\n', (524, 534), False, 'from nltk import sent_tokenize\n'), ((2392, 2405), 'utils.load_sample', 'load_sample', ([], {}), '()\n', (2403, 2405), False, 'from utils import load_sample\n'), ((592, 609), 'sklearn.feature_extraction.text.CountVectorizer', 'CountVectorizer', ([], {}), '()\n', (607, 609), False, 'from sklearn.feature_extraction.text import TfidfTransformer, CountVectorizer\n'), ((652, 670), 'sklearn.feature_extraction.text.TfidfTransformer', 'TfidfTransformer', ([], {}), '()\n', (668, 670), False, 'from sklearn.feature_extraction.text import TfidfTransformer, CountVectorizer\n')]
import os import sys import numpy as np import multiprocessing # Import flags specifying dataset parameters from flags import getFlags def preprocess_data(start_index, data_count, data_dir, mesh_dir, soln_dir, RESCALE=True): RESCALE = False LORES = True HIRES = False for i in range(start_index, start_index + data_count): if LORES: mesh = np.load(mesh_dir + 'mesh_' + str(0) + '.npy') out_of_domain = (mesh == 0) data = np.load(data_dir + 'data_' + str(i) + '.npy') data[out_of_domain] = 0.0 #soln = np.load(soln_dir + 'solution_' + str(i) + '.npy') if RESCALE: ## Rescale data and solutions scaling = np.max(np.abs(data)) data = data/scaling #soln = soln/scaling np.save(data_dir + 'data_' + str(i) + '.npy', data) #np.save(soln_dir + 'solution_' + str(i) + '.npy', soln) if HIRES: hires_mesh = np.load(mesh_dir + 'hires_mesh_' + str(0) + '.npy') hires_out_of_domain = (hires_mesh == 0) hires_data = np.load(data_dir + 'hires_data_' + str(i) + '.npy') hires_data[hires_out_of_domain] = 0.0 #hires_soln = np.load(soln_dir + 'hires_solution_' + str(i) + '.npy') if RESCALE: ## Rescale data and solutions hires_scaling = np.max(np.abs(hires_data)) hires_data = hires_data/hires_scaling #hires_soln = hires_soln/hires_scaling np.save(data_dir + 'hires_data_' + str(i) + '.npy', hires_data) #np.save(soln_dir + 'hires_solution_' + str(i) + '.npy', hires_soln) if __name__ == '__main__': FLAGS = getFlags() # Divide tasks into smaller pieces subdivision = 5 #hires_mesh = np.load(FLAGS.mesh_dir + 'hires_mesh_' + str(0) + '.npy') def preprocess(d): preprocess_data(d, int(FLAGS.data_count/subdivision), FLAGS.data_dir, FLAGS.mesh_dir, FLAGS.soln_dir) # Create multiprocessing pool NumProcesses = FLAGS.cpu_count pool = multiprocessing.Pool(processes=NumProcesses) start_indices = [int(n*FLAGS.data_count/subdivision) for n in range(0,subdivision*FLAGS.cov_count)] start_indices = [FLAGS.data_start_count + n for n in start_indices] print('\n [ Preprocessing Data ]\n') num_tasks = subdivision*FLAGS.cov_count for i, _ in enumerate(pool.imap_unordered(preprocess, [d for d in start_indices]), 1): sys.stdout.write('\r Progress: {0:.1%}'.format(i/num_tasks)) sys.stdout.flush() print('\n')
[ "flags.getFlags", "numpy.abs", "sys.stdout.flush", "multiprocessing.Pool" ]
[((1759, 1769), 'flags.getFlags', 'getFlags', ([], {}), '()\n', (1767, 1769), False, 'from flags import getFlags\n'), ((2122, 2166), 'multiprocessing.Pool', 'multiprocessing.Pool', ([], {'processes': 'NumProcesses'}), '(processes=NumProcesses)\n', (2142, 2166), False, 'import multiprocessing\n'), ((2604, 2622), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (2620, 2622), False, 'import sys\n'), ((743, 755), 'numpy.abs', 'np.abs', (['data'], {}), '(data)\n', (749, 755), True, 'import numpy as np\n'), ((1431, 1449), 'numpy.abs', 'np.abs', (['hires_data'], {}), '(hires_data)\n', (1437, 1449), True, 'import numpy as np\n')]
# Copyright 2019 The Cirq Developers # # 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. from collections import defaultdict from typing import (Mapping, Optional, Tuple, Union, List, FrozenSet, DefaultDict, TYPE_CHECKING) import numbers import numpy as np from cirq import protocols, qis, value from cirq._doc import document from cirq.linalg import operator_spaces from cirq.ops import identity, raw_types, pauli_gates, pauli_string from cirq.ops.pauli_string import PauliString, _validate_qubit_mapping from cirq.value.linear_dict import _format_terms if TYPE_CHECKING: import cirq UnitPauliStringT = FrozenSet[Tuple[raw_types.Qid, pauli_gates.Pauli]] PauliSumLike = Union[int, float, complex, PauliString, 'PauliSum', pauli_string. SingleQubitPauliStringGateOperation] document( PauliSumLike, # type: ignore """Any value that can be easily translated into a sum of Pauli products. """) class LinearCombinationOfGates(value.LinearDict[raw_types.Gate]): """Represents linear operator defined by a linear combination of gates. Suppose G1, G2, ..., Gn are gates and b1, b2, ..., bn are complex numbers. Then LinearCombinationOfGates({G1: b1, G2: b2, ..., Gn: bn}) represents the linear operator A = b1 G1 + b2 G2 + ... + bn Gn Note that A may not be unitary or even normal. Rather than creating LinearCombinationOfGates instance explicitly, one may use overloaded arithmetic operators. For example, cirq.LinearCombinationOfGates({cirq.X: 2, cirq.Z: -2}) is equivalent to 2 * cirq.X - 2 * cirq.Z """ def __init__(self, terms: Mapping[raw_types.Gate, value.Scalar]) -> None: """Initializes linear combination from a collection of terms. Args: terms: Mapping of gates to coefficients in the linear combination being initialized. """ super().__init__(terms, validator=self._is_compatible) def num_qubits(self) -> Optional[int]: """Returns number of qubits in the domain if known, None if unknown.""" if not self: return None any_gate = next(iter(self)) return any_gate.num_qubits() def _is_compatible(self, gate: 'cirq.Gate') -> bool: return (self.num_qubits() is None or self.num_qubits() == gate.num_qubits()) def __add__(self, other: Union[raw_types.Gate, 'LinearCombinationOfGates'] ) -> 'LinearCombinationOfGates': if not isinstance(other, LinearCombinationOfGates): other = other.wrap_in_linear_combination() return super().__add__(other) def __iadd__(self, other: Union[raw_types.Gate, 'LinearCombinationOfGates'] ) -> 'LinearCombinationOfGates': if not isinstance(other, LinearCombinationOfGates): other = other.wrap_in_linear_combination() return super().__iadd__(other) def __sub__(self, other: Union[raw_types.Gate, 'LinearCombinationOfGates'] ) -> 'LinearCombinationOfGates': if not isinstance(other, LinearCombinationOfGates): other = other.wrap_in_linear_combination() return super().__sub__(other) def __isub__(self, other: Union[raw_types.Gate, 'LinearCombinationOfGates'] ) -> 'LinearCombinationOfGates': if not isinstance(other, LinearCombinationOfGates): other = other.wrap_in_linear_combination() return super().__isub__(other) def __pow__(self, exponent: int) -> 'LinearCombinationOfGates': if not isinstance(exponent, int): return NotImplemented if exponent < 0: return NotImplemented if self.num_qubits() != 1: return NotImplemented pauli_basis = { identity.I, pauli_gates.X, pauli_gates.Y, pauli_gates.Z, } if not set(self.keys()).issubset(pauli_basis): return NotImplemented ai = self[identity.I] ax = self[pauli_gates.X] ay = self[pauli_gates.Y] az = self[pauli_gates.Z] bi, bx, by, bz = operator_spaces.pow_pauli_combination( ai, ax, ay, az, exponent) return LinearCombinationOfGates({ identity.I: bi, pauli_gates.X: bx, pauli_gates.Y: by, pauli_gates.Z: bz }) def matrix(self) -> np.ndarray: """Reconstructs matrix of self using unitaries of underlying gates. Raises: TypeError: if any of the gates in self does not provide a unitary. """ num_qubits = self.num_qubits() if num_qubits is None: raise ValueError('Unknown number of qubits') num_dim = 2 ** num_qubits result = np.zeros((num_dim, num_dim), dtype=np.complex128) for gate, coefficient in self.items(): result += protocols.unitary(gate) * coefficient return result def _pauli_expansion_(self) -> value.LinearDict[str]: result = value.LinearDict({}) # type: value.LinearDict[str] for gate, coefficient in self.items(): result += protocols.pauli_expansion(gate) * coefficient return result class LinearCombinationOfOperations(value.LinearDict[raw_types.Operation]): """Represents operator defined by linear combination of gate operations. If G1, ..., Gn are gate operations, {q1_1, ..., q1_k1}, {q2_1, ..., q2_k2}, ..., {qn_1, ..., qn_kn} are (not necessarily disjoint) sets of qubits and b1, b2, ..., bn are complex numbers, then LinearCombinationOfOperations({ G1(q1_1, ..., q1_k1): b1, G2(q2_1, ..., q2_k2): b2, ..., Gn(qn_1, ..., qn_kn): bn}) represents the linear operator A = b1 G1(q1_1, ..., q1_k1) + + b2 G2(q2_1, ..., q2_k2) + + ... + + bn Gn(qn_1, ..., qn_kn) where in each term qubits not explicitly listed are assumed to be acted on by the identity operator. Note that A may not be unitary or even normal. """ def __init__(self, terms: Mapping[raw_types.Operation, value.Scalar]) -> None: """Initializes linear combination from a collection of terms. Args: terms: Mapping of gate operations to coefficients in the linear combination being initialized. """ super().__init__(terms, validator=self._is_compatible) def _is_compatible(self, operation: 'cirq.Operation') -> bool: return isinstance(operation, raw_types.Operation) @property def qubits(self) -> Tuple[raw_types.Qid, ...]: """Returns qubits acted on self.""" if not self: return () qubit_sets = [set(op.qubits) for op in self.keys()] all_qubits = set.union(*qubit_sets) return tuple(sorted(all_qubits)) def __pow__(self, exponent: int) -> 'LinearCombinationOfOperations': if not isinstance(exponent, int): return NotImplemented if exponent < 0: return NotImplemented if len(self.qubits) != 1: return NotImplemented qubit = self.qubits[0] i = identity.I(qubit) x = pauli_gates.X(qubit) y = pauli_gates.Y(qubit) z = pauli_gates.Z(qubit) pauli_basis = {i, x, y, z} if not set(self.keys()).issubset(pauli_basis): return NotImplemented ai, ax, ay, az = self[i], self[x], self[y], self[z] bi, bx, by, bz = operator_spaces.pow_pauli_combination( ai, ax, ay, az, exponent) return LinearCombinationOfOperations({i: bi, x: bx, y: by, z: bz}) def matrix(self) -> np.ndarray: """Reconstructs matrix of self using unitaries of underlying operations. Raises: TypeError: if any of the gates in self does not provide a unitary. """ num_qubits = len(self.qubits) num_dim = 2**num_qubits qubit_to_axis = {q: i for i, q in enumerate(self.qubits)} result = np.zeros((2,) * (2 * num_qubits), dtype=np.complex128) for op, coefficient in self.items(): identity = np.eye(num_dim, dtype=np.complex128).reshape(result.shape) workspace = np.empty_like(identity) axes = tuple(qubit_to_axis[q] for q in op.qubits) u = protocols.apply_unitary( op, protocols.ApplyUnitaryArgs(identity, workspace, axes)) result += coefficient * u return result.reshape((num_dim, num_dim)) def _pauli_expansion_(self) -> value.LinearDict[str]: """Computes Pauli expansion of self from Pauli expansions of terms.""" def extend_term(pauli_names: str, qubits: Tuple['cirq.Qid', ...], all_qubits: Tuple['cirq.Qid', ...]) -> str: """Extends Pauli product on qubits to product on all_qubits.""" assert len(pauli_names) == len(qubits) qubit_to_pauli_name = dict(zip(qubits, pauli_names)) return ''.join(qubit_to_pauli_name.get(q, 'I') for q in all_qubits) def extend(expansion: value.LinearDict[str], qubits: Tuple['cirq.Qid', ...], all_qubits: Tuple['cirq.Qid', ...]) -> value.LinearDict[str]: """Extends Pauli expansion on qubits to expansion on all_qubits.""" return value.LinearDict({ extend_term(p, qubits, all_qubits): c for p, c in expansion.items() }) result = value.LinearDict({}) # type: value.LinearDict[str] for op, coefficient in self.items(): expansion = protocols.pauli_expansion(op) extended_expansion = extend(expansion, op.qubits, self.qubits) result += extended_expansion * coefficient return result def _is_linear_dict_of_unit_pauli_string( linear_dict: value.LinearDict[UnitPauliStringT]) -> bool: if not isinstance(linear_dict, value.LinearDict): return False for k in linear_dict.keys(): if not isinstance(k, frozenset): return False for qid, pauli in k: if not isinstance(qid, raw_types.Qid): return False if not isinstance(pauli, pauli_gates.Pauli): return False return True def _pauli_string_from_unit(unit: UnitPauliStringT, coefficient: Union[int, float, complex] = 1): return PauliString(qubit_pauli_map=dict(unit), coefficient=coefficient) @value.value_equality(approximate=True) class PauliSum: """Represents operator defined by linear combination of PauliStrings. Since PauliStrings store their own coefficients, this class does not implement the LinearDict interface. Instead, you can add and subtract terms and then iterate over the resulting (simplified) expression. Under the hood, this class is backed by a LinearDict with coefficient-less PauliStrings as keys. PauliStrings are reconstructed on-the-fly during iteration. """ def __init__( self, linear_dict: Optional[value.LinearDict[UnitPauliStringT]] = None): if linear_dict is None: linear_dict = value.LinearDict() if not _is_linear_dict_of_unit_pauli_string(linear_dict): raise ValueError( "PauliSum constructor takes a LinearDict[UnitPauliStringT]. " "Consider using PauliSum.from_pauli_strings() or adding and " "subtracting PauliStrings") self._linear_dict = linear_dict def _value_equality_values_(self): return self._linear_dict @staticmethod def wrap(val: PauliSumLike) -> 'PauliSum': if isinstance(val, PauliSum): return val return PauliSum() + val @classmethod def from_pauli_strings(cls, terms: Union[PauliString, List[PauliString]] ) -> 'PauliSum': if isinstance(terms, PauliString): terms = [terms] termdict: DefaultDict[UnitPauliStringT, value.Scalar] = defaultdict( lambda: 0) for pstring in terms: key = frozenset(pstring._qubit_pauli_map.items()) termdict[key] += pstring.coefficient return cls(linear_dict=value.LinearDict(termdict)) @property def qubits(self) -> Tuple[raw_types.Qid, ...]: qs = {q for k in self._linear_dict.keys() for q, _ in k} return tuple(sorted(qs)) def copy(self) -> 'PauliSum': factory = type(self) return factory(self._linear_dict.copy()) def expectation_from_wavefunction(self, state: np.ndarray, qubit_map: Mapping[raw_types.Qid, int], *, atol: float = 1e-7, check_preconditions: bool = True ) -> float: """Evaluate the expectation of this PauliSum given a wavefunction. See `PauliString.expectation_from_wavefunction`. Args: state: An array representing a valid wavefunction. qubit_map: A map from all qubits used in this PauliSum to the indices of the qubits that `state` is defined over. atol: Absolute numerical tolerance. check_preconditions: Whether to check that `state` represents a valid wavefunction. Returns: The expectation value of the input state. """ if any(abs(p.coefficient.imag) > 0.0001 for p in self): raise NotImplementedError( "Cannot compute expectation value of a non-Hermitian " "PauliString <{}>. Coefficient must be real.".format(self)) # FIXME: Avoid enforce specific complex type. This is necessary to # prevent an `apply_unitary` bug (Issue #2041). if state.dtype.kind != 'c': raise TypeError("Input state dtype must be np.complex64 or " "np.complex128") size = state.size num_qubits = size.bit_length() - 1 _validate_qubit_mapping(qubit_map, self.qubits, num_qubits) if len(state.shape) != 1 and state.shape != (2,) * num_qubits: raise ValueError("Input array does not represent a wavefunction " "with shape `(2 ** n,)` or `(2, ..., 2)`.") if check_preconditions: qis.validate_normalized_state(state=state, qid_shape=(2,) * num_qubits, dtype=state.dtype, atol=atol) return sum( p._expectation_from_wavefunction_no_validation(state, qubit_map) for p in self) def expectation_from_density_matrix(self, state: np.ndarray, qubit_map: Mapping[raw_types.Qid, int], *, atol: float = 1e-7, check_preconditions: bool = True ) -> float: """Evaluate the expectation of this PauliSum given a density matrix. See `PauliString.expectation_from_density_matrix`. Args: state: An array representing a valid density matrix. qubit_map: A map from all qubits used in this PauliSum to the indices of the qubits that `state` is defined over. atol: Absolute numerical tolerance. check_preconditions: Whether to check that `state` represents a valid density matrix. Returns: The expectation value of the input state. """ if any(abs(p.coefficient.imag) > 0.0001 for p in self): raise NotImplementedError( "Cannot compute expectation value of a non-Hermitian " "PauliString <{}>. Coefficient must be real.".format(self)) # FIXME: Avoid enforce specific complex type. This is necessary to # prevent an `apply_unitary` bug (Issue #2041). if state.dtype.kind != 'c': raise TypeError("Input state dtype must be np.complex64 or " "np.complex128") size = state.size num_qubits = int(np.sqrt(size)).bit_length() - 1 _validate_qubit_mapping(qubit_map, self.qubits, num_qubits) dim = int(np.sqrt(size)) if state.shape != (dim, dim) and state.shape != (2, 2) * num_qubits: raise ValueError("Input array does not represent a density matrix " "with shape `(2 ** n, 2 ** n)` or `(2, ..., 2)`.") if check_preconditions: # Do not enforce reshaping if the state all axes are dimension 2. _ = qis.to_valid_density_matrix(density_matrix_rep=state.reshape( dim, dim), num_qubits=num_qubits, dtype=state.dtype, atol=atol) return sum( p._expectation_from_density_matrix_no_validation(state, qubit_map) for p in self) def __iter__(self): for vec, coeff in self._linear_dict.items(): yield _pauli_string_from_unit(vec, coeff) def __len__(self) -> int: return len(self._linear_dict) def __iadd__(self, other): if isinstance(other, numbers.Complex): other = PauliSum.from_pauli_strings( [PauliString(coefficient=other)]) elif isinstance(other, PauliString): other = PauliSum.from_pauli_strings([other]) if not isinstance(other, PauliSum): return NotImplemented self._linear_dict += other._linear_dict return self def __add__(self, other): if not isinstance(other, (numbers.Complex, PauliString, PauliSum)): return NotImplemented result = self.copy() result += other return result def __radd__(self, other): return self.__add__(other) def __rsub__(self, other): return -self.__sub__(other) def __isub__(self, other): if isinstance(other, numbers.Complex): other = PauliSum.from_pauli_strings( [PauliString(coefficient=other)]) if isinstance(other, PauliString): other = PauliSum.from_pauli_strings([other]) if not isinstance(other, PauliSum): return NotImplemented self._linear_dict -= other._linear_dict return self def __sub__(self, other): if not isinstance(other, (numbers.Complex, PauliString, PauliSum)): return NotImplemented result = self.copy() result -= other return result def __neg__(self): factory = type(self) return factory(-self._linear_dict) def __imul__(self, other: PauliSumLike): if not isinstance(other, (numbers.Complex, PauliString, PauliSum)): return NotImplemented if isinstance(other, numbers.Complex): self._linear_dict *= other elif isinstance(other, PauliString): temp = PauliSum.from_pauli_strings([term * other for term in self]) self._linear_dict = temp._linear_dict elif isinstance(other, PauliSum): temp = PauliSum.from_pauli_strings( [term * other_term for term in self for other_term in other]) self._linear_dict = temp._linear_dict return self def __mul__(self, other: PauliSumLike): if not isinstance(other, (numbers.Complex, PauliString, PauliSum)): return NotImplemented result = self.copy() result *= other return result def __rmul__(self, other: PauliSumLike): if isinstance(other, numbers.Complex): result = self.copy() result *= other return result elif isinstance(other, PauliString): result = self.copy() return PauliSum.from_pauli_strings([other]) * result return NotImplemented def __pow__(self, exponent: int): if not isinstance(exponent, numbers.Integral): return NotImplemented if exponent == 0: return PauliSum(value.LinearDict({frozenset(): 1 + 0j})) if exponent > 0: base = self.copy() for _ in range(exponent - 1): base *= base return base return NotImplemented def __truediv__(self, a: value.Scalar): return self.__mul__(1 / a) def __bool__(self) -> bool: return bool(self._linear_dict) def __repr__(self) -> str: class_name = self.__class__.__name__ return f'cirq.{class_name}({self._linear_dict!r})' def __format__(self, format_spec: str) -> str: terms = [(_pauli_string_from_unit(v), self._linear_dict[v]) for v in self._linear_dict.keys()] return _format_terms(terms=terms, format_spec=format_spec) def __str__(self) -> str: return self.__format__('.3f')
[ "cirq.ops.pauli_gates.Y", "numpy.sqrt", "cirq.protocols.pauli_expansion", "cirq.value.linear_dict._format_terms", "cirq.ops.pauli_gates.Z", "cirq.ops.identity.I", "cirq.value.LinearDict", "cirq.linalg.operator_spaces.pow_pauli_combination", "cirq._doc.document", "cirq.ops.pauli_gates.X", "cirq.p...
[((1317, 1430), 'cirq._doc.document', 'document', (['PauliSumLike', '"""Any value that can be easily translated into a sum of Pauli products.\n """'], {}), '(PauliSumLike,\n """Any value that can be easily translated into a sum of Pauli products.\n """\n )\n', (1325, 1430), False, 'from cirq._doc import document\n'), ((11209, 11247), 'cirq.value.value_equality', 'value.value_equality', ([], {'approximate': '(True)'}), '(approximate=True)\n', (11229, 11247), False, 'from cirq import protocols, qis, value\n'), ((4743, 4806), 'cirq.linalg.operator_spaces.pow_pauli_combination', 'operator_spaces.pow_pauli_combination', (['ai', 'ax', 'ay', 'az', 'exponent'], {}), '(ai, ax, ay, az, exponent)\n', (4780, 4806), False, 'from cirq.linalg import operator_spaces\n'), ((5392, 5441), 'numpy.zeros', 'np.zeros', (['(num_dim, num_dim)'], {'dtype': 'np.complex128'}), '((num_dim, num_dim), dtype=np.complex128)\n', (5400, 5441), True, 'import numpy as np\n'), ((5647, 5667), 'cirq.value.LinearDict', 'value.LinearDict', (['{}'], {}), '({})\n', (5663, 5667), False, 'from cirq import protocols, qis, value\n'), ((7829, 7846), 'cirq.ops.identity.I', 'identity.I', (['qubit'], {}), '(qubit)\n', (7839, 7846), False, 'from cirq.ops import identity, raw_types, pauli_gates, pauli_string\n'), ((7859, 7879), 'cirq.ops.pauli_gates.X', 'pauli_gates.X', (['qubit'], {}), '(qubit)\n', (7872, 7879), False, 'from cirq.ops import identity, raw_types, pauli_gates, pauli_string\n'), ((7892, 7912), 'cirq.ops.pauli_gates.Y', 'pauli_gates.Y', (['qubit'], {}), '(qubit)\n', (7905, 7912), False, 'from cirq.ops import identity, raw_types, pauli_gates, pauli_string\n'), ((7925, 7945), 'cirq.ops.pauli_gates.Z', 'pauli_gates.Z', (['qubit'], {}), '(qubit)\n', (7938, 7945), False, 'from cirq.ops import identity, raw_types, pauli_gates, pauli_string\n'), ((8156, 8219), 'cirq.linalg.operator_spaces.pow_pauli_combination', 'operator_spaces.pow_pauli_combination', (['ai', 'ax', 'ay', 'az', 'exponent'], {}), '(ai, ax, ay, az, exponent)\n', (8193, 8219), False, 'from cirq.linalg import operator_spaces\n'), ((8687, 8741), 'numpy.zeros', 'np.zeros', (['((2,) * (2 * num_qubits))'], {'dtype': 'np.complex128'}), '((2,) * (2 * num_qubits), dtype=np.complex128)\n', (8695, 8741), True, 'import numpy as np\n'), ((10203, 10223), 'cirq.value.LinearDict', 'value.LinearDict', (['{}'], {}), '({})\n', (10219, 10223), False, 'from cirq import protocols, qis, value\n'), ((12773, 12796), 'collections.defaultdict', 'defaultdict', (['(lambda : 0)'], {}), '(lambda : 0)\n', (12784, 12796), False, 'from collections import defaultdict\n'), ((14896, 14955), 'cirq.ops.pauli_string._validate_qubit_mapping', '_validate_qubit_mapping', (['qubit_map', 'self.qubits', 'num_qubits'], {}), '(qubit_map, self.qubits, num_qubits)\n', (14919, 14955), False, 'from cirq.ops.pauli_string import PauliString, _validate_qubit_mapping\n'), ((17223, 17282), 'cirq.ops.pauli_string._validate_qubit_mapping', '_validate_qubit_mapping', (['qubit_map', 'self.qubits', 'num_qubits'], {}), '(qubit_map, self.qubits, num_qubits)\n', (17246, 17282), False, 'from cirq.ops.pauli_string import PauliString, _validate_qubit_mapping\n'), ((21917, 21968), 'cirq.value.linear_dict._format_terms', '_format_terms', ([], {'terms': 'terms', 'format_spec': 'format_spec'}), '(terms=terms, format_spec=format_spec)\n', (21930, 21968), False, 'from cirq.value.linear_dict import _format_terms\n'), ((8923, 8946), 'numpy.empty_like', 'np.empty_like', (['identity'], {}), '(identity)\n', (8936, 8946), True, 'import numpy as np\n'), ((10324, 10353), 'cirq.protocols.pauli_expansion', 'protocols.pauli_expansion', (['op'], {}), '(op)\n', (10349, 10353), False, 'from cirq import protocols, qis, value\n'), ((11913, 11931), 'cirq.value.LinearDict', 'value.LinearDict', ([], {}), '()\n', (11929, 11931), False, 'from cirq import protocols, qis, value\n'), ((15224, 15329), 'cirq.qis.validate_normalized_state', 'qis.validate_normalized_state', ([], {'state': 'state', 'qid_shape': '((2,) * num_qubits)', 'dtype': 'state.dtype', 'atol': 'atol'}), '(state=state, qid_shape=(2,) * num_qubits,\n dtype=state.dtype, atol=atol)\n', (15253, 15329), False, 'from cirq import protocols, qis, value\n'), ((17302, 17315), 'numpy.sqrt', 'np.sqrt', (['size'], {}), '(size)\n', (17309, 17315), True, 'import numpy as np\n'), ((5511, 5534), 'cirq.protocols.unitary', 'protocols.unitary', (['gate'], {}), '(gate)\n', (5528, 5534), False, 'from cirq import protocols, qis, value\n'), ((5768, 5799), 'cirq.protocols.pauli_expansion', 'protocols.pauli_expansion', (['gate'], {}), '(gate)\n', (5793, 5799), False, 'from cirq import protocols, qis, value\n'), ((9070, 9123), 'cirq.protocols.ApplyUnitaryArgs', 'protocols.ApplyUnitaryArgs', (['identity', 'workspace', 'axes'], {}), '(identity, workspace, axes)\n', (9096, 9123), False, 'from cirq import protocols, qis, value\n'), ((12981, 13007), 'cirq.value.LinearDict', 'value.LinearDict', (['termdict'], {}), '(termdict)\n', (12997, 13007), False, 'from cirq import protocols, qis, value\n'), ((8810, 8846), 'numpy.eye', 'np.eye', (['num_dim'], {'dtype': 'np.complex128'}), '(num_dim, dtype=np.complex128)\n', (8816, 8846), True, 'import numpy as np\n'), ((18427, 18457), 'cirq.ops.pauli_string.PauliString', 'PauliString', ([], {'coefficient': 'other'}), '(coefficient=other)\n', (18438, 18457), False, 'from cirq.ops.pauli_string import PauliString, _validate_qubit_mapping\n'), ((19206, 19236), 'cirq.ops.pauli_string.PauliString', 'PauliString', ([], {'coefficient': 'other'}), '(coefficient=other)\n', (19217, 19236), False, 'from cirq.ops.pauli_string import PauliString, _validate_qubit_mapping\n'), ((17183, 17196), 'numpy.sqrt', 'np.sqrt', (['size'], {}), '(size)\n', (17190, 17196), True, 'import numpy as np\n')]
import os import sys import subprocess from joblib import Parallel, delayed import numpy as np import imageio imageio.plugins.freeimage.download() from imageio.plugins import freeimage import h5py from lz4.block import decompress import scipy.misc import cv2 from path import Path path = os.path.join(os.path.dirname(os.path.abspath(__file__))) def dump_example(dataset_name): print("Converting {:}.h5 ...".format(dataset_name)) file = h5py.File(os.path.join(path, "testdata", "{:}.h5".format(dataset_name)), "r") for (seq_idx, seq_name) in enumerate(file): if dataset_name == 'scenes11_test': scale = 0.4 else: scale = 1 print("Processing sequence {:d}/{:d}".format(seq_idx, len(file))) dump_dir = os.path.join(path, '../test', dataset_name + "_" + "{:05d}".format(seq_idx)) if not os.path.isdir(dump_dir): os.mkdir(dump_dir) dump_dir = Path(dump_dir) sequence = file[seq_name]["frames"]["t0"] poses = [] for (f_idx, f_name) in enumerate(sequence): frame = sequence[f_name] for dt_type in frame: dataset = frame[dt_type] img = dataset[...] if dt_type == "camera": if f_idx == 0: intrinsics = np.array([[img[0], 0, img[3]], [0, img[1], img[4]], [0, 0, 1]]) pose = np.array([[img[5],img[8],img[11],img[14]*scale], [img[6],img[9],img[12],img[15]*scale], [img[7],img[10],img[13],img[16]*scale]]) poses.append(pose.tolist()) elif dt_type == "depth": dimension = dataset.attrs["extents"] depth = np.array(np.frombuffer(decompress(img.tobytes(), dimension[0] * dimension[1] * 2), dtype = np.float16)).astype(np.float32) depth = depth.reshape(dimension[0], dimension[1])*scale dump_depth_file = dump_dir/'{:04d}.npy'.format(f_idx) np.save(dump_depth_file, depth) elif dt_type == "image": img = imageio.imread(img.tobytes()) dump_img_file = dump_dir/'{:04d}.jpg'.format(f_idx) scipy.misc.imsave(dump_img_file, img) dump_cam_file = dump_dir/'cam.txt' np.savetxt(dump_cam_file, intrinsics) poses_file = dump_dir/'poses.txt' np.savetxt(poses_file, np.array(poses).reshape(-1, 12), fmt='%.6e') if len(dump_dir.files('*.jpg')) < 2: dump_dir.rmtree() def preparedata(): num_threads = 1 SUB_DATASET_NAMES = (["mvs_test", "rgbd_test", "scenes11_test", "sun3d_test"]) dump_root = os.path.join(path, '../test') if not os.path.isdir(dump_root): os.mkdir(dump_root) if num_threads == 1: for scene in SUB_DATASET_NAMES: dump_example(scene) else: Parallel(n_jobs=num_threads)(delayed(dump_example)(scene) for scene in SUB_DATASET_NAMES) dump_root = Path(dump_root) subdirs = dump_root.dirs() subdirs = [subdir.basename() for subdir in subdirs] subdirs = sorted(subdirs) with open(dump_root / 'test.txt', 'w') as tf: for subdir in subdirs: tf.write('{}\n'.format(subdir)) print("Finished Converting Data.") if __name__ == "__main__": preparedata()
[ "os.path.join", "joblib.Parallel", "path.Path", "numpy.array", "os.path.isdir", "os.mkdir", "numpy.savetxt", "os.path.abspath", "joblib.delayed", "imageio.plugins.freeimage.download", "numpy.save" ]
[((111, 147), 'imageio.plugins.freeimage.download', 'imageio.plugins.freeimage.download', ([], {}), '()\n', (145, 147), False, 'import imageio\n'), ((2710, 2739), 'os.path.join', 'os.path.join', (['path', '"""../test"""'], {}), "(path, '../test')\n", (2722, 2739), False, 'import os\n'), ((3028, 3043), 'path.Path', 'Path', (['dump_root'], {}), '(dump_root)\n', (3032, 3043), False, 'from path import Path\n'), ((320, 345), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (335, 345), False, 'import os\n'), ((944, 958), 'path.Path', 'Path', (['dump_dir'], {}), '(dump_dir)\n', (948, 958), False, 'from path import Path\n'), ((2338, 2375), 'numpy.savetxt', 'np.savetxt', (['dump_cam_file', 'intrinsics'], {}), '(dump_cam_file, intrinsics)\n', (2348, 2375), True, 'import numpy as np\n'), ((2751, 2775), 'os.path.isdir', 'os.path.isdir', (['dump_root'], {}), '(dump_root)\n', (2764, 2775), False, 'import os\n'), ((2785, 2804), 'os.mkdir', 'os.mkdir', (['dump_root'], {}), '(dump_root)\n', (2793, 2804), False, 'import os\n'), ((869, 892), 'os.path.isdir', 'os.path.isdir', (['dump_dir'], {}), '(dump_dir)\n', (882, 892), False, 'import os\n'), ((906, 924), 'os.mkdir', 'os.mkdir', (['dump_dir'], {}), '(dump_dir)\n', (914, 924), False, 'import os\n'), ((2921, 2949), 'joblib.Parallel', 'Parallel', ([], {'n_jobs': 'num_threads'}), '(n_jobs=num_threads)\n', (2929, 2949), False, 'from joblib import Parallel, delayed\n'), ((1430, 1578), 'numpy.array', 'np.array', (['[[img[5], img[8], img[11], img[14] * scale], [img[6], img[9], img[12], img[\n 15] * scale], [img[7], img[10], img[13], img[16] * scale]]'], {}), '([[img[5], img[8], img[11], img[14] * scale], [img[6], img[9], img[\n 12], img[15] * scale], [img[7], img[10], img[13], img[16] * scale]])\n', (1438, 1578), True, 'import numpy as np\n'), ((2449, 2464), 'numpy.array', 'np.array', (['poses'], {}), '(poses)\n', (2457, 2464), True, 'import numpy as np\n'), ((2950, 2971), 'joblib.delayed', 'delayed', (['dump_example'], {}), '(dump_example)\n', (2957, 2971), False, 'from joblib import Parallel, delayed\n'), ((1339, 1402), 'numpy.array', 'np.array', (['[[img[0], 0, img[3]], [0, img[1], img[4]], [0, 0, 1]]'], {}), '([[img[0], 0, img[3]], [0, img[1], img[4]], [0, 0, 1]])\n', (1347, 1402), True, 'import numpy as np\n'), ((2027, 2058), 'numpy.save', 'np.save', (['dump_depth_file', 'depth'], {}), '(dump_depth_file, depth)\n', (2034, 2058), True, 'import numpy as np\n')]
# coding: utf-8 # # Color grading with optimal transport # # #### *<NAME>, <NAME>* # In this tutorial we will learn how to perform color grading of images with optimal transport. This is somehow a very direct usage of optimal transport. You will learn how to treat an image as an empirical distribution, and apply optimal transport to find a matching between two different images seens as distributions. # First we need to load two images. To this end we need some packages # # In[2]: import numpy as np import matplotlib.pylab as pl from matplotlib.pyplot import imread from mpl_toolkits.mplot3d import Axes3D I1 = imread('./data/klimt.jpg').astype(np.float64) / 256 I2 = imread('./data/schiele.jpg').astype(np.float64) / 256 # We need some code to visualize them # In[3]: def showImage(I,myPreferredFigsize=(8,8)): pl.figure(figsize=myPreferredFigsize) pl.imshow(I) pl.axis('off') pl.tight_layout() pl.show() # In[4]: showImage(I1) showImage(I2) # Those are two beautiful paintings of respectively <NAME> and <NAME>. Now we will treat them as empirical distributions. # Write two functions that will be used to convert 2D images as arrays of 3D points (in the color space), and back. # In[5]: def im2mat(I): """Converts and image to matrix (one pixel per line)""" return I.reshape((I.shape[0] * I.shape[1], I.shape[2])) def mat2im(X, shape): """Converts back a matrix to an image""" return X.reshape(shape) X1 = im2mat(I1) X2 = im2mat(I2) # It is unlikely that our solver, as efficient it can be, can handle so large distributions (1Mx1M for the coupling). We will use the Mini batch k-means procedure from sklearn to subsample those distributions. Write the code that performs this subsampling (you can choose a size of 1000 clusters to have a good approximation of the image) # In[6]: import sklearn.cluster as skcluster nbsamples=1000 clust1 = skcluster.MiniBatchKMeans(n_clusters=nbsamples,init_size=3000).fit(X1) Xs = clust1.cluster_centers_ clust2 = skcluster.MiniBatchKMeans(n_clusters=nbsamples,init_size=3000).fit(X2) Xt = clust2.cluster_centers_ # You can use the following procedure to display them as point clouds # In[7]: def showImageAsPointCloud(X,myPreferredFigsize=(8,8)): fig = pl.figure(figsize=myPreferredFigsize) ax = fig.add_subplot(111, projection='3d') ax.set_xlim(0,1) ax.scatter(X[:,0], X[:,1], X[:,2], c=X, marker='o', alpha=1.0) ax.set_xlabel('R',fontsize=22) ax.set_xticklabels([]) ax.set_ylim(0,1) ax.set_ylabel('G',fontsize=22) ax.set_yticklabels([]) ax.set_zlim(0,1) ax.set_zlabel('B',fontsize=22) ax.set_zticklabels([]) ax.grid('off') pl.show() # In[8]: showImageAsPointCloud(Xs) showImageAsPointCloud(Xt) # You can now compute the coupling between those two distributions using the exact LP solver (EMD) # In[9]: import ot mu_s = ot.unif(nbsamples) mu_t = ot.unif(nbsamples) M = ot.dist(Xs,Xt,"sqeuclidean") G = ot.emd(mu_s,mu_t, M) # using the barycentric mapping method, express the tansformation of both images into the other one # In[10]: newXs=nbsamples*G.dot(Xt) showImageAsPointCloud(newXs) newXt=nbsamples*G.T.dot(Xs) newXt[newXt>1]=1 showImageAsPointCloud(newXt) # Since only the centroid of clusters have changed, we need to figure out a simple way of transporting all the pixels in the original image. At first, we will apply a simple strategy where the new value of the pixel corresponds simply to the new position of its corresponding centroid # Express this transformation in your code, and display the corresponding adapted image. # In[11]: newX1 = newXs[clust1.predict(X1),:] showImage(mat2im(newX1,I1.shape)) newX2 = newXt[clust2.predict(X2),:] showImage(mat2im(newX2,I2.shape)) # You can use also the entropy regularized version of Optimal Transport (a.k.a. the Sinkhorn algorithm) to explore the impact of regularization on the final result # # In[12]: for reg in np.logspace(-3,0,4): G = ot.bregman.sinkhorn(mu_s,mu_t, M, reg) newXs=nbsamples*G.dot(Xt) showImageAsPointCloud(newXs) newX1 = newXs[clust1.predict(X1),:] showImage(mat2im(newX1,I1.shape))
[ "matplotlib.pylab.axis", "matplotlib.pylab.figure", "ot.unif", "matplotlib.pylab.tight_layout", "sklearn.cluster.MiniBatchKMeans", "matplotlib.pyplot.imread", "ot.bregman.sinkhorn", "ot.dist", "matplotlib.pylab.imshow", "ot.emd", "matplotlib.pylab.show", "numpy.logspace" ]
[((2908, 2926), 'ot.unif', 'ot.unif', (['nbsamples'], {}), '(nbsamples)\n', (2915, 2926), False, 'import ot\n'), ((2934, 2952), 'ot.unif', 'ot.unif', (['nbsamples'], {}), '(nbsamples)\n', (2941, 2952), False, 'import ot\n'), ((2957, 2987), 'ot.dist', 'ot.dist', (['Xs', 'Xt', '"""sqeuclidean"""'], {}), "(Xs, Xt, 'sqeuclidean')\n", (2964, 2987), False, 'import ot\n'), ((2990, 3011), 'ot.emd', 'ot.emd', (['mu_s', 'mu_t', 'M'], {}), '(mu_s, mu_t, M)\n', (2996, 3011), False, 'import ot\n'), ((3980, 4001), 'numpy.logspace', 'np.logspace', (['(-3)', '(0)', '(4)'], {}), '(-3, 0, 4)\n', (3991, 4001), True, 'import numpy as np\n'), ((837, 874), 'matplotlib.pylab.figure', 'pl.figure', ([], {'figsize': 'myPreferredFigsize'}), '(figsize=myPreferredFigsize)\n', (846, 874), True, 'import matplotlib.pylab as pl\n'), ((879, 891), 'matplotlib.pylab.imshow', 'pl.imshow', (['I'], {}), '(I)\n', (888, 891), True, 'import matplotlib.pylab as pl\n'), ((896, 910), 'matplotlib.pylab.axis', 'pl.axis', (['"""off"""'], {}), "('off')\n", (903, 910), True, 'import matplotlib.pylab as pl\n'), ((915, 932), 'matplotlib.pylab.tight_layout', 'pl.tight_layout', ([], {}), '()\n', (930, 932), True, 'import matplotlib.pylab as pl\n'), ((937, 946), 'matplotlib.pylab.show', 'pl.show', ([], {}), '()\n', (944, 946), True, 'import matplotlib.pylab as pl\n'), ((2278, 2315), 'matplotlib.pylab.figure', 'pl.figure', ([], {'figsize': 'myPreferredFigsize'}), '(figsize=myPreferredFigsize)\n', (2287, 2315), True, 'import matplotlib.pylab as pl\n'), ((2702, 2711), 'matplotlib.pylab.show', 'pl.show', ([], {}), '()\n', (2709, 2711), True, 'import matplotlib.pylab as pl\n'), ((4009, 4048), 'ot.bregman.sinkhorn', 'ot.bregman.sinkhorn', (['mu_s', 'mu_t', 'M', 'reg'], {}), '(mu_s, mu_t, M, reg)\n', (4028, 4048), False, 'import ot\n'), ((1919, 1982), 'sklearn.cluster.MiniBatchKMeans', 'skcluster.MiniBatchKMeans', ([], {'n_clusters': 'nbsamples', 'init_size': '(3000)'}), '(n_clusters=nbsamples, init_size=3000)\n', (1944, 1982), True, 'import sklearn.cluster as skcluster\n'), ((2029, 2092), 'sklearn.cluster.MiniBatchKMeans', 'skcluster.MiniBatchKMeans', ([], {'n_clusters': 'nbsamples', 'init_size': '(3000)'}), '(n_clusters=nbsamples, init_size=3000)\n', (2054, 2092), True, 'import sklearn.cluster as skcluster\n'), ((627, 653), 'matplotlib.pyplot.imread', 'imread', (['"""./data/klimt.jpg"""'], {}), "('./data/klimt.jpg')\n", (633, 653), False, 'from matplotlib.pyplot import imread\n'), ((684, 712), 'matplotlib.pyplot.imread', 'imread', (['"""./data/schiele.jpg"""'], {}), "('./data/schiele.jpg')\n", (690, 712), False, 'from matplotlib.pyplot import imread\n')]
import os import pandas as pd import numpy as np import matplotlib.pyplot as plt import sys import seaborn as sns sns.set(style="whitegrid") sys.path.append(os.path.abspath(".")) import config from src.features import fe from src.utli import utli # read data df_main = fe.mergred_store_and_user() # check missing rate and drop some vars has serious missing rate dataReport = utli.missing_data(df_main) criteria = 0.25 drop_list = [i for i in dataReport[dataReport['Percent'] > criteria].index] # loop drop process df_EDA = df_main for i in drop_list: df_EDA = df_EDA.drop(i, axis = 1) """ ****user userID placeID rating food_rating service_rating latitude_x longitude_x smoker ,drink_level ,dress_preference ,ambience ,transport ,marital_status ,hijos ,birth_year ,interest ,personality ,religion ,activity ,color ,budget ## numeric weight height Upayment ****store latitude_y longitude_y store_the_geom_meter store_address store_city, store_state, store_country, store_alcohol, store_smoking_area, store_dress_code store_accessibility, store_price, store_Rambience, store_area, store_other_services, park ## numeric cuisin fri_hours mon_hours sat_hours sun_hours thu_hours tue_hours wed_hours park payment distance_between_user_and_store """ # start to plot user_non_numeric = ['smoker', 'drink_level', 'dress_preference','ambience', 'transport', 'marital_status', 'hijos', 'interest', 'personality', 'religion', 'activity','color', 'budget', ] store_non_numeric = ['store_alcohol', 'store_smoking_area', 'store_dress_code', 'store_accessibility', 'store_price', 'store_Rambience', 'store_area', 'store_other_services', 'park'] if 0: for var_temp_user in user_non_numeric: for var_temp_store in store_non_numeric: fig, ax = plt.subplots(figsize=(10, 8)) g = sns.barplot(x = var_temp_user, y ='rating', hue = var_temp_store, data = df_EDA) avg = df_EDA['rating'].mean() plt.xlabel(var_temp_user) plt.ylabel('rating') plt.title('{1} in different {0} and {2}'.format(var_temp_user, 'rating',var_temp_store)) # g.legend(loc='upper left', frameon=False) plt.legend(bbox_to_anchor=(0.95, 1), loc="upper left") plt.axhline(avg, color='r', linestyle='dashed', linewidth=2) # 繪製平均線 plt.savefig('{}/rating_by_{}_and_{}_barplot.jpg'.format(config.fig_report_path, var_temp_user, var_temp_store) ,pad = 0.5) plt.close() for var_temp_user in user_non_numeric: for var_temp_store in store_non_numeric: fig, ax = plt.subplots(figsize=(10, 8)) g = sns.barplot(x = var_temp_user, y ='food_rating', hue = var_temp_store, data = df_EDA) avg = df_EDA['food_rating'].mean() plt.xlabel(var_temp_user) plt.ylabel('food_rating') plt.title('{1} in different {0} by different {2}'.format(var_temp_user, 'food_rating',var_temp_store)) # g.legend(loc='upper left', frameon=False) plt.legend(bbox_to_anchor=(0.95, 1), loc="upper left") plt.axhline(avg, color='r', linestyle='dashed', linewidth=1) # 繪製平均線 plt.savefig('{}/food_rating_by_{}_and_{}_barplot.jpg'.format(config.fig_report_path, var_temp_user, var_temp_store) ,pad = 0.5) plt.close() for var_temp_user in user_non_numeric: for var_temp_store in store_non_numeric: fig, ax = plt.subplots(figsize=(10, 8)) g = sns.barplot(x = var_temp_user, y ='service_rating', hue = var_temp_store, data = df_EDA) avg = df_EDA['service_rating'].mean() plt.xlabel(var_temp_user) plt.ylabel('service_rating') plt.title('{1} in different {0} by different {2}'.format(var_temp_user, 'service_rating',var_temp_store)) g.legend(loc='upper left', frameon=False) plt.legend(bbox_to_anchor=(0.95, 1), loc="upper left") # plt.axhline(avg, color='r', linestyle='dashed', linewidth=1) # 繪製平均線 plt.savefig('{}/service_rating_by_{}_and_{}_barplot.jpg'.format(config.fig_report_path, var_temp_user, var_temp_store) ,pad = 0.5) plt.close() if 0: for var_temp_user in user_non_numeric: # for var_temp_store in store_non_numeric: fig, ax = plt.subplots(figsize=(10, 8)) g = sns.scatterplot(x='service_rating', y='food_rating', hue = var_temp_user, size = 'rating', data=df_EDA ,ax=ax) avg = df_EDA['rating'].mean() plt.xlabel('service_rating') plt.ylabel('food_rating') plt.title('service_rating and food_rating in different {0} by rating'.format(var_temp_user)) # g.legend(loc='upper left', frameon=False) plt.legend(bbox_to_anchor=(0.95, 1), loc= 0) # plt.axhline(avg, color='r', linestyle='dashed', linewidth=2) # 繪製平均線 plt.savefig('{0}/service_rating and food_rating in different {1} by rating_scatterplot.jpg'.format(config.fig_report_path, var_temp_user) ,pad = 0.5) plt.close() if 0: for var_temp_user in user_non_numeric: for var_temp_store in store_non_numeric: g = sns.catplot(x= 'rating', y= var_temp_user, row= var_temp_store, kind="violin", orient="h", height = 1.5, aspect=4, data=df_EDA ) # avg = df_EDA['rating'].mean() plt.xlabel('rating') # plt.ylabel('food_rating') # plt.title('service_rating and in different {0} by rating'.format(var_temp_user)) # g.legend(loc='upper left', frameon=False) # plt.legend(bbox_to_anchor=(0.95, 1), loc= 0) # plt.axhline(avg, color='r', linestyle='dashed', linewidth=2) # 繪製平均線 plt.savefig('{0}/ {1} and {2} rating_catplot.jpg'.format(config.fig_report_path, var_temp_user, var_temp_store) ,pad = 0.5) plt.close() modeling_numeric_list = ['birth_year', 'payment_methods', 'number_of_store_cuisin','cuisine_match', 'num_of_Upayment', 'height'] # for i in modeling_numeric_list: # for var_temp_user in user_non_numeric: # for var_temp_store in store_non_numeric: # fig, ax = plt.subplots(figsize=(10, 8)) # sns.scatterplot(x='rating', y= i, # hue = var_temp_user, size = var_temp_store, data=df_EDA ,ax=ax) # plt.xlabel('rating') # plt.savefig('{0}/rating_by_{1}by_{2}by_{3}_scater.jpg'.format(config.fig_report_path, i,var_temp_user, var_temp_store) # ,pad = 0.5) # plt.close() # 'latitude_x', 'longitude_x', 'latitude_y', 'longitude_y' # fig, ax = plt.subplots(figsize=(10, 8)) # sns.scatterplot(x='latitude_y', y='longitude_y', hue = 'rating', data=df_EDA ,ax=ax) # plt.show() # fig, ax = plt.subplots(figsize=(10, 8)) if 1: # fig, ax = plt.subplots(figsize=(10, 8)) sns.catplot(x= 'rating', y= 'store_dress_code', kind="violin", orient="h", height= 2, aspect=4, data=df_EDA ) plt.xlabel('rating') plt.title('store_dress_code vs rating') plt.savefig('1233.png', pad = 0.5) plt.show() sys.exit() fig, ax = plt.subplots(figsize=(10, 8)) sns.scatterplot(x='food_rating', y='service_rating', hue = 'religion', data=df_EDA ,ax=ax) # ax = ax plt.show() co = df_EDA.corr() mask = np.zeros_like(co) # minor mask to filter out a half of vars mask[np.triu_indices_from(mask)] = True fig, ax = plt.subplots(figsize=(8, 8)) sns.heatmap(co, mask=mask, vmax=0.5, square=True, annot= True, fmt = '.2f',linewidths = 0.2) plt.savefig('%s/dfcorr.jpg'%(config.fig_report_path),pad = 0.5) plt.show() # sns.regplot(x= 'weight', y ='rating',data = df_EDA) # plt.show() # sns.regplot(x= 'height', y ='rating',data = df_EDA) # plt.show() # corr chart # kernel chat # parallel chart
[ "matplotlib.pyplot.ylabel", "seaborn.catplot", "src.utli.utli.missing_data", "seaborn.scatterplot", "sys.exit", "seaborn.set", "src.features.fe.mergred_store_and_user", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.close", "matplotlib.pyplot.axhline", "matplotlib.pyplot.savefig", "numpy.triu_...
[((114, 140), 'seaborn.set', 'sns.set', ([], {'style': '"""whitegrid"""'}), "(style='whitegrid')\n", (121, 140), True, 'import seaborn as sns\n'), ((270, 297), 'src.features.fe.mergred_store_and_user', 'fe.mergred_store_and_user', ([], {}), '()\n', (295, 297), False, 'from src.features import fe\n'), ((378, 404), 'src.utli.utli.missing_data', 'utli.missing_data', (['df_main'], {}), '(df_main)\n', (395, 404), False, 'from src.utli import utli\n'), ((7468, 7478), 'sys.exit', 'sys.exit', ([], {}), '()\n', (7476, 7478), False, 'import sys\n'), ((7491, 7520), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(10, 8)'}), '(figsize=(10, 8))\n', (7503, 7520), True, 'import matplotlib.pyplot as plt\n'), ((7521, 7614), 'seaborn.scatterplot', 'sns.scatterplot', ([], {'x': '"""food_rating"""', 'y': '"""service_rating"""', 'hue': '"""religion"""', 'data': 'df_EDA', 'ax': 'ax'}), "(x='food_rating', y='service_rating', hue='religion', data=\n df_EDA, ax=ax)\n", (7536, 7614), True, 'import seaborn as sns\n'), ((7622, 7632), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (7630, 7632), True, 'import matplotlib.pyplot as plt\n'), ((7661, 7678), 'numpy.zeros_like', 'np.zeros_like', (['co'], {}), '(co)\n', (7674, 7678), True, 'import numpy as np\n'), ((7771, 7799), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(8, 8)'}), '(figsize=(8, 8))\n', (7783, 7799), True, 'import matplotlib.pyplot as plt\n'), ((7800, 7892), 'seaborn.heatmap', 'sns.heatmap', (['co'], {'mask': 'mask', 'vmax': '(0.5)', 'square': '(True)', 'annot': '(True)', 'fmt': '""".2f"""', 'linewidths': '(0.2)'}), "(co, mask=mask, vmax=0.5, square=True, annot=True, fmt='.2f',\n linewidths=0.2)\n", (7811, 7892), True, 'import seaborn as sns\n'), ((7893, 7955), 'matplotlib.pyplot.savefig', 'plt.savefig', (["('%s/dfcorr.jpg' % config.fig_report_path)"], {'pad': '(0.5)'}), "('%s/dfcorr.jpg' % config.fig_report_path, pad=0.5)\n", (7904, 7955), True, 'import matplotlib.pyplot as plt\n'), ((7957, 7967), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (7965, 7967), True, 'import matplotlib.pyplot as plt\n'), ((157, 177), 'os.path.abspath', 'os.path.abspath', (['"""."""'], {}), "('.')\n", (172, 177), False, 'import os\n'), ((7185, 7294), 'seaborn.catplot', 'sns.catplot', ([], {'x': '"""rating"""', 'y': '"""store_dress_code"""', 'kind': '"""violin"""', 'orient': '"""h"""', 'height': '(2)', 'aspect': '(4)', 'data': 'df_EDA'}), "(x='rating', y='store_dress_code', kind='violin', orient='h',\n height=2, aspect=4, data=df_EDA)\n", (7196, 7294), True, 'import seaborn as sns\n'), ((7349, 7369), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""rating"""'], {}), "('rating')\n", (7359, 7369), True, 'import matplotlib.pyplot as plt\n'), ((7374, 7413), 'matplotlib.pyplot.title', 'plt.title', (['"""store_dress_code vs rating"""'], {}), "('store_dress_code vs rating')\n", (7383, 7413), True, 'import matplotlib.pyplot as plt\n'), ((7418, 7450), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""1233.png"""'], {'pad': '(0.5)'}), "('1233.png', pad=0.5)\n", (7429, 7450), True, 'import matplotlib.pyplot as plt\n'), ((7457, 7467), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (7465, 7467), True, 'import matplotlib.pyplot as plt\n'), ((7726, 7752), 'numpy.triu_indices_from', 'np.triu_indices_from', (['mask'], {}), '(mask)\n', (7746, 7752), True, 'import numpy as np\n'), ((4516, 4545), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(10, 8)'}), '(figsize=(10, 8))\n', (4528, 4545), True, 'import matplotlib.pyplot as plt\n'), ((4558, 4668), 'seaborn.scatterplot', 'sns.scatterplot', ([], {'x': '"""service_rating"""', 'y': '"""food_rating"""', 'hue': 'var_temp_user', 'size': '"""rating"""', 'data': 'df_EDA', 'ax': 'ax'}), "(x='service_rating', y='food_rating', hue=var_temp_user,\n size='rating', data=df_EDA, ax=ax)\n", (4573, 4668), True, 'import seaborn as sns\n'), ((4716, 4744), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""service_rating"""'], {}), "('service_rating')\n", (4726, 4744), True, 'import matplotlib.pyplot as plt\n'), ((4753, 4778), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""food_rating"""'], {}), "('food_rating')\n", (4763, 4778), True, 'import matplotlib.pyplot as plt\n'), ((4940, 4983), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'bbox_to_anchor': '(0.95, 1)', 'loc': '(0)'}), '(bbox_to_anchor=(0.95, 1), loc=0)\n', (4950, 4983), True, 'import matplotlib.pyplot as plt\n'), ((5250, 5261), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (5259, 5261), True, 'import matplotlib.pyplot as plt\n'), ((1884, 1913), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(10, 8)'}), '(figsize=(10, 8))\n', (1896, 1913), True, 'import matplotlib.pyplot as plt\n'), ((1930, 2003), 'seaborn.barplot', 'sns.barplot', ([], {'x': 'var_temp_user', 'y': '"""rating"""', 'hue': 'var_temp_store', 'data': 'df_EDA'}), "(x=var_temp_user, y='rating', hue=var_temp_store, data=df_EDA)\n", (1941, 2003), True, 'import seaborn as sns\n'), ((2065, 2090), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['var_temp_user'], {}), '(var_temp_user)\n', (2075, 2090), True, 'import matplotlib.pyplot as plt\n'), ((2103, 2123), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""rating"""'], {}), "('rating')\n", (2113, 2123), True, 'import matplotlib.pyplot as plt\n'), ((2294, 2348), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'bbox_to_anchor': '(0.95, 1)', 'loc': '"""upper left"""'}), "(bbox_to_anchor=(0.95, 1), loc='upper left')\n", (2304, 2348), True, 'import matplotlib.pyplot as plt\n'), ((2361, 2421), 'matplotlib.pyplot.axhline', 'plt.axhline', (['avg'], {'color': '"""r"""', 'linestyle': '"""dashed"""', 'linewidth': '(2)'}), "(avg, color='r', linestyle='dashed', linewidth=2)\n", (2372, 2421), True, 'import matplotlib.pyplot as plt\n'), ((2601, 2612), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (2610, 2612), True, 'import matplotlib.pyplot as plt\n'), ((2736, 2765), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(10, 8)'}), '(figsize=(10, 8))\n', (2748, 2765), True, 'import matplotlib.pyplot as plt\n'), ((2782, 2860), 'seaborn.barplot', 'sns.barplot', ([], {'x': 'var_temp_user', 'y': '"""food_rating"""', 'hue': 'var_temp_store', 'data': 'df_EDA'}), "(x=var_temp_user, y='food_rating', hue=var_temp_store, data=df_EDA)\n", (2793, 2860), True, 'import seaborn as sns\n'), ((2927, 2952), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['var_temp_user'], {}), '(var_temp_user)\n', (2937, 2952), True, 'import matplotlib.pyplot as plt\n'), ((2965, 2990), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""food_rating"""'], {}), "('food_rating')\n", (2975, 2990), True, 'import matplotlib.pyplot as plt\n'), ((3174, 3228), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'bbox_to_anchor': '(0.95, 1)', 'loc': '"""upper left"""'}), "(bbox_to_anchor=(0.95, 1), loc='upper left')\n", (3184, 3228), True, 'import matplotlib.pyplot as plt\n'), ((3241, 3301), 'matplotlib.pyplot.axhline', 'plt.axhline', (['avg'], {'color': '"""r"""', 'linestyle': '"""dashed"""', 'linewidth': '(1)'}), "(avg, color='r', linestyle='dashed', linewidth=1)\n", (3252, 3301), True, 'import matplotlib.pyplot as plt\n'), ((3487, 3498), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (3496, 3498), True, 'import matplotlib.pyplot as plt\n'), ((3618, 3647), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(10, 8)'}), '(figsize=(10, 8))\n', (3630, 3647), True, 'import matplotlib.pyplot as plt\n'), ((3664, 3750), 'seaborn.barplot', 'sns.barplot', ([], {'x': 'var_temp_user', 'y': '"""service_rating"""', 'hue': 'var_temp_store', 'data': 'df_EDA'}), "(x=var_temp_user, y='service_rating', hue=var_temp_store, data=\n df_EDA)\n", (3675, 3750), True, 'import seaborn as sns\n'), ((3815, 3840), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['var_temp_user'], {}), '(var_temp_user)\n', (3825, 3840), True, 'import matplotlib.pyplot as plt\n'), ((3853, 3881), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""service_rating"""'], {}), "('service_rating')\n", (3863, 3881), True, 'import matplotlib.pyplot as plt\n'), ((4066, 4120), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'bbox_to_anchor': '(0.95, 1)', 'loc': '"""upper left"""'}), "(bbox_to_anchor=(0.95, 1), loc='upper left')\n", (4076, 4120), True, 'import matplotlib.pyplot as plt\n'), ((4384, 4395), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (4393, 4395), True, 'import matplotlib.pyplot as plt\n'), ((5378, 5504), 'seaborn.catplot', 'sns.catplot', ([], {'x': '"""rating"""', 'y': 'var_temp_user', 'row': 'var_temp_store', 'kind': '"""violin"""', 'orient': '"""h"""', 'height': '(1.5)', 'aspect': '(4)', 'data': 'df_EDA'}), "(x='rating', y=var_temp_user, row=var_temp_store, kind='violin',\n orient='h', height=1.5, aspect=4, data=df_EDA)\n", (5389, 5504), True, 'import seaborn as sns\n'), ((5619, 5639), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""rating"""'], {}), "('rating')\n", (5629, 5639), True, 'import matplotlib.pyplot as plt\n'), ((6145, 6156), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (6154, 6156), True, 'import matplotlib.pyplot as plt\n')]
import itertools import random from typing import Callable from typing import Dict from typing import List from typing import Optional from typing import Tuple from typing import Union from unittest.mock import patch from unittest.mock import PropertyMock import numpy as np import pytest import optuna from optuna.samplers import _tpe from optuna.samplers import TPESampler class MockSystemAttr: def __init__(self) -> None: self.value = {} # type: Dict[str, dict] def set_trial_system_attr(self, _: int, key: str, value: dict) -> None: self.value[key] = value def test_multi_objective_sample_independent_seed_fix() -> None: study = optuna.create_study(directions=["minimize", "maximize"]) dist = optuna.distributions.UniformDistribution(1.0, 100.0) random.seed(128) past_trials = [frozen_trial_factory(i, [random.random(), random.random()]) for i in range(16)] # Prepare a trial and a sample for later checks. trial = frozen_trial_factory(16, [0, 0]) sampler = TPESampler(seed=0) attrs = MockSystemAttr() with patch.object(study._storage, "get_all_trials", return_value=past_trials), patch.object( study._storage, "set_trial_system_attr", side_effect=attrs.set_trial_system_attr ), patch.object(study._storage, "get_trial", return_value=trial), patch( "optuna.trial.Trial.system_attrs", new_callable=PropertyMock ) as mock1, patch( "optuna.trial.FrozenTrial.system_attrs", new_callable=PropertyMock, ) as mock2: mock1.return_value = attrs.value mock2.return_value = attrs.value suggestion = sampler.sample_independent(study, trial, "param-a", dist) sampler = TPESampler(seed=0) attrs = MockSystemAttr() with patch.object(study._storage, "get_all_trials", return_value=past_trials), patch.object( study._storage, "set_trial_system_attr", side_effect=attrs.set_trial_system_attr ), patch.object(study._storage, "get_trial", return_value=trial), patch( "optuna.trial.Trial.system_attrs", new_callable=PropertyMock ) as mock1, patch( "optuna.trial.FrozenTrial.system_attrs", new_callable=PropertyMock, ) as mock2: mock1.return_value = attrs.value mock2.return_value = attrs.value assert sampler.sample_independent(study, trial, "param-a", dist) == suggestion sampler = TPESampler(seed=1) attrs = MockSystemAttr() with patch.object(study._storage, "get_all_trials", return_value=past_trials), patch.object( study._storage, "set_trial_system_attr", side_effect=attrs.set_trial_system_attr ), patch.object(study._storage, "get_trial", return_value=trial), patch( "optuna.trial.Trial.system_attrs", new_callable=PropertyMock ) as mock1, patch( "optuna.trial.FrozenTrial.system_attrs", new_callable=PropertyMock, ) as mock2: mock1.return_value = attrs.value mock2.return_value = attrs.value assert sampler.sample_independent(study, trial, "param-a", dist) != suggestion def test_multi_objective_sample_independent_prior() -> None: study = optuna.create_study(directions=["minimize", "maximize"]) dist = optuna.distributions.UniformDistribution(1.0, 100.0) random.seed(128) past_trials = [frozen_trial_factory(i, [random.random(), random.random()]) for i in range(16)] # Prepare a trial and a sample for later checks. trial = frozen_trial_factory(16, [0, 0]) sampler = TPESampler(seed=0) attrs = MockSystemAttr() with patch.object(study._storage, "get_all_trials", return_value=past_trials), patch.object( study._storage, "set_trial_system_attr", side_effect=attrs.set_trial_system_attr ), patch.object(study._storage, "get_trial", return_value=trial), patch( "optuna.trial.Trial.system_attrs", new_callable=PropertyMock ) as mock1, patch( "optuna.trial.FrozenTrial.system_attrs", new_callable=PropertyMock, ) as mock2: mock1.return_value = attrs.value mock2.return_value = attrs.value suggestion = sampler.sample_independent(study, trial, "param-a", dist) sampler = TPESampler(consider_prior=False, seed=0) attrs = MockSystemAttr() with patch.object(study._storage, "get_all_trials", return_value=past_trials), patch.object( study._storage, "set_trial_system_attr", side_effect=attrs.set_trial_system_attr ), patch.object(study._storage, "get_trial", return_value=trial), patch( "optuna.trial.Trial.system_attrs", new_callable=PropertyMock ) as mock1, patch( "optuna.trial.FrozenTrial.system_attrs", new_callable=PropertyMock, ) as mock2: mock1.return_value = attrs.value mock2.return_value = attrs.value assert sampler.sample_independent(study, trial, "param-a", dist) != suggestion sampler = TPESampler(prior_weight=0.5, seed=0) attrs = MockSystemAttr() with patch.object(study._storage, "get_all_trials", return_value=past_trials), patch.object( study._storage, "set_trial_system_attr", side_effect=attrs.set_trial_system_attr ), patch.object(study._storage, "get_trial", return_value=trial), patch( "optuna.trial.Trial.system_attrs", new_callable=PropertyMock ) as mock1, patch( "optuna.trial.FrozenTrial.system_attrs", new_callable=PropertyMock, ) as mock2: mock1.return_value = attrs.value mock2.return_value = attrs.value assert sampler.sample_independent(study, trial, "param-a", dist) != suggestion def test_multi_objective_sample_independent_n_startup_trial() -> None: study = optuna.create_study(directions=["minimize", "maximize"]) dist = optuna.distributions.UniformDistribution(1.0, 100.0) random.seed(128) past_trials = [frozen_trial_factory(i, [random.random(), random.random()]) for i in range(16)] trial = frozen_trial_factory(16, [0, 0]) sampler = TPESampler(n_startup_trials=16, seed=0) attrs = MockSystemAttr() with patch.object( study._storage, "get_all_trials", return_value=past_trials[:15] ), patch.object( study._storage, "set_trial_system_attr", side_effect=attrs.set_trial_system_attr ), patch.object( study._storage, "get_trial", return_value=trial ), patch( "optuna.trial.Trial.system_attrs", new_callable=PropertyMock ) as mock1, patch( "optuna.trial.FrozenTrial.system_attrs", new_callable=PropertyMock, ) as mock2, patch.object( optuna.samplers.RandomSampler, "sample_independent", return_value=1.0, ) as sample_method: mock1.return_value = attrs.value mock2.return_value = attrs.value sampler.sample_independent(study, trial, "param-a", dist) assert sample_method.call_count == 1 sampler = TPESampler(n_startup_trials=16, seed=0) attrs = MockSystemAttr() with patch.object(study._storage, "get_all_trials", return_value=past_trials), patch.object( study._storage, "set_trial_system_attr", side_effect=attrs.set_trial_system_attr ), patch.object(study._storage, "get_trial", return_value=trial), patch( "optuna.trial.Trial.system_attrs", new_callable=PropertyMock ) as mock1, patch( "optuna.trial.FrozenTrial.system_attrs", new_callable=PropertyMock, ) as mock2, patch.object( optuna.samplers.RandomSampler, "sample_independent", return_value=1.0, ) as sample_method: mock1.return_value = attrs.value mock2.return_value = attrs.value sampler.sample_independent(study, trial, "param-a", dist) assert sample_method.call_count == 0 def test_multi_objective_sample_independent_misc_arguments() -> None: study = optuna.create_study(directions=["minimize", "maximize"]) dist = optuna.distributions.UniformDistribution(1.0, 100.0) random.seed(128) past_trials = [frozen_trial_factory(i, [random.random(), random.random()]) for i in range(32)] # Prepare a trial and a sample for later checks. trial = frozen_trial_factory(16, [0, 0]) sampler = TPESampler(seed=0) attrs = MockSystemAttr() with patch.object(study._storage, "get_all_trials", return_value=past_trials), patch.object( study._storage, "set_trial_system_attr", side_effect=attrs.set_trial_system_attr ), patch.object(study._storage, "get_trial", return_value=trial), patch( "optuna.trial.Trial.system_attrs", new_callable=PropertyMock ) as mock1, patch( "optuna.trial.FrozenTrial.system_attrs", new_callable=PropertyMock, ) as mock2: mock1.return_value = attrs.value mock2.return_value = attrs.value suggestion = sampler.sample_independent(study, trial, "param-a", dist) # Test misc. parameters. sampler = TPESampler(n_ei_candidates=13, seed=0) attrs = MockSystemAttr() with patch.object(study._storage, "get_all_trials", return_value=past_trials), patch.object( study._storage, "set_trial_system_attr", side_effect=attrs.set_trial_system_attr ), patch.object(study._storage, "get_trial", return_value=trial), patch( "optuna.trial.Trial.system_attrs", new_callable=PropertyMock ) as mock1, patch( "optuna.trial.FrozenTrial.system_attrs", new_callable=PropertyMock, ) as mock2: mock1.return_value = attrs.value mock2.return_value = attrs.value assert sampler.sample_independent(study, trial, "param-a", dist) != suggestion sampler = TPESampler(gamma=lambda _: 1, seed=0) attrs = MockSystemAttr() with patch.object(study._storage, "get_all_trials", return_value=past_trials), patch.object( study._storage, "set_trial_system_attr", side_effect=attrs.set_trial_system_attr ), patch.object(study._storage, "get_trial", return_value=trial), patch( "optuna.trial.Trial.system_attrs", new_callable=PropertyMock ) as mock1, patch( "optuna.trial.FrozenTrial.system_attrs", new_callable=PropertyMock, ) as mock2: mock1.return_value = attrs.value mock2.return_value = attrs.value assert sampler.sample_independent(study, trial, "param-a", dist) != suggestion sampler = TPESampler(weights=lambda n: np.zeros(n), seed=0) attrs = MockSystemAttr() with patch.object(study._storage, "get_all_trials", return_value=past_trials), patch.object( study._storage, "set_trial_system_attr", side_effect=attrs.set_trial_system_attr ), patch.object(study._storage, "get_trial", return_value=trial), patch( "optuna.trial.Trial.system_attrs", new_callable=PropertyMock ) as mock1, patch( "optuna.trial.FrozenTrial.system_attrs", new_callable=PropertyMock, ) as mock2: mock1.return_value = attrs.value mock2.return_value = attrs.value assert sampler.sample_independent(study, trial, "param-a", dist) != suggestion def test_multi_objective_sample_independent_uniform_distributions() -> None: # Prepare sample from uniform distribution for cheking other distributions. study = optuna.create_study(directions=["minimize", "maximize"]) random.seed(128) past_trials = [frozen_trial_factory(i, [random.random(), random.random()]) for i in range(16)] uni_dist = optuna.distributions.UniformDistribution(1.0, 100.0) trial = frozen_trial_factory(16, [0, 0]) sampler = TPESampler(seed=0) attrs = MockSystemAttr() with patch.object(study._storage, "get_all_trials", return_value=past_trials), patch.object( study._storage, "set_trial_system_attr", side_effect=attrs.set_trial_system_attr ), patch.object(study._storage, "get_trial", return_value=trial), patch( "optuna.trial.Trial.system_attrs", new_callable=PropertyMock ) as mock1, patch( "optuna.trial.FrozenTrial.system_attrs", new_callable=PropertyMock, ) as mock2: mock1.return_value = attrs.value mock2.return_value = attrs.value uniform_suggestion = sampler.sample_independent(study, trial, "param-a", uni_dist) assert 1.0 <= uniform_suggestion < 100.0 def test_multi_objective_sample_independent_log_uniform_distributions() -> None: """Prepare sample from uniform distribution for cheking other distributions.""" study = optuna.create_study(directions=["minimize", "maximize"]) random.seed(128) uni_dist = optuna.distributions.UniformDistribution(1.0, 100.0) past_trials = [frozen_trial_factory(i, [random.random(), random.random()]) for i in range(16)] trial = frozen_trial_factory(16, [0, 0]) sampler = TPESampler(seed=0) attrs = MockSystemAttr() with patch.object(study._storage, "get_all_trials", return_value=past_trials), patch.object( study._storage, "set_trial_system_attr", side_effect=attrs.set_trial_system_attr ), patch.object(study._storage, "get_trial", return_value=trial), patch( "optuna.trial.Trial.system_attrs", new_callable=PropertyMock ) as mock1, patch( "optuna.trial.FrozenTrial.system_attrs", new_callable=PropertyMock, ) as mock2: mock1.return_value = attrs.value mock2.return_value = attrs.value uniform_suggestion = sampler.sample_independent(study, trial, "param-a", uni_dist) # Test sample from log-uniform is different from uniform. log_dist = optuna.distributions.LogUniformDistribution(1.0, 100.0) past_trials = [ frozen_trial_factory(i, [random.random(), random.random()], log_dist) for i in range(16) ] trial = frozen_trial_factory(16, [0, 0]) sampler = TPESampler(seed=0) attrs = MockSystemAttr() with patch.object(study._storage, "get_all_trials", return_value=past_trials), patch.object( study._storage, "set_trial_system_attr", side_effect=attrs.set_trial_system_attr ), patch.object(study._storage, "get_trial", return_value=trial), patch( "optuna.trial.Trial.system_attrs", new_callable=PropertyMock ) as mock1, patch( "optuna.trial.FrozenTrial.system_attrs", new_callable=PropertyMock, ) as mock2: mock1.return_value = attrs.value mock2.return_value = attrs.value loguniform_suggestion = sampler.sample_independent(study, trial, "param-a", log_dist) assert 1.0 <= loguniform_suggestion < 100.0 assert uniform_suggestion != loguniform_suggestion def test_multi_objective_sample_independent_disrete_uniform_distributions() -> None: """Test samples from discrete have expected intervals.""" study = optuna.create_study(directions=["minimize", "maximize"]) random.seed(128) disc_dist = optuna.distributions.DiscreteUniformDistribution(1.0, 100.0, 0.1) def value_fn(idx: int) -> float: return int(random.random() * 1000) * 0.1 past_trials = [ frozen_trial_factory( i, [random.random(), random.random()], dist=disc_dist, value_fn=value_fn ) for i in range(16) ] trial = frozen_trial_factory(16, [0, 0]) sampler = TPESampler(seed=0) attrs = MockSystemAttr() with patch.object(study._storage, "get_all_trials", return_value=past_trials), patch.object( study._storage, "set_trial_system_attr", side_effect=attrs.set_trial_system_attr ), patch.object(study._storage, "get_trial", return_value=trial), patch( "optuna.trial.Trial.system_attrs", new_callable=PropertyMock ) as mock1, patch( "optuna.trial.FrozenTrial.system_attrs", new_callable=PropertyMock, ) as mock2: mock1.return_value = attrs.value mock2.return_value = attrs.value discrete_uniform_suggestion = sampler.sample_independent( study, trial, "param-a", disc_dist ) assert 1.0 <= discrete_uniform_suggestion <= 100.0 assert abs(int(discrete_uniform_suggestion * 10) - discrete_uniform_suggestion * 10) < 1e-3 def test_multi_objective_sample_independent_categorical_distributions() -> None: """Test samples are drawn from the specified category.""" study = optuna.create_study(directions=["minimize", "maximize"]) random.seed(128) categories = [i * 0.3 + 1.0 for i in range(330)] def cat_value_fn(idx: int) -> float: return categories[random.randint(0, len(categories) - 1)] cat_dist = optuna.distributions.CategoricalDistribution(categories) past_trials = [ frozen_trial_factory( i, [random.random(), random.random()], dist=cat_dist, value_fn=cat_value_fn ) for i in range(16) ] trial = frozen_trial_factory(16, [0, 0]) sampler = TPESampler(seed=0) attrs = MockSystemAttr() with patch.object(study._storage, "get_all_trials", return_value=past_trials), patch.object( study._storage, "set_trial_system_attr", side_effect=attrs.set_trial_system_attr ), patch.object(study._storage, "get_trial", return_value=trial), patch( "optuna.trial.Trial.system_attrs", new_callable=PropertyMock ) as mock1, patch( "optuna.trial.FrozenTrial.system_attrs", new_callable=PropertyMock, ) as mock2: mock1.return_value = attrs.value mock2.return_value = attrs.value categorical_suggestion = sampler.sample_independent(study, trial, "param-a", cat_dist) assert categorical_suggestion in categories def test_multi_objective_sample_int_uniform_distributions() -> None: """Test sampling from int distribution returns integer.""" study = optuna.create_study(directions=["minimize", "maximize"]) random.seed(128) def int_value_fn(idx: int) -> float: return random.randint(0, 100) int_dist = optuna.distributions.IntUniformDistribution(1, 100) past_trials = [ frozen_trial_factory( i, [random.random(), random.random()], dist=int_dist, value_fn=int_value_fn ) for i in range(16) ] trial = frozen_trial_factory(16, [0, 0]) sampler = TPESampler(seed=0) attrs = MockSystemAttr() with patch.object(study._storage, "get_all_trials", return_value=past_trials), patch.object( study._storage, "set_trial_system_attr", side_effect=attrs.set_trial_system_attr ), patch.object(study._storage, "get_trial", return_value=trial), patch( "optuna.trial.Trial.system_attrs", new_callable=PropertyMock ) as mock1, patch( "optuna.trial.FrozenTrial.system_attrs", new_callable=PropertyMock, ) as mock2: mock1.return_value = attrs.value mock2.return_value = attrs.value int_suggestion = sampler.sample_independent(study, trial, "param-a", int_dist) assert 1 <= int_suggestion <= 100 assert isinstance(int_suggestion, int) @pytest.mark.parametrize( "state", [ (optuna.trial.TrialState.FAIL,), (optuna.trial.TrialState.PRUNED,), (optuna.trial.TrialState.RUNNING,), (optuna.trial.TrialState.WAITING,), ], ) def test_multi_objective_sample_independent_handle_unsuccessful_states( state: optuna.trial.TrialState, ) -> None: study = optuna.create_study(directions=["minimize", "maximize"]) dist = optuna.distributions.UniformDistribution(1.0, 100.0) random.seed(128) # Prepare sampling result for later tests. past_trials = [frozen_trial_factory(i, [random.random(), random.random()]) for i in range(32)] trial = frozen_trial_factory(32, [0, 0]) sampler = TPESampler(seed=0) attrs = MockSystemAttr() with patch.object(study._storage, "get_all_trials", return_value=past_trials), patch.object( study._storage, "set_trial_system_attr", side_effect=attrs.set_trial_system_attr ), patch.object(study._storage, "get_trial", return_value=trial), patch( "optuna.trial.Trial.system_attrs", new_callable=PropertyMock ) as mock1, patch( "optuna.trial.FrozenTrial.system_attrs", new_callable=PropertyMock, ) as mock2: mock1.return_value = attrs.value mock2.return_value = attrs.value all_success_suggestion = sampler.sample_independent(study, trial, "param-a", dist) # Test unsuccessful trials are handled differently. state_fn = build_state_fn(state) past_trials = [ frozen_trial_factory(i, [random.random(), random.random()], state_fn=state_fn) for i in range(32) ] trial = frozen_trial_factory(32, [0, 0]) sampler = TPESampler(seed=0) attrs = MockSystemAttr() with patch.object(study._storage, "get_all_trials", return_value=past_trials), patch.object( study._storage, "set_trial_system_attr", side_effect=attrs.set_trial_system_attr ), patch.object(study._storage, "get_trial", return_value=trial), patch( "optuna.trial.Trial.system_attrs", new_callable=PropertyMock ) as mock1, patch( "optuna.trial.FrozenTrial.system_attrs", new_callable=PropertyMock, ) as mock2: mock1.return_value = attrs.value mock2.return_value = attrs.value partial_unsuccessful_suggestion = sampler.sample_independent(study, trial, "param-a", dist) assert partial_unsuccessful_suggestion != all_success_suggestion def test_multi_objective_sample_independent_ignored_states() -> None: """Tests FAIL, RUNNING, and WAITING states are equally.""" study = optuna.create_study(directions=["minimize", "maximize"]) dist = optuna.distributions.UniformDistribution(1.0, 100.0) suggestions = [] for state in [ optuna.trial.TrialState.FAIL, optuna.trial.TrialState.RUNNING, optuna.trial.TrialState.WAITING, ]: random.seed(128) state_fn = build_state_fn(state) past_trials = [ frozen_trial_factory(i, [random.random(), random.random()], state_fn=state_fn) for i in range(32) ] trial = frozen_trial_factory(32, [0, 0]) sampler = TPESampler(seed=0) attrs = MockSystemAttr() with patch.object(study._storage, "get_all_trials", return_value=past_trials), patch.object( study._storage, "set_trial_system_attr", side_effect=attrs.set_trial_system_attr ), patch.object(study._storage, "get_trial", return_value=trial), patch( "optuna.trial.Trial.system_attrs", new_callable=PropertyMock ) as mock1, patch( "optuna.trial.FrozenTrial.system_attrs", new_callable=PropertyMock, ) as mock2: mock1.return_value = attrs.value mock2.return_value = attrs.value suggestions.append(sampler.sample_independent(study, trial, "param-a", dist)) assert len(set(suggestions)) == 1 def test_multi_objective_get_observation_pairs() -> None: def objective(trial: optuna.trial.Trial) -> Tuple[float, float]: trial.suggest_int("x", 5, 5) return 5.0, 5.0 sampler = TPESampler(seed=0) study = optuna.create_study(directions=["minimize", "maximize"], sampler=sampler) study.optimize(objective, n_trials=5) assert _tpe.sampler._get_observation_pairs(study, ["x"], False) == ( {"x": [5.0, 5.0, 5.0, 5.0, 5.0]}, [(-float("inf"), [5.0, -5.0]) for _ in range(5)], ) assert _tpe.sampler._get_observation_pairs(study, ["y"], False) == ( {"y": [None, None, None, None, None]}, [(-float("inf"), [5.0, -5.0]) for _ in range(5)], ) assert _tpe.sampler._get_observation_pairs(study, ["x"], True) == ( {"x": [5.0, 5.0, 5.0, 5.0, 5.0]}, [(-float("inf"), [5.0, -5.0]) for _ in range(5)], ) assert _tpe.sampler._get_observation_pairs(study, ["y"], True) == ({"y": []}, []) def test_calculate_nondomination_rank() -> None: # Single objective test_case = np.asarray([[10], [20], [20], [30]]) ranks = list(_tpe.sampler._calculate_nondomination_rank(test_case)) assert ranks == [0, 1, 1, 2] # Two objectives test_case = np.asarray([[10, 30], [10, 10], [20, 20], [30, 10], [15, 15]]) ranks = list(_tpe.sampler._calculate_nondomination_rank(test_case)) assert ranks == [1, 0, 2, 1, 1] # Three objectives test_case = np.asarray([[5, 5, 4], [5, 5, 5], [9, 9, 0], [5, 7, 5], [0, 0, 9], [0, 9, 9]]) ranks = list(_tpe.sampler._calculate_nondomination_rank(test_case)) assert ranks == [0, 1, 0, 2, 0, 1] def test_calculate_weights_below_for_multi_objective() -> None: # Two samples. weights_below = _tpe.sampler._calculate_weights_below_for_multi_objective( {"x": [1.0, 2.0, 3.0]}, [(0, [0.2, 0.5]), (0, [0.9, 0.4]), (0, [1, 1])], np.array([0, 1]) ) assert len(weights_below) == 2 assert weights_below[0] > weights_below[1] assert sum(weights_below) > 0 # Two equally contributed samples. weights_below = _tpe.sampler._calculate_weights_below_for_multi_objective( {"x": [1.0, 2.0, 3.0]}, [(0, [0.2, 0.8]), (0, [0.8, 0.2]), (0, [1, 1])], np.array([0, 1]) ) assert len(weights_below) == 2 assert weights_below[0] == weights_below[1] assert sum(weights_below) > 0 # Duplicated samples. weights_below = _tpe.sampler._calculate_weights_below_for_multi_objective( {"x": [1.0, 2.0, 3.0]}, [(0, [0.2, 0.8]), (0, [0.2, 0.8]), (0, [1, 1])], np.array([0, 1]) ) assert len(weights_below) == 2 assert weights_below[0] == weights_below[1] assert sum(weights_below) > 0 # Three samples. weights_below = _tpe.sampler._calculate_weights_below_for_multi_objective( {"x": [1.0, 2.0, 3.0, 4.0]}, [(0, [0.3, 0.3]), (0, [0.2, 0.8]), (0, [0.8, 0.2]), (0, [1, 1])], np.array([0, 1, 2]), ) assert len(weights_below) == 3 assert weights_below[0] > weights_below[1] assert weights_below[0] > weights_below[2] assert weights_below[1] == weights_below[2] assert sum(weights_below) > 0 def test_solve_hssp() -> None: random.seed(128) # Two dimensions for i in range(8): subset_size = int(random.random() * i) + 1 test_case = np.asarray([[random.random(), random.random()] for _ in range(8)]) r = 1.1 * np.max(test_case, axis=0) truth = 0.0 for subset in itertools.permutations(test_case, subset_size): truth = max(truth, _tpe.sampler._compute_hypervolume(np.asarray(subset), r)) indices = _tpe.sampler._solve_hssp(test_case, np.arange(len(test_case)), subset_size, r) approx = _tpe.sampler._compute_hypervolume(test_case[indices], r) assert approx / truth > 0.6321 # 1 - 1/e # Three dimensions for i in range(8): subset_size = int(random.random() * i) + 1 test_case = np.asarray( [[random.random(), random.random(), random.random()] for _ in range(8)] ) r = 1.1 * np.max(test_case, axis=0) truth = 0 for subset in itertools.permutations(test_case, subset_size): truth = max(truth, _tpe.sampler._compute_hypervolume(np.asarray(subset), r)) indices = _tpe.sampler._solve_hssp(test_case, np.arange(len(test_case)), subset_size, r) approx = _tpe.sampler._compute_hypervolume(test_case[indices], r) assert approx / truth > 0.6321 # 1 - 1/e def frozen_trial_factory( number: int, values: List[float], dist: optuna.distributions.BaseDistribution = optuna.distributions.UniformDistribution( 1.0, 100.0 ), value_fn: Optional[Callable[[int], Union[int, float]]] = None, state_fn: Callable[ [int], optuna.trial.TrialState ] = lambda _: optuna.trial.TrialState.COMPLETE, ) -> optuna.trial.FrozenTrial: if value_fn is None: value = random.random() * 99.0 + 1.0 else: value = value_fn(number) trial = optuna.trial.FrozenTrial( number=number, trial_id=number, state=optuna.trial.TrialState.COMPLETE, value=None, datetime_start=None, datetime_complete=None, params={"param-a": value}, distributions={"param-a": dist}, user_attrs={}, system_attrs={}, intermediate_values={}, values=values, ) return trial def build_state_fn(state: optuna.trial.TrialState) -> Callable[[int], optuna.trial.TrialState]: def state_fn(idx: int) -> optuna.trial.TrialState: return [optuna.trial.TrialState.COMPLETE, state][idx % 2] return state_fn
[ "optuna.distributions.DiscreteUniformDistribution", "optuna.samplers._tpe.sampler._get_observation_pairs", "numpy.array", "optuna.distributions.CategoricalDistribution", "optuna.distributions.UniformDistribution", "unittest.mock.patch", "numpy.asarray", "numpy.max", "optuna.samplers._tpe.sampler._co...
[((18731, 18915), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""state"""', '[(optuna.trial.TrialState.FAIL,), (optuna.trial.TrialState.PRUNED,), (\n optuna.trial.TrialState.RUNNING,), (optuna.trial.TrialState.WAITING,)]'], {}), "('state', [(optuna.trial.TrialState.FAIL,), (optuna.\n trial.TrialState.PRUNED,), (optuna.trial.TrialState.RUNNING,), (optuna.\n trial.TrialState.WAITING,)])\n", (18754, 18915), False, 'import pytest\n'), ((669, 725), 'optuna.create_study', 'optuna.create_study', ([], {'directions': "['minimize', 'maximize']"}), "(directions=['minimize', 'maximize'])\n", (688, 725), False, 'import optuna\n'), ((737, 789), 'optuna.distributions.UniformDistribution', 'optuna.distributions.UniformDistribution', (['(1.0)', '(100.0)'], {}), '(1.0, 100.0)\n', (777, 789), False, 'import optuna\n'), ((795, 811), 'random.seed', 'random.seed', (['(128)'], {}), '(128)\n', (806, 811), False, 'import random\n'), ((1023, 1041), 'optuna.samplers.TPESampler', 'TPESampler', ([], {'seed': '(0)'}), '(seed=0)\n', (1033, 1041), False, 'from optuna.samplers import TPESampler\n'), ((1702, 1720), 'optuna.samplers.TPESampler', 'TPESampler', ([], {'seed': '(0)'}), '(seed=0)\n', (1712, 1720), False, 'from optuna.samplers import TPESampler\n'), ((2389, 2407), 'optuna.samplers.TPESampler', 'TPESampler', ([], {'seed': '(1)'}), '(seed=1)\n', (2399, 2407), False, 'from optuna.samplers import TPESampler\n'), ((3136, 3192), 'optuna.create_study', 'optuna.create_study', ([], {'directions': "['minimize', 'maximize']"}), "(directions=['minimize', 'maximize'])\n", (3155, 3192), False, 'import optuna\n'), ((3204, 3256), 'optuna.distributions.UniformDistribution', 'optuna.distributions.UniformDistribution', (['(1.0)', '(100.0)'], {}), '(1.0, 100.0)\n', (3244, 3256), False, 'import optuna\n'), ((3262, 3278), 'random.seed', 'random.seed', (['(128)'], {}), '(128)\n', (3273, 3278), False, 'import random\n'), ((3491, 3509), 'optuna.samplers.TPESampler', 'TPESampler', ([], {'seed': '(0)'}), '(seed=0)\n', (3501, 3509), False, 'from optuna.samplers import TPESampler\n'), ((4170, 4210), 'optuna.samplers.TPESampler', 'TPESampler', ([], {'consider_prior': '(False)', 'seed': '(0)'}), '(consider_prior=False, seed=0)\n', (4180, 4210), False, 'from optuna.samplers import TPESampler\n'), ((4879, 4915), 'optuna.samplers.TPESampler', 'TPESampler', ([], {'prior_weight': '(0.5)', 'seed': '(0)'}), '(prior_weight=0.5, seed=0)\n', (4889, 4915), False, 'from optuna.samplers import TPESampler\n'), ((5654, 5710), 'optuna.create_study', 'optuna.create_study', ([], {'directions': "['minimize', 'maximize']"}), "(directions=['minimize', 'maximize'])\n", (5673, 5710), False, 'import optuna\n'), ((5722, 5774), 'optuna.distributions.UniformDistribution', 'optuna.distributions.UniformDistribution', (['(1.0)', '(100.0)'], {}), '(1.0, 100.0)\n', (5762, 5774), False, 'import optuna\n'), ((5779, 5795), 'random.seed', 'random.seed', (['(128)'], {}), '(128)\n', (5790, 5795), False, 'import random\n'), ((5955, 5994), 'optuna.samplers.TPESampler', 'TPESampler', ([], {'n_startup_trials': '(16)', 'seed': '(0)'}), '(n_startup_trials=16, seed=0)\n', (5965, 5994), False, 'from optuna.samplers import TPESampler\n'), ((6849, 6888), 'optuna.samplers.TPESampler', 'TPESampler', ([], {'n_startup_trials': '(16)', 'seed': '(0)'}), '(n_startup_trials=16, seed=0)\n', (6859, 6888), False, 'from optuna.samplers import TPESampler\n'), ((7779, 7835), 'optuna.create_study', 'optuna.create_study', ([], {'directions': "['minimize', 'maximize']"}), "(directions=['minimize', 'maximize'])\n", (7798, 7835), False, 'import optuna\n'), ((7847, 7899), 'optuna.distributions.UniformDistribution', 'optuna.distributions.UniformDistribution', (['(1.0)', '(100.0)'], {}), '(1.0, 100.0)\n', (7887, 7899), False, 'import optuna\n'), ((7904, 7920), 'random.seed', 'random.seed', (['(128)'], {}), '(128)\n', (7915, 7920), False, 'import random\n'), ((8133, 8151), 'optuna.samplers.TPESampler', 'TPESampler', ([], {'seed': '(0)'}), '(seed=0)\n', (8143, 8151), False, 'from optuna.samplers import TPESampler\n'), ((8841, 8879), 'optuna.samplers.TPESampler', 'TPESampler', ([], {'n_ei_candidates': '(13)', 'seed': '(0)'}), '(n_ei_candidates=13, seed=0)\n', (8851, 8879), False, 'from optuna.samplers import TPESampler\n'), ((9548, 9585), 'optuna.samplers.TPESampler', 'TPESampler', ([], {'gamma': '(lambda _: 1)', 'seed': '(0)'}), '(gamma=lambda _: 1, seed=0)\n', (9558, 9585), False, 'from optuna.samplers import TPESampler\n'), ((11128, 11184), 'optuna.create_study', 'optuna.create_study', ([], {'directions': "['minimize', 'maximize']"}), "(directions=['minimize', 'maximize'])\n", (11147, 11184), False, 'import optuna\n'), ((11189, 11205), 'random.seed', 'random.seed', (['(128)'], {}), '(128)\n', (11200, 11205), False, 'import random\n'), ((11321, 11373), 'optuna.distributions.UniformDistribution', 'optuna.distributions.UniformDistribution', (['(1.0)', '(100.0)'], {}), '(1.0, 100.0)\n', (11361, 11373), False, 'import optuna\n'), ((11433, 11451), 'optuna.samplers.TPESampler', 'TPESampler', ([], {'seed': '(0)'}), '(seed=0)\n', (11443, 11451), False, 'from optuna.samplers import TPESampler\n'), ((12334, 12390), 'optuna.create_study', 'optuna.create_study', ([], {'directions': "['minimize', 'maximize']"}), "(directions=['minimize', 'maximize'])\n", (12353, 12390), False, 'import optuna\n'), ((12395, 12411), 'random.seed', 'random.seed', (['(128)'], {}), '(128)\n', (12406, 12411), False, 'import random\n'), ((12428, 12480), 'optuna.distributions.UniformDistribution', 'optuna.distributions.UniformDistribution', (['(1.0)', '(100.0)'], {}), '(1.0, 100.0)\n', (12468, 12480), False, 'import optuna\n'), ((12639, 12657), 'optuna.samplers.TPESampler', 'TPESampler', ([], {'seed': '(0)'}), '(seed=0)\n', (12649, 12657), False, 'from optuna.samplers import TPESampler\n'), ((13393, 13448), 'optuna.distributions.LogUniformDistribution', 'optuna.distributions.LogUniformDistribution', (['(1.0)', '(100.0)'], {}), '(1.0, 100.0)\n', (13436, 13448), False, 'import optuna\n'), ((13631, 13649), 'optuna.samplers.TPESampler', 'TPESampler', ([], {'seed': '(0)'}), '(seed=0)\n', (13641, 13649), False, 'from optuna.samplers import TPESampler\n'), ((14575, 14631), 'optuna.create_study', 'optuna.create_study', ([], {'directions': "['minimize', 'maximize']"}), "(directions=['minimize', 'maximize'])\n", (14594, 14631), False, 'import optuna\n'), ((14636, 14652), 'random.seed', 'random.seed', (['(128)'], {}), '(128)\n', (14647, 14652), False, 'import random\n'), ((14670, 14735), 'optuna.distributions.DiscreteUniformDistribution', 'optuna.distributions.DiscreteUniformDistribution', (['(1.0)', '(100.0)', '(0.1)'], {}), '(1.0, 100.0, 0.1)\n', (14718, 14735), False, 'import optuna\n'), ((15062, 15080), 'optuna.samplers.TPESampler', 'TPESampler', ([], {'seed': '(0)'}), '(seed=0)\n', (15072, 15080), False, 'from optuna.samplers import TPESampler\n'), ((16079, 16135), 'optuna.create_study', 'optuna.create_study', ([], {'directions': "['minimize', 'maximize']"}), "(directions=['minimize', 'maximize'])\n", (16098, 16135), False, 'import optuna\n'), ((16140, 16156), 'random.seed', 'random.seed', (['(128)'], {}), '(128)\n', (16151, 16156), False, 'import random\n'), ((16335, 16391), 'optuna.distributions.CategoricalDistribution', 'optuna.distributions.CategoricalDistribution', (['categories'], {}), '(categories)\n', (16379, 16391), False, 'import optuna\n'), ((16633, 16651), 'optuna.samplers.TPESampler', 'TPESampler', ([], {'seed': '(0)'}), '(seed=0)\n', (16643, 16651), False, 'from optuna.samplers import TPESampler\n'), ((17508, 17564), 'optuna.create_study', 'optuna.create_study', ([], {'directions': "['minimize', 'maximize']"}), "(directions=['minimize', 'maximize'])\n", (17527, 17564), False, 'import optuna\n'), ((17569, 17585), 'random.seed', 'random.seed', (['(128)'], {}), '(128)\n', (17580, 17585), False, 'import random\n'), ((17682, 17733), 'optuna.distributions.IntUniformDistribution', 'optuna.distributions.IntUniformDistribution', (['(1)', '(100)'], {}), '(1, 100)\n', (17725, 17733), False, 'import optuna\n'), ((17975, 17993), 'optuna.samplers.TPESampler', 'TPESampler', ([], {'seed': '(0)'}), '(seed=0)\n', (17985, 17993), False, 'from optuna.samplers import TPESampler\n'), ((19087, 19143), 'optuna.create_study', 'optuna.create_study', ([], {'directions': "['minimize', 'maximize']"}), "(directions=['minimize', 'maximize'])\n", (19106, 19143), False, 'import optuna\n'), ((19155, 19207), 'optuna.distributions.UniformDistribution', 'optuna.distributions.UniformDistribution', (['(1.0)', '(100.0)'], {}), '(1.0, 100.0)\n', (19195, 19207), False, 'import optuna\n'), ((19212, 19228), 'random.seed', 'random.seed', (['(128)'], {}), '(128)\n', (19223, 19228), False, 'import random\n'), ((19436, 19454), 'optuna.samplers.TPESampler', 'TPESampler', ([], {'seed': '(0)'}), '(seed=0)\n', (19446, 19454), False, 'from optuna.samplers import TPESampler\n'), ((20406, 20424), 'optuna.samplers.TPESampler', 'TPESampler', ([], {'seed': '(0)'}), '(seed=0)\n', (20416, 20424), False, 'from optuna.samplers import TPESampler\n'), ((21307, 21363), 'optuna.create_study', 'optuna.create_study', ([], {'directions': "['minimize', 'maximize']"}), "(directions=['minimize', 'maximize'])\n", (21326, 21363), False, 'import optuna\n'), ((21375, 21427), 'optuna.distributions.UniformDistribution', 'optuna.distributions.UniformDistribution', (['(1.0)', '(100.0)'], {}), '(1.0, 100.0)\n', (21415, 21427), False, 'import optuna\n'), ((22800, 22818), 'optuna.samplers.TPESampler', 'TPESampler', ([], {'seed': '(0)'}), '(seed=0)\n', (22810, 22818), False, 'from optuna.samplers import TPESampler\n'), ((22831, 22904), 'optuna.create_study', 'optuna.create_study', ([], {'directions': "['minimize', 'maximize']", 'sampler': 'sampler'}), "(directions=['minimize', 'maximize'], sampler=sampler)\n", (22850, 22904), False, 'import optuna\n'), ((23665, 23701), 'numpy.asarray', 'np.asarray', (['[[10], [20], [20], [30]]'], {}), '([[10], [20], [20], [30]])\n', (23675, 23701), True, 'import numpy as np\n'), ((23845, 23907), 'numpy.asarray', 'np.asarray', (['[[10, 30], [10, 10], [20, 20], [30, 10], [15, 15]]'], {}), '([[10, 30], [10, 10], [20, 20], [30, 10], [15, 15]])\n', (23855, 23907), True, 'import numpy as np\n'), ((24056, 24134), 'numpy.asarray', 'np.asarray', (['[[5, 5, 4], [5, 5, 5], [9, 9, 0], [5, 7, 5], [0, 0, 9], [0, 9, 9]]'], {}), '([[5, 5, 4], [5, 5, 5], [9, 9, 0], [5, 7, 5], [0, 0, 9], [0, 9, 9]])\n', (24066, 24134), True, 'import numpy as np\n'), ((25792, 25808), 'random.seed', 'random.seed', (['(128)'], {}), '(128)\n', (25803, 25808), False, 'import random\n'), ((27222, 27274), 'optuna.distributions.UniformDistribution', 'optuna.distributions.UniformDistribution', (['(1.0)', '(100.0)'], {}), '(1.0, 100.0)\n', (27262, 27274), False, 'import optuna\n'), ((27629, 27932), 'optuna.trial.FrozenTrial', 'optuna.trial.FrozenTrial', ([], {'number': 'number', 'trial_id': 'number', 'state': 'optuna.trial.TrialState.COMPLETE', 'value': 'None', 'datetime_start': 'None', 'datetime_complete': 'None', 'params': "{'param-a': value}", 'distributions': "{'param-a': dist}", 'user_attrs': '{}', 'system_attrs': '{}', 'intermediate_values': '{}', 'values': 'values'}), "(number=number, trial_id=number, state=optuna.trial\n .TrialState.COMPLETE, value=None, datetime_start=None,\n datetime_complete=None, params={'param-a': value}, distributions={\n 'param-a': dist}, user_attrs={}, system_attrs={}, intermediate_values={\n }, values=values)\n", (27653, 27932), False, 'import optuna\n'), ((1080, 1152), 'unittest.mock.patch.object', 'patch.object', (['study._storage', '"""get_all_trials"""'], {'return_value': 'past_trials'}), "(study._storage, 'get_all_trials', return_value=past_trials)\n", (1092, 1152), False, 'from unittest.mock import patch\n'), ((1154, 1253), 'unittest.mock.patch.object', 'patch.object', (['study._storage', '"""set_trial_system_attr"""'], {'side_effect': 'attrs.set_trial_system_attr'}), "(study._storage, 'set_trial_system_attr', side_effect=attrs.\n set_trial_system_attr)\n", (1166, 1253), False, 'from unittest.mock import patch\n'), ((1264, 1325), 'unittest.mock.patch.object', 'patch.object', (['study._storage', '"""get_trial"""'], {'return_value': 'trial'}), "(study._storage, 'get_trial', return_value=trial)\n", (1276, 1325), False, 'from unittest.mock import patch\n'), ((1327, 1394), 'unittest.mock.patch', 'patch', (['"""optuna.trial.Trial.system_attrs"""'], {'new_callable': 'PropertyMock'}), "('optuna.trial.Trial.system_attrs', new_callable=PropertyMock)\n", (1332, 1394), False, 'from unittest.mock import patch\n'), ((1419, 1492), 'unittest.mock.patch', 'patch', (['"""optuna.trial.FrozenTrial.system_attrs"""'], {'new_callable': 'PropertyMock'}), "('optuna.trial.FrozenTrial.system_attrs', new_callable=PropertyMock)\n", (1424, 1492), False, 'from unittest.mock import patch\n'), ((1759, 1831), 'unittest.mock.patch.object', 'patch.object', (['study._storage', '"""get_all_trials"""'], {'return_value': 'past_trials'}), "(study._storage, 'get_all_trials', return_value=past_trials)\n", (1771, 1831), False, 'from unittest.mock import patch\n'), ((1833, 1932), 'unittest.mock.patch.object', 'patch.object', (['study._storage', '"""set_trial_system_attr"""'], {'side_effect': 'attrs.set_trial_system_attr'}), "(study._storage, 'set_trial_system_attr', side_effect=attrs.\n set_trial_system_attr)\n", (1845, 1932), False, 'from unittest.mock import patch\n'), ((1943, 2004), 'unittest.mock.patch.object', 'patch.object', (['study._storage', '"""get_trial"""'], {'return_value': 'trial'}), "(study._storage, 'get_trial', return_value=trial)\n", (1955, 2004), False, 'from unittest.mock import patch\n'), ((2006, 2073), 'unittest.mock.patch', 'patch', (['"""optuna.trial.Trial.system_attrs"""'], {'new_callable': 'PropertyMock'}), "('optuna.trial.Trial.system_attrs', new_callable=PropertyMock)\n", (2011, 2073), False, 'from unittest.mock import patch\n'), ((2098, 2171), 'unittest.mock.patch', 'patch', (['"""optuna.trial.FrozenTrial.system_attrs"""'], {'new_callable': 'PropertyMock'}), "('optuna.trial.FrozenTrial.system_attrs', new_callable=PropertyMock)\n", (2103, 2171), False, 'from unittest.mock import patch\n'), ((2446, 2518), 'unittest.mock.patch.object', 'patch.object', (['study._storage', '"""get_all_trials"""'], {'return_value': 'past_trials'}), "(study._storage, 'get_all_trials', return_value=past_trials)\n", (2458, 2518), False, 'from unittest.mock import patch\n'), ((2520, 2619), 'unittest.mock.patch.object', 'patch.object', (['study._storage', '"""set_trial_system_attr"""'], {'side_effect': 'attrs.set_trial_system_attr'}), "(study._storage, 'set_trial_system_attr', side_effect=attrs.\n set_trial_system_attr)\n", (2532, 2619), False, 'from unittest.mock import patch\n'), ((2630, 2691), 'unittest.mock.patch.object', 'patch.object', (['study._storage', '"""get_trial"""'], {'return_value': 'trial'}), "(study._storage, 'get_trial', return_value=trial)\n", (2642, 2691), False, 'from unittest.mock import patch\n'), ((2693, 2760), 'unittest.mock.patch', 'patch', (['"""optuna.trial.Trial.system_attrs"""'], {'new_callable': 'PropertyMock'}), "('optuna.trial.Trial.system_attrs', new_callable=PropertyMock)\n", (2698, 2760), False, 'from unittest.mock import patch\n'), ((2785, 2858), 'unittest.mock.patch', 'patch', (['"""optuna.trial.FrozenTrial.system_attrs"""'], {'new_callable': 'PropertyMock'}), "('optuna.trial.FrozenTrial.system_attrs', new_callable=PropertyMock)\n", (2790, 2858), False, 'from unittest.mock import patch\n'), ((3548, 3620), 'unittest.mock.patch.object', 'patch.object', (['study._storage', '"""get_all_trials"""'], {'return_value': 'past_trials'}), "(study._storage, 'get_all_trials', return_value=past_trials)\n", (3560, 3620), False, 'from unittest.mock import patch\n'), ((3622, 3721), 'unittest.mock.patch.object', 'patch.object', (['study._storage', '"""set_trial_system_attr"""'], {'side_effect': 'attrs.set_trial_system_attr'}), "(study._storage, 'set_trial_system_attr', side_effect=attrs.\n set_trial_system_attr)\n", (3634, 3721), False, 'from unittest.mock import patch\n'), ((3732, 3793), 'unittest.mock.patch.object', 'patch.object', (['study._storage', '"""get_trial"""'], {'return_value': 'trial'}), "(study._storage, 'get_trial', return_value=trial)\n", (3744, 3793), False, 'from unittest.mock import patch\n'), ((3795, 3862), 'unittest.mock.patch', 'patch', (['"""optuna.trial.Trial.system_attrs"""'], {'new_callable': 'PropertyMock'}), "('optuna.trial.Trial.system_attrs', new_callable=PropertyMock)\n", (3800, 3862), False, 'from unittest.mock import patch\n'), ((3887, 3960), 'unittest.mock.patch', 'patch', (['"""optuna.trial.FrozenTrial.system_attrs"""'], {'new_callable': 'PropertyMock'}), "('optuna.trial.FrozenTrial.system_attrs', new_callable=PropertyMock)\n", (3892, 3960), False, 'from unittest.mock import patch\n'), ((4249, 4321), 'unittest.mock.patch.object', 'patch.object', (['study._storage', '"""get_all_trials"""'], {'return_value': 'past_trials'}), "(study._storage, 'get_all_trials', return_value=past_trials)\n", (4261, 4321), False, 'from unittest.mock import patch\n'), ((4323, 4422), 'unittest.mock.patch.object', 'patch.object', (['study._storage', '"""set_trial_system_attr"""'], {'side_effect': 'attrs.set_trial_system_attr'}), "(study._storage, 'set_trial_system_attr', side_effect=attrs.\n set_trial_system_attr)\n", (4335, 4422), False, 'from unittest.mock import patch\n'), ((4433, 4494), 'unittest.mock.patch.object', 'patch.object', (['study._storage', '"""get_trial"""'], {'return_value': 'trial'}), "(study._storage, 'get_trial', return_value=trial)\n", (4445, 4494), False, 'from unittest.mock import patch\n'), ((4496, 4563), 'unittest.mock.patch', 'patch', (['"""optuna.trial.Trial.system_attrs"""'], {'new_callable': 'PropertyMock'}), "('optuna.trial.Trial.system_attrs', new_callable=PropertyMock)\n", (4501, 4563), False, 'from unittest.mock import patch\n'), ((4588, 4661), 'unittest.mock.patch', 'patch', (['"""optuna.trial.FrozenTrial.system_attrs"""'], {'new_callable': 'PropertyMock'}), "('optuna.trial.FrozenTrial.system_attrs', new_callable=PropertyMock)\n", (4593, 4661), False, 'from unittest.mock import patch\n'), ((4954, 5026), 'unittest.mock.patch.object', 'patch.object', (['study._storage', '"""get_all_trials"""'], {'return_value': 'past_trials'}), "(study._storage, 'get_all_trials', return_value=past_trials)\n", (4966, 5026), False, 'from unittest.mock import patch\n'), ((5028, 5127), 'unittest.mock.patch.object', 'patch.object', (['study._storage', '"""set_trial_system_attr"""'], {'side_effect': 'attrs.set_trial_system_attr'}), "(study._storage, 'set_trial_system_attr', side_effect=attrs.\n set_trial_system_attr)\n", (5040, 5127), False, 'from unittest.mock import patch\n'), ((5138, 5199), 'unittest.mock.patch.object', 'patch.object', (['study._storage', '"""get_trial"""'], {'return_value': 'trial'}), "(study._storage, 'get_trial', return_value=trial)\n", (5150, 5199), False, 'from unittest.mock import patch\n'), ((5201, 5268), 'unittest.mock.patch', 'patch', (['"""optuna.trial.Trial.system_attrs"""'], {'new_callable': 'PropertyMock'}), "('optuna.trial.Trial.system_attrs', new_callable=PropertyMock)\n", (5206, 5268), False, 'from unittest.mock import patch\n'), ((5293, 5366), 'unittest.mock.patch', 'patch', (['"""optuna.trial.FrozenTrial.system_attrs"""'], {'new_callable': 'PropertyMock'}), "('optuna.trial.FrozenTrial.system_attrs', new_callable=PropertyMock)\n", (5298, 5366), False, 'from unittest.mock import patch\n'), ((6033, 6110), 'unittest.mock.patch.object', 'patch.object', (['study._storage', '"""get_all_trials"""'], {'return_value': 'past_trials[:15]'}), "(study._storage, 'get_all_trials', return_value=past_trials[:15])\n", (6045, 6110), False, 'from unittest.mock import patch\n'), ((6126, 6225), 'unittest.mock.patch.object', 'patch.object', (['study._storage', '"""set_trial_system_attr"""'], {'side_effect': 'attrs.set_trial_system_attr'}), "(study._storage, 'set_trial_system_attr', side_effect=attrs.\n set_trial_system_attr)\n", (6138, 6225), False, 'from unittest.mock import patch\n'), ((6236, 6297), 'unittest.mock.patch.object', 'patch.object', (['study._storage', '"""get_trial"""'], {'return_value': 'trial'}), "(study._storage, 'get_trial', return_value=trial)\n", (6248, 6297), False, 'from unittest.mock import patch\n'), ((6313, 6380), 'unittest.mock.patch', 'patch', (['"""optuna.trial.Trial.system_attrs"""'], {'new_callable': 'PropertyMock'}), "('optuna.trial.Trial.system_attrs', new_callable=PropertyMock)\n", (6318, 6380), False, 'from unittest.mock import patch\n'), ((6405, 6478), 'unittest.mock.patch', 'patch', (['"""optuna.trial.FrozenTrial.system_attrs"""'], {'new_callable': 'PropertyMock'}), "('optuna.trial.FrozenTrial.system_attrs', new_callable=PropertyMock)\n", (6410, 6478), False, 'from unittest.mock import patch\n'), ((6512, 6599), 'unittest.mock.patch.object', 'patch.object', (['optuna.samplers.RandomSampler', '"""sample_independent"""'], {'return_value': '(1.0)'}), "(optuna.samplers.RandomSampler, 'sample_independent',\n return_value=1.0)\n", (6524, 6599), False, 'from unittest.mock import patch\n'), ((6927, 6999), 'unittest.mock.patch.object', 'patch.object', (['study._storage', '"""get_all_trials"""'], {'return_value': 'past_trials'}), "(study._storage, 'get_all_trials', return_value=past_trials)\n", (6939, 6999), False, 'from unittest.mock import patch\n'), ((7001, 7100), 'unittest.mock.patch.object', 'patch.object', (['study._storage', '"""set_trial_system_attr"""'], {'side_effect': 'attrs.set_trial_system_attr'}), "(study._storage, 'set_trial_system_attr', side_effect=attrs.\n set_trial_system_attr)\n", (7013, 7100), False, 'from unittest.mock import patch\n'), ((7111, 7172), 'unittest.mock.patch.object', 'patch.object', (['study._storage', '"""get_trial"""'], {'return_value': 'trial'}), "(study._storage, 'get_trial', return_value=trial)\n", (7123, 7172), False, 'from unittest.mock import patch\n'), ((7174, 7241), 'unittest.mock.patch', 'patch', (['"""optuna.trial.Trial.system_attrs"""'], {'new_callable': 'PropertyMock'}), "('optuna.trial.Trial.system_attrs', new_callable=PropertyMock)\n", (7179, 7241), False, 'from unittest.mock import patch\n'), ((7266, 7339), 'unittest.mock.patch', 'patch', (['"""optuna.trial.FrozenTrial.system_attrs"""'], {'new_callable': 'PropertyMock'}), "('optuna.trial.FrozenTrial.system_attrs', new_callable=PropertyMock)\n", (7271, 7339), False, 'from unittest.mock import patch\n'), ((7373, 7460), 'unittest.mock.patch.object', 'patch.object', (['optuna.samplers.RandomSampler', '"""sample_independent"""'], {'return_value': '(1.0)'}), "(optuna.samplers.RandomSampler, 'sample_independent',\n return_value=1.0)\n", (7385, 7460), False, 'from unittest.mock import patch\n'), ((8190, 8262), 'unittest.mock.patch.object', 'patch.object', (['study._storage', '"""get_all_trials"""'], {'return_value': 'past_trials'}), "(study._storage, 'get_all_trials', return_value=past_trials)\n", (8202, 8262), False, 'from unittest.mock import patch\n'), ((8264, 8363), 'unittest.mock.patch.object', 'patch.object', (['study._storage', '"""set_trial_system_attr"""'], {'side_effect': 'attrs.set_trial_system_attr'}), "(study._storage, 'set_trial_system_attr', side_effect=attrs.\n set_trial_system_attr)\n", (8276, 8363), False, 'from unittest.mock import patch\n'), ((8374, 8435), 'unittest.mock.patch.object', 'patch.object', (['study._storage', '"""get_trial"""'], {'return_value': 'trial'}), "(study._storage, 'get_trial', return_value=trial)\n", (8386, 8435), False, 'from unittest.mock import patch\n'), ((8437, 8504), 'unittest.mock.patch', 'patch', (['"""optuna.trial.Trial.system_attrs"""'], {'new_callable': 'PropertyMock'}), "('optuna.trial.Trial.system_attrs', new_callable=PropertyMock)\n", (8442, 8504), False, 'from unittest.mock import patch\n'), ((8529, 8602), 'unittest.mock.patch', 'patch', (['"""optuna.trial.FrozenTrial.system_attrs"""'], {'new_callable': 'PropertyMock'}), "('optuna.trial.FrozenTrial.system_attrs', new_callable=PropertyMock)\n", (8534, 8602), False, 'from unittest.mock import patch\n'), ((8918, 8990), 'unittest.mock.patch.object', 'patch.object', (['study._storage', '"""get_all_trials"""'], {'return_value': 'past_trials'}), "(study._storage, 'get_all_trials', return_value=past_trials)\n", (8930, 8990), False, 'from unittest.mock import patch\n'), ((8992, 9091), 'unittest.mock.patch.object', 'patch.object', (['study._storage', '"""set_trial_system_attr"""'], {'side_effect': 'attrs.set_trial_system_attr'}), "(study._storage, 'set_trial_system_attr', side_effect=attrs.\n set_trial_system_attr)\n", (9004, 9091), False, 'from unittest.mock import patch\n'), ((9102, 9163), 'unittest.mock.patch.object', 'patch.object', (['study._storage', '"""get_trial"""'], {'return_value': 'trial'}), "(study._storage, 'get_trial', return_value=trial)\n", (9114, 9163), False, 'from unittest.mock import patch\n'), ((9165, 9232), 'unittest.mock.patch', 'patch', (['"""optuna.trial.Trial.system_attrs"""'], {'new_callable': 'PropertyMock'}), "('optuna.trial.Trial.system_attrs', new_callable=PropertyMock)\n", (9170, 9232), False, 'from unittest.mock import patch\n'), ((9257, 9330), 'unittest.mock.patch', 'patch', (['"""optuna.trial.FrozenTrial.system_attrs"""'], {'new_callable': 'PropertyMock'}), "('optuna.trial.FrozenTrial.system_attrs', new_callable=PropertyMock)\n", (9262, 9330), False, 'from unittest.mock import patch\n'), ((9624, 9696), 'unittest.mock.patch.object', 'patch.object', (['study._storage', '"""get_all_trials"""'], {'return_value': 'past_trials'}), "(study._storage, 'get_all_trials', return_value=past_trials)\n", (9636, 9696), False, 'from unittest.mock import patch\n'), ((9698, 9797), 'unittest.mock.patch.object', 'patch.object', (['study._storage', '"""set_trial_system_attr"""'], {'side_effect': 'attrs.set_trial_system_attr'}), "(study._storage, 'set_trial_system_attr', side_effect=attrs.\n set_trial_system_attr)\n", (9710, 9797), False, 'from unittest.mock import patch\n'), ((9808, 9869), 'unittest.mock.patch.object', 'patch.object', (['study._storage', '"""get_trial"""'], {'return_value': 'trial'}), "(study._storage, 'get_trial', return_value=trial)\n", (9820, 9869), False, 'from unittest.mock import patch\n'), ((9871, 9938), 'unittest.mock.patch', 'patch', (['"""optuna.trial.Trial.system_attrs"""'], {'new_callable': 'PropertyMock'}), "('optuna.trial.Trial.system_attrs', new_callable=PropertyMock)\n", (9876, 9938), False, 'from unittest.mock import patch\n'), ((9963, 10036), 'unittest.mock.patch', 'patch', (['"""optuna.trial.FrozenTrial.system_attrs"""'], {'new_callable': 'PropertyMock'}), "('optuna.trial.FrozenTrial.system_attrs', new_callable=PropertyMock)\n", (9968, 10036), False, 'from unittest.mock import patch\n'), ((10342, 10414), 'unittest.mock.patch.object', 'patch.object', (['study._storage', '"""get_all_trials"""'], {'return_value': 'past_trials'}), "(study._storage, 'get_all_trials', return_value=past_trials)\n", (10354, 10414), False, 'from unittest.mock import patch\n'), ((10416, 10515), 'unittest.mock.patch.object', 'patch.object', (['study._storage', '"""set_trial_system_attr"""'], {'side_effect': 'attrs.set_trial_system_attr'}), "(study._storage, 'set_trial_system_attr', side_effect=attrs.\n set_trial_system_attr)\n", (10428, 10515), False, 'from unittest.mock import patch\n'), ((10526, 10587), 'unittest.mock.patch.object', 'patch.object', (['study._storage', '"""get_trial"""'], {'return_value': 'trial'}), "(study._storage, 'get_trial', return_value=trial)\n", (10538, 10587), False, 'from unittest.mock import patch\n'), ((10589, 10656), 'unittest.mock.patch', 'patch', (['"""optuna.trial.Trial.system_attrs"""'], {'new_callable': 'PropertyMock'}), "('optuna.trial.Trial.system_attrs', new_callable=PropertyMock)\n", (10594, 10656), False, 'from unittest.mock import patch\n'), ((10681, 10754), 'unittest.mock.patch', 'patch', (['"""optuna.trial.FrozenTrial.system_attrs"""'], {'new_callable': 'PropertyMock'}), "('optuna.trial.FrozenTrial.system_attrs', new_callable=PropertyMock)\n", (10686, 10754), False, 'from unittest.mock import patch\n'), ((11490, 11562), 'unittest.mock.patch.object', 'patch.object', (['study._storage', '"""get_all_trials"""'], {'return_value': 'past_trials'}), "(study._storage, 'get_all_trials', return_value=past_trials)\n", (11502, 11562), False, 'from unittest.mock import patch\n'), ((11564, 11663), 'unittest.mock.patch.object', 'patch.object', (['study._storage', '"""set_trial_system_attr"""'], {'side_effect': 'attrs.set_trial_system_attr'}), "(study._storage, 'set_trial_system_attr', side_effect=attrs.\n set_trial_system_attr)\n", (11576, 11663), False, 'from unittest.mock import patch\n'), ((11674, 11735), 'unittest.mock.patch.object', 'patch.object', (['study._storage', '"""get_trial"""'], {'return_value': 'trial'}), "(study._storage, 'get_trial', return_value=trial)\n", (11686, 11735), False, 'from unittest.mock import patch\n'), ((11737, 11804), 'unittest.mock.patch', 'patch', (['"""optuna.trial.Trial.system_attrs"""'], {'new_callable': 'PropertyMock'}), "('optuna.trial.Trial.system_attrs', new_callable=PropertyMock)\n", (11742, 11804), False, 'from unittest.mock import patch\n'), ((11829, 11902), 'unittest.mock.patch', 'patch', (['"""optuna.trial.FrozenTrial.system_attrs"""'], {'new_callable': 'PropertyMock'}), "('optuna.trial.FrozenTrial.system_attrs', new_callable=PropertyMock)\n", (11834, 11902), False, 'from unittest.mock import patch\n'), ((12696, 12768), 'unittest.mock.patch.object', 'patch.object', (['study._storage', '"""get_all_trials"""'], {'return_value': 'past_trials'}), "(study._storage, 'get_all_trials', return_value=past_trials)\n", (12708, 12768), False, 'from unittest.mock import patch\n'), ((12770, 12869), 'unittest.mock.patch.object', 'patch.object', (['study._storage', '"""set_trial_system_attr"""'], {'side_effect': 'attrs.set_trial_system_attr'}), "(study._storage, 'set_trial_system_attr', side_effect=attrs.\n set_trial_system_attr)\n", (12782, 12869), False, 'from unittest.mock import patch\n'), ((12880, 12941), 'unittest.mock.patch.object', 'patch.object', (['study._storage', '"""get_trial"""'], {'return_value': 'trial'}), "(study._storage, 'get_trial', return_value=trial)\n", (12892, 12941), False, 'from unittest.mock import patch\n'), ((12943, 13010), 'unittest.mock.patch', 'patch', (['"""optuna.trial.Trial.system_attrs"""'], {'new_callable': 'PropertyMock'}), "('optuna.trial.Trial.system_attrs', new_callable=PropertyMock)\n", (12948, 13010), False, 'from unittest.mock import patch\n'), ((13035, 13108), 'unittest.mock.patch', 'patch', (['"""optuna.trial.FrozenTrial.system_attrs"""'], {'new_callable': 'PropertyMock'}), "('optuna.trial.FrozenTrial.system_attrs', new_callable=PropertyMock)\n", (13040, 13108), False, 'from unittest.mock import patch\n'), ((13688, 13760), 'unittest.mock.patch.object', 'patch.object', (['study._storage', '"""get_all_trials"""'], {'return_value': 'past_trials'}), "(study._storage, 'get_all_trials', return_value=past_trials)\n", (13700, 13760), False, 'from unittest.mock import patch\n'), ((13762, 13861), 'unittest.mock.patch.object', 'patch.object', (['study._storage', '"""set_trial_system_attr"""'], {'side_effect': 'attrs.set_trial_system_attr'}), "(study._storage, 'set_trial_system_attr', side_effect=attrs.\n set_trial_system_attr)\n", (13774, 13861), False, 'from unittest.mock import patch\n'), ((13872, 13933), 'unittest.mock.patch.object', 'patch.object', (['study._storage', '"""get_trial"""'], {'return_value': 'trial'}), "(study._storage, 'get_trial', return_value=trial)\n", (13884, 13933), False, 'from unittest.mock import patch\n'), ((13935, 14002), 'unittest.mock.patch', 'patch', (['"""optuna.trial.Trial.system_attrs"""'], {'new_callable': 'PropertyMock'}), "('optuna.trial.Trial.system_attrs', new_callable=PropertyMock)\n", (13940, 14002), False, 'from unittest.mock import patch\n'), ((14027, 14100), 'unittest.mock.patch', 'patch', (['"""optuna.trial.FrozenTrial.system_attrs"""'], {'new_callable': 'PropertyMock'}), "('optuna.trial.FrozenTrial.system_attrs', new_callable=PropertyMock)\n", (14032, 14100), False, 'from unittest.mock import patch\n'), ((15119, 15191), 'unittest.mock.patch.object', 'patch.object', (['study._storage', '"""get_all_trials"""'], {'return_value': 'past_trials'}), "(study._storage, 'get_all_trials', return_value=past_trials)\n", (15131, 15191), False, 'from unittest.mock import patch\n'), ((15193, 15292), 'unittest.mock.patch.object', 'patch.object', (['study._storage', '"""set_trial_system_attr"""'], {'side_effect': 'attrs.set_trial_system_attr'}), "(study._storage, 'set_trial_system_attr', side_effect=attrs.\n set_trial_system_attr)\n", (15205, 15292), False, 'from unittest.mock import patch\n'), ((15303, 15364), 'unittest.mock.patch.object', 'patch.object', (['study._storage', '"""get_trial"""'], {'return_value': 'trial'}), "(study._storage, 'get_trial', return_value=trial)\n", (15315, 15364), False, 'from unittest.mock import patch\n'), ((15366, 15433), 'unittest.mock.patch', 'patch', (['"""optuna.trial.Trial.system_attrs"""'], {'new_callable': 'PropertyMock'}), "('optuna.trial.Trial.system_attrs', new_callable=PropertyMock)\n", (15371, 15433), False, 'from unittest.mock import patch\n'), ((15458, 15531), 'unittest.mock.patch', 'patch', (['"""optuna.trial.FrozenTrial.system_attrs"""'], {'new_callable': 'PropertyMock'}), "('optuna.trial.FrozenTrial.system_attrs', new_callable=PropertyMock)\n", (15463, 15531), False, 'from unittest.mock import patch\n'), ((16690, 16762), 'unittest.mock.patch.object', 'patch.object', (['study._storage', '"""get_all_trials"""'], {'return_value': 'past_trials'}), "(study._storage, 'get_all_trials', return_value=past_trials)\n", (16702, 16762), False, 'from unittest.mock import patch\n'), ((16764, 16863), 'unittest.mock.patch.object', 'patch.object', (['study._storage', '"""set_trial_system_attr"""'], {'side_effect': 'attrs.set_trial_system_attr'}), "(study._storage, 'set_trial_system_attr', side_effect=attrs.\n set_trial_system_attr)\n", (16776, 16863), False, 'from unittest.mock import patch\n'), ((16874, 16935), 'unittest.mock.patch.object', 'patch.object', (['study._storage', '"""get_trial"""'], {'return_value': 'trial'}), "(study._storage, 'get_trial', return_value=trial)\n", (16886, 16935), False, 'from unittest.mock import patch\n'), ((16937, 17004), 'unittest.mock.patch', 'patch', (['"""optuna.trial.Trial.system_attrs"""'], {'new_callable': 'PropertyMock'}), "('optuna.trial.Trial.system_attrs', new_callable=PropertyMock)\n", (16942, 17004), False, 'from unittest.mock import patch\n'), ((17029, 17102), 'unittest.mock.patch', 'patch', (['"""optuna.trial.FrozenTrial.system_attrs"""'], {'new_callable': 'PropertyMock'}), "('optuna.trial.FrozenTrial.system_attrs', new_callable=PropertyMock)\n", (17034, 17102), False, 'from unittest.mock import patch\n'), ((17643, 17665), 'random.randint', 'random.randint', (['(0)', '(100)'], {}), '(0, 100)\n', (17657, 17665), False, 'import random\n'), ((18032, 18104), 'unittest.mock.patch.object', 'patch.object', (['study._storage', '"""get_all_trials"""'], {'return_value': 'past_trials'}), "(study._storage, 'get_all_trials', return_value=past_trials)\n", (18044, 18104), False, 'from unittest.mock import patch\n'), ((18106, 18205), 'unittest.mock.patch.object', 'patch.object', (['study._storage', '"""set_trial_system_attr"""'], {'side_effect': 'attrs.set_trial_system_attr'}), "(study._storage, 'set_trial_system_attr', side_effect=attrs.\n set_trial_system_attr)\n", (18118, 18205), False, 'from unittest.mock import patch\n'), ((18216, 18277), 'unittest.mock.patch.object', 'patch.object', (['study._storage', '"""get_trial"""'], {'return_value': 'trial'}), "(study._storage, 'get_trial', return_value=trial)\n", (18228, 18277), False, 'from unittest.mock import patch\n'), ((18279, 18346), 'unittest.mock.patch', 'patch', (['"""optuna.trial.Trial.system_attrs"""'], {'new_callable': 'PropertyMock'}), "('optuna.trial.Trial.system_attrs', new_callable=PropertyMock)\n", (18284, 18346), False, 'from unittest.mock import patch\n'), ((18371, 18444), 'unittest.mock.patch', 'patch', (['"""optuna.trial.FrozenTrial.system_attrs"""'], {'new_callable': 'PropertyMock'}), "('optuna.trial.FrozenTrial.system_attrs', new_callable=PropertyMock)\n", (18376, 18444), False, 'from unittest.mock import patch\n'), ((19493, 19565), 'unittest.mock.patch.object', 'patch.object', (['study._storage', '"""get_all_trials"""'], {'return_value': 'past_trials'}), "(study._storage, 'get_all_trials', return_value=past_trials)\n", (19505, 19565), False, 'from unittest.mock import patch\n'), ((19567, 19666), 'unittest.mock.patch.object', 'patch.object', (['study._storage', '"""set_trial_system_attr"""'], {'side_effect': 'attrs.set_trial_system_attr'}), "(study._storage, 'set_trial_system_attr', side_effect=attrs.\n set_trial_system_attr)\n", (19579, 19666), False, 'from unittest.mock import patch\n'), ((19677, 19738), 'unittest.mock.patch.object', 'patch.object', (['study._storage', '"""get_trial"""'], {'return_value': 'trial'}), "(study._storage, 'get_trial', return_value=trial)\n", (19689, 19738), False, 'from unittest.mock import patch\n'), ((19740, 19807), 'unittest.mock.patch', 'patch', (['"""optuna.trial.Trial.system_attrs"""'], {'new_callable': 'PropertyMock'}), "('optuna.trial.Trial.system_attrs', new_callable=PropertyMock)\n", (19745, 19807), False, 'from unittest.mock import patch\n'), ((19832, 19905), 'unittest.mock.patch', 'patch', (['"""optuna.trial.FrozenTrial.system_attrs"""'], {'new_callable': 'PropertyMock'}), "('optuna.trial.FrozenTrial.system_attrs', new_callable=PropertyMock)\n", (19837, 19905), False, 'from unittest.mock import patch\n'), ((20463, 20535), 'unittest.mock.patch.object', 'patch.object', (['study._storage', '"""get_all_trials"""'], {'return_value': 'past_trials'}), "(study._storage, 'get_all_trials', return_value=past_trials)\n", (20475, 20535), False, 'from unittest.mock import patch\n'), ((20537, 20636), 'unittest.mock.patch.object', 'patch.object', (['study._storage', '"""set_trial_system_attr"""'], {'side_effect': 'attrs.set_trial_system_attr'}), "(study._storage, 'set_trial_system_attr', side_effect=attrs.\n set_trial_system_attr)\n", (20549, 20636), False, 'from unittest.mock import patch\n'), ((20647, 20708), 'unittest.mock.patch.object', 'patch.object', (['study._storage', '"""get_trial"""'], {'return_value': 'trial'}), "(study._storage, 'get_trial', return_value=trial)\n", (20659, 20708), False, 'from unittest.mock import patch\n'), ((20710, 20777), 'unittest.mock.patch', 'patch', (['"""optuna.trial.Trial.system_attrs"""'], {'new_callable': 'PropertyMock'}), "('optuna.trial.Trial.system_attrs', new_callable=PropertyMock)\n", (20715, 20777), False, 'from unittest.mock import patch\n'), ((20802, 20875), 'unittest.mock.patch', 'patch', (['"""optuna.trial.FrozenTrial.system_attrs"""'], {'new_callable': 'PropertyMock'}), "('optuna.trial.FrozenTrial.system_attrs', new_callable=PropertyMock)\n", (20807, 20875), False, 'from unittest.mock import patch\n'), ((21604, 21620), 'random.seed', 'random.seed', (['(128)'], {}), '(128)\n', (21615, 21620), False, 'import random\n'), ((21885, 21903), 'optuna.samplers.TPESampler', 'TPESampler', ([], {'seed': '(0)'}), '(seed=0)\n', (21895, 21903), False, 'from optuna.samplers import TPESampler\n'), ((21942, 22014), 'unittest.mock.patch.object', 'patch.object', (['study._storage', '"""get_all_trials"""'], {'return_value': 'past_trials'}), "(study._storage, 'get_all_trials', return_value=past_trials)\n", (21954, 22014), False, 'from unittest.mock import patch\n'), ((22016, 22115), 'unittest.mock.patch.object', 'patch.object', (['study._storage', '"""set_trial_system_attr"""'], {'side_effect': 'attrs.set_trial_system_attr'}), "(study._storage, 'set_trial_system_attr', side_effect=attrs.\n set_trial_system_attr)\n", (22028, 22115), False, 'from unittest.mock import patch\n'), ((22126, 22187), 'unittest.mock.patch.object', 'patch.object', (['study._storage', '"""get_trial"""'], {'return_value': 'trial'}), "(study._storage, 'get_trial', return_value=trial)\n", (22138, 22187), False, 'from unittest.mock import patch\n'), ((22189, 22256), 'unittest.mock.patch', 'patch', (['"""optuna.trial.Trial.system_attrs"""'], {'new_callable': 'PropertyMock'}), "('optuna.trial.Trial.system_attrs', new_callable=PropertyMock)\n", (22194, 22256), False, 'from unittest.mock import patch\n'), ((22281, 22354), 'unittest.mock.patch', 'patch', (['"""optuna.trial.FrozenTrial.system_attrs"""'], {'new_callable': 'PropertyMock'}), "('optuna.trial.FrozenTrial.system_attrs', new_callable=PropertyMock)\n", (22286, 22354), False, 'from unittest.mock import patch\n'), ((22959, 23015), 'optuna.samplers._tpe.sampler._get_observation_pairs', '_tpe.sampler._get_observation_pairs', (['study', "['x']", '(False)'], {}), "(study, ['x'], False)\n", (22994, 23015), False, 'from optuna.samplers import _tpe\n'), ((23138, 23194), 'optuna.samplers._tpe.sampler._get_observation_pairs', '_tpe.sampler._get_observation_pairs', (['study', "['y']", '(False)'], {}), "(study, ['y'], False)\n", (23173, 23194), False, 'from optuna.samplers import _tpe\n'), ((23322, 23377), 'optuna.samplers._tpe.sampler._get_observation_pairs', '_tpe.sampler._get_observation_pairs', (['study', "['x']", '(True)'], {}), "(study, ['x'], True)\n", (23357, 23377), False, 'from optuna.samplers import _tpe\n'), ((23500, 23555), 'optuna.samplers._tpe.sampler._get_observation_pairs', '_tpe.sampler._get_observation_pairs', (['study', "['y']", '(True)'], {}), "(study, ['y'], True)\n", (23535, 23555), False, 'from optuna.samplers import _tpe\n'), ((23719, 23772), 'optuna.samplers._tpe.sampler._calculate_nondomination_rank', '_tpe.sampler._calculate_nondomination_rank', (['test_case'], {}), '(test_case)\n', (23761, 23772), False, 'from optuna.samplers import _tpe\n'), ((23925, 23978), 'optuna.samplers._tpe.sampler._calculate_nondomination_rank', '_tpe.sampler._calculate_nondomination_rank', (['test_case'], {}), '(test_case)\n', (23967, 23978), False, 'from optuna.samplers import _tpe\n'), ((24152, 24205), 'optuna.samplers._tpe.sampler._calculate_nondomination_rank', '_tpe.sampler._calculate_nondomination_rank', (['test_case'], {}), '(test_case)\n', (24194, 24205), False, 'from optuna.samplers import _tpe\n'), ((24491, 24507), 'numpy.array', 'np.array', (['[0, 1]'], {}), '([0, 1])\n', (24499, 24507), True, 'import numpy as np\n'), ((24830, 24846), 'numpy.array', 'np.array', (['[0, 1]'], {}), '([0, 1])\n', (24838, 24846), True, 'import numpy as np\n'), ((25157, 25173), 'numpy.array', 'np.array', (['[0, 1]'], {}), '([0, 1])\n', (25165, 25173), True, 'import numpy as np\n'), ((25517, 25536), 'numpy.array', 'np.array', (['[0, 1, 2]'], {}), '([0, 1, 2])\n', (25525, 25536), True, 'import numpy as np\n'), ((26078, 26124), 'itertools.permutations', 'itertools.permutations', (['test_case', 'subset_size'], {}), '(test_case, subset_size)\n', (26100, 26124), False, 'import itertools\n'), ((26329, 26385), 'optuna.samplers._tpe.sampler._compute_hypervolume', '_tpe.sampler._compute_hypervolume', (['test_case[indices]', 'r'], {}), '(test_case[indices], r)\n', (26362, 26385), False, 'from optuna.samplers import _tpe\n'), ((26744, 26790), 'itertools.permutations', 'itertools.permutations', (['test_case', 'subset_size'], {}), '(test_case, subset_size)\n', (26766, 26790), False, 'import itertools\n'), ((26995, 27051), 'optuna.samplers._tpe.sampler._compute_hypervolume', '_tpe.sampler._compute_hypervolume', (['test_case[indices]', 'r'], {}), '(test_case[indices], r)\n', (27028, 27051), False, 'from optuna.samplers import _tpe\n'), ((26010, 26035), 'numpy.max', 'np.max', (['test_case'], {'axis': '(0)'}), '(test_case, axis=0)\n', (26016, 26035), True, 'import numpy as np\n'), ((26678, 26703), 'numpy.max', 'np.max', (['test_case'], {'axis': '(0)'}), '(test_case, axis=0)\n', (26684, 26703), True, 'import numpy as np\n'), ((856, 871), 'random.random', 'random.random', ([], {}), '()\n', (869, 871), False, 'import random\n'), ((873, 888), 'random.random', 'random.random', ([], {}), '()\n', (886, 888), False, 'import random\n'), ((3323, 3338), 'random.random', 'random.random', ([], {}), '()\n', (3336, 3338), False, 'import random\n'), ((3340, 3355), 'random.random', 'random.random', ([], {}), '()\n', (3353, 3355), False, 'import random\n'), ((5840, 5855), 'random.random', 'random.random', ([], {}), '()\n', (5853, 5855), False, 'import random\n'), ((5857, 5872), 'random.random', 'random.random', ([], {}), '()\n', (5870, 5872), False, 'import random\n'), ((7965, 7980), 'random.random', 'random.random', ([], {}), '()\n', (7978, 7980), False, 'import random\n'), ((7982, 7997), 'random.random', 'random.random', ([], {}), '()\n', (7995, 7997), False, 'import random\n'), ((10283, 10294), 'numpy.zeros', 'np.zeros', (['n'], {}), '(n)\n', (10291, 10294), True, 'import numpy as np\n'), ((11250, 11265), 'random.random', 'random.random', ([], {}), '()\n', (11263, 11265), False, 'import random\n'), ((11267, 11282), 'random.random', 'random.random', ([], {}), '()\n', (11280, 11282), False, 'import random\n'), ((12525, 12540), 'random.random', 'random.random', ([], {}), '()\n', (12538, 12540), False, 'import random\n'), ((12542, 12557), 'random.random', 'random.random', ([], {}), '()\n', (12555, 12557), False, 'import random\n'), ((13502, 13517), 'random.random', 'random.random', ([], {}), '()\n', (13515, 13517), False, 'import random\n'), ((13519, 13534), 'random.random', 'random.random', ([], {}), '()\n', (13532, 13534), False, 'import random\n'), ((14890, 14905), 'random.random', 'random.random', ([], {}), '()\n', (14903, 14905), False, 'import random\n'), ((14907, 14922), 'random.random', 'random.random', ([], {}), '()\n', (14920, 14922), False, 'import random\n'), ((16458, 16473), 'random.random', 'random.random', ([], {}), '()\n', (16471, 16473), False, 'import random\n'), ((16475, 16490), 'random.random', 'random.random', ([], {}), '()\n', (16488, 16490), False, 'import random\n'), ((17800, 17815), 'random.random', 'random.random', ([], {}), '()\n', (17813, 17815), False, 'import random\n'), ((17817, 17832), 'random.random', 'random.random', ([], {}), '()\n', (17830, 17832), False, 'import random\n'), ((19321, 19336), 'random.random', 'random.random', ([], {}), '()\n', (19334, 19336), False, 'import random\n'), ((19338, 19353), 'random.random', 'random.random', ([], {}), '()\n', (19351, 19353), False, 'import random\n'), ((20259, 20274), 'random.random', 'random.random', ([], {}), '()\n', (20272, 20274), False, 'import random\n'), ((20276, 20291), 'random.random', 'random.random', ([], {}), '()\n', (20289, 20291), False, 'import random\n'), ((27544, 27559), 'random.random', 'random.random', ([], {}), '()\n', (27557, 27559), False, 'import random\n'), ((14793, 14808), 'random.random', 'random.random', ([], {}), '()\n', (14806, 14808), False, 'import random\n'), ((21723, 21738), 'random.random', 'random.random', ([], {}), '()\n', (21736, 21738), False, 'import random\n'), ((21740, 21755), 'random.random', 'random.random', ([], {}), '()\n', (21753, 21755), False, 'import random\n'), ((25880, 25895), 'random.random', 'random.random', ([], {}), '()\n', (25893, 25895), False, 'import random\n'), ((25938, 25953), 'random.random', 'random.random', ([], {}), '()\n', (25951, 25953), False, 'import random\n'), ((25955, 25970), 'random.random', 'random.random', ([], {}), '()\n', (25968, 25970), False, 'import random\n'), ((26191, 26209), 'numpy.asarray', 'np.asarray', (['subset'], {}), '(subset)\n', (26201, 26209), True, 'import numpy as np\n'), ((26509, 26524), 'random.random', 'random.random', ([], {}), '()\n', (26522, 26524), False, 'import random\n'), ((26580, 26595), 'random.random', 'random.random', ([], {}), '()\n', (26593, 26595), False, 'import random\n'), ((26597, 26612), 'random.random', 'random.random', ([], {}), '()\n', (26610, 26612), False, 'import random\n'), ((26614, 26629), 'random.random', 'random.random', ([], {}), '()\n', (26627, 26629), False, 'import random\n'), ((26857, 26875), 'numpy.asarray', 'np.asarray', (['subset'], {}), '(subset)\n', (26867, 26875), True, 'import numpy as np\n')]
#!/usr/bin/python # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of NVIDIA CORPORATION nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY # EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY # OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import argparse import time import numpy as np import pandas as pd import os from builtins import range from PIL import Image import grpc # Drop "from src.core import" because the import hierarchy in proto files # will be removed in Makefile.clients from tensorrtserver.api import api_pb2 from tensorrtserver.api import grpc_service_pb2 from tensorrtserver.api import grpc_service_pb2_grpc from tensorrtserver.api import model_config_pb2 from tensorrtserver.api import request_status_pb2 from tensorrtserver.api import server_status_pb2 FLAGS = None def _log(*args, **kwargs): print("[Client]", *args, **kwargs) def model_dtype_to_np(model_dtype): if model_dtype == model_config_pb2.TYPE_BOOL: return np.bool elif model_dtype == model_config_pb2.TYPE_INT8: return np.int8 elif model_dtype == model_config_pb2.TYPE_INT16: return np.int16 elif model_dtype == model_config_pb2.TYPE_INT32: return np.int32 elif model_dtype == model_config_pb2.TYPE_INT64: return np.int64 elif model_dtype == model_config_pb2.TYPE_UINT8: return np.uint8 elif model_dtype == model_config_pb2.TYPE_UINT16: return np.uint16 elif model_dtype == model_config_pb2.TYPE_FP16: return np.float16 elif model_dtype == model_config_pb2.TYPE_FP32: return np.float32 elif model_dtype == model_config_pb2.TYPE_FP64: return np.float64 return None def parse_model(status, model_name, batch_size, verbose=False): """ Check the configuration of a model to make sure it meets the requirements for an image classification network (as expected by this client) """ server_status = status.server_status if model_name not in server_status.model_status.keys(): raise Exception("unable to get status for '" + model_name + "'") status = server_status.model_status[model_name] config = status.config if len(config.input) != 1: raise Exception("expecting 1 input, got " + len(config.input)) if len(config.output) != 1: raise Exception("expecting 1 output, got " + len(config.output)) input = config.input[0] output = config.output[0] if output.data_type != model_config_pb2.TYPE_FP32: raise Exception("expecting output datatype to be TYPE_FP32, model '" + model_name + "' output type is " + model_config_pb2.DataType.Name(output.data_type)) # Output is expected to be a vector. But allow any number of # dimensions as long as all but 1 is size 1 (e.g. { 10 }, { 1, 10 # }, { 10, 1, 1 } are all ok). non_one_cnt = 0 for dim in output.dims: if dim > 1: non_one_cnt += 1 if non_one_cnt > 1: raise Exception("expecting model output to be a vector") # Model specifying maximum batch size of 0 indicates that batching # is not supported and so the input tensors do not expect an "N" # dimension (and 'batch_size' should be 1 so that only a single # image instance is inferred at a time). max_batch_size = config.max_batch_size if max_batch_size == 0: if batch_size != 1: raise Exception("batching not supported for model '" + model_name + "'") else: # max_batch_size > 0 if batch_size > max_batch_size: raise Exception("expecting batch size <= " + max_batch_size + " for model '" + model_name + "'") # Model input must have 3 dims, either CHW or HWC if len(input.dims) != 3: raise Exception("expecting input to have 3 dimensions, model '" + model_name + "' input has " << len(input.dims)) if ((input.format != model_config_pb2.ModelInput.FORMAT_NCHW) and (input.format != model_config_pb2.ModelInput.FORMAT_NHWC)): raise Exception("unexpected input format " + model_config_pb2.ModelInput.Format.Name(input.format) + ", expecting " + model_config_pb2.ModelInput.Format.Name(model_config_pb2.ModelInput.FORMAT_NCHW) + " or " + model_config_pb2.ModelInput.Format.Name(model_config_pb2.ModelInput.FORMAT_NHWC)) if input.format == model_config_pb2.ModelInput.FORMAT_NHWC: h = input.dims[0] w = input.dims[1] c = input.dims[2] else: c = input.dims[0] h = input.dims[1] w = input.dims[2] output_size = 1 for dim in output.dims: output_size = output_size * dim output_size = output_size * np.dtype(model_dtype_to_np(output.data_type)).itemsize return (input.name, output.name, c, h, w, input.format, model_dtype_to_np(input.data_type), output_size) def preprocess(img, format, dtype, c, h, w, scaling): """ Pre-process an image to meet the size, type and format requirements specified by the parameters. """ #np.set_printoptions(threshold='nan') if c == 1: sample_img = img.convert('L') else: sample_img = img.convert('RGB') resized_img = sample_img.resize((h, w), Image.BILINEAR) resized = np.array(resized_img) if resized.ndim == 2: resized = resized[:,:,np.newaxis] typed = resized.astype(dtype) if scaling == 'INCEPTION': scaled = (typed / 128) - 1 elif scaling == 'VGG': if c == 1: scaled = typed - np.asarray((128,), dtype=dtype) else: scaled = typed - np.asarray((123, 117, 104), dtype=dtype) else: scaled = typed # Swap to CHW if necessary if format == model_config_pb2.ModelInput.FORMAT_NCHW: ordered = np.transpose(scaled, (2, 0, 1)) else: ordered = scaled # Channels are in RGB order. Currently model configuration data # doesn't provide any information as to other channel orderings # (like BGR) so we just assume RGB. return ordered def postprocess(results, files, idx, batch_size, num_classes, verbose=False): """ Post-process results to show classifications. """ show_all = verbose or ((batch_size == 1) and (num_classes > 1)) if show_all: if idx == 0: print("Output probabilities:") print("batch {}:".format(idx)) if len(results) != 1: raise Exception("expected 1 result, got " + str(len(results))) batched_result = results[0].batch_classes if len(batched_result) != batch_size: raise Exception("expected " + str(batch_size) + " results, got " + str(len(batched_result))) # For each result in the batch count the top prediction. Since we # used the same image for every entry in the batch we expect the # top prediction to be the same for each entry... but this code # doesn't assume that. counts = dict() predictions = dict() for (index, result) in enumerate(batched_result): label = result.cls[0].label if label not in counts: counts[label] = 0 counts[label] += 1 predictions[label] = result.cls[0] # If requested, print all the class results for the entry if show_all: if (index >= len(files)): index = len(files) - 1 # Top 1, print compactly if len(result.cls) == 1: print("Image '{}': {} ({}) = {}".format( files[index], result.cls[0].idx, result.cls[0].label, result.cls[0].value)) else: print("Image '{}':".format(files[index])) for cls in result.cls: print(" {} ({}) = {}".format(cls.idx, cls.label, cls.value)) # Summary print("Prediction totals:") for (label, cnt) in counts.items(): cls = predictions[label] print("\tcnt={}\t({}) {}".format(cnt, cls.idx, cls.label)) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('-v', '--verbose', action="store_true", required=False, default=False, help='Enable verbose output') parser.add_argument('-m', '--model-name', type=str, required=True, help='Name of model') parser.add_argument('-x', '--model-version', type=str, required=False, help='Version of model. Default is to use latest version.') parser.add_argument('-b', '--batch-size', type=int, required=False, default=1, help='Batch size. Default is 1.') parser.add_argument('-c', '--classes', type=int, required=False, default=1, help='Number of class results to report. Default is 1.') parser.add_argument('-s', '--scaling', type=str, choices=['NONE', 'INCEPTION', 'VGG'], required=False, default='NONE', help='Type of scaling to apply to image pixels. Default is NONE.') parser.add_argument('-u', '--url', type=str, required=False, default='localhost:8001', help='Inference server URL. Default is localhost:8001.') parser.add_argument('-p', '--preprocessed', type=str, required=False, metavar='FILE', help='Write preprocessed image to specified file.') parser.add_argument('--result-name', type=str, required=False, help='Path to parquet file') parser.add_argument('image_filename', type=str, nargs='?', default=None, help='Input image.') FLAGS = parser.parse_args() # Create gRPC stub for communicating with the server channel = grpc.insecure_channel(FLAGS.url) grpc_stub = grpc_service_pb2_grpc.GRPCServiceStub(channel) # Prepare request for Status gRPC request = grpc_service_pb2.StatusRequest(model_name=FLAGS.model_name) # Call and receive response from Status gRPC response = grpc_stub.Status(request) # Make sure the model matches our requirements, and get some # properties of the model that we need for preprocessing input_name, output_name, c, h, w, format, dtype, output_size = parse_model( response, FLAGS.model_name, FLAGS.batch_size, FLAGS.verbose) # Prepare request for Infer gRPC # The meta data part can be reused across requests request = grpc_service_pb2.InferRequest() request.model_name = FLAGS.model_name if FLAGS.model_version is None: FLAGS.model_version = "" # using lastest version request.version = FLAGS.model_version request.meta_data.batch_size = FLAGS.batch_size output_message = api_pb2.InferRequestHeader.Output() output_message.name = output_name output_message.byte_size = output_size output_message.cls.count = FLAGS.classes request.meta_data.output.extend([output_message]) multiple_inputs = False batched_filenames = [] responses = [] if os.path.isdir(FLAGS.image_filename): files = [f for f in os.listdir(FLAGS.image_filename) if os.path.isfile(os.path.join(FLAGS.image_filename, f))] multiple_inputs = (len(files) > 1) input_bytes = None requests = [] filenames = [] # Place every 'batch_size' number of images into one request # and send it via AsyncRun() API. If the last request doesn't have # 'batch_size' input tensors, pad it with the last input tensor. cnt = 0 for idx in range(len(files)): filenames.append(files[idx]) img = Image.open(os.path.join(FLAGS.image_filename, files[idx])) input_tensor = preprocess(img, format, dtype, c, h, w, FLAGS.scaling) # This field can not be set until input tensor is obtained if len(request.meta_data.input) == 0: request.meta_data.input.add( name=input_name, byte_size=input_tensor.size * input_tensor.itemsize) if input_bytes is None: input_bytes = input_tensor.tobytes() else: input_bytes += input_tensor.tobytes() cnt += 1 if (idx + 1 == len(files)): while (cnt != FLAGS.batch_size): input_bytes += input_tensor.tobytes() cnt += 1 # Send the request and reset input_tensors if cnt >= FLAGS.batch_size: del request.raw_input[:] request.raw_input.extend([input_bytes]) # Call and receive future response from async Infer gRPC requests.append(grpc_stub.Infer.future(request)) input_bytes = None cnt = 0 batched_filenames.append(filenames) filenames = [] # Get results by send order for request in requests: responses.append(request.result()) else: batched_filenames.append([FLAGS.image_filename]) # Load and preprocess the image img = Image.open(FLAGS.image_filename) input_tensor = preprocess(img, format, dtype, c, h, w, FLAGS.scaling) request.meta_data.input.add( name=input_name, byte_size=input_tensor.size * input_tensor.itemsize) if FLAGS.preprocessed is not None: with open(preprocessed, "w") as file: file.write(input_tensor.tobytes()) # Need 'batch_size' copies of the input tensor... input_bytes = input_tensor.tobytes() for b in range(FLAGS.batch_size-1): input_bytes += input_tensor.tobytes() request.raw_input.extend([input_bytes]) # Call and receive response from Infer gRPC durations = [] for _ in range(2000): start = time.perf_counter() responses.append(grpc_stub.Infer(request)) end = time.perf_counter() duration_ms = (end - start) * 1000 durations.append(duration_ms) responses.append(grpc_stub.Infer(request)) # print(responses[0].request_status) # Save Data df = pd.DataFrame({"duration_ms": durations}) df.to_parquet('10.pq') mean, p99 = df["duration_ms"].mean(), np.percentile(durations, 99) _log(f"Mean Latency: {mean}, P99: {p99}") # TODO: Update postprocess #for idx in range(len(responses)): # postprocess(responses[idx].meta_data.output, batched_filenames[idx], # idx, FLAGS.batch_size, FLAGS.classes, # FLAGS.verbose or multiple_inputs)
[ "numpy.array", "builtins.range", "os.listdir", "argparse.ArgumentParser", "numpy.asarray", "time.perf_counter", "tensorrtserver.api.api_pb2.InferRequestHeader.Output", "os.path.isdir", "pandas.DataFrame", "tensorrtserver.api.model_config_pb2.ModelInput.Format.Name", "tensorrtserver.api.model_con...
[((6714, 6735), 'numpy.array', 'np.array', (['resized_img'], {}), '(resized_img)\n', (6722, 6735), True, 'import numpy as np\n'), ((9477, 9502), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (9500, 9502), False, 'import argparse\n'), ((11157, 11189), 'grpc.insecure_channel', 'grpc.insecure_channel', (['FLAGS.url'], {}), '(FLAGS.url)\n', (11178, 11189), False, 'import grpc\n'), ((11206, 11252), 'tensorrtserver.api.grpc_service_pb2_grpc.GRPCServiceStub', 'grpc_service_pb2_grpc.GRPCServiceStub', (['channel'], {}), '(channel)\n', (11243, 11252), False, 'from tensorrtserver.api import grpc_service_pb2_grpc\n'), ((11306, 11365), 'tensorrtserver.api.grpc_service_pb2.StatusRequest', 'grpc_service_pb2.StatusRequest', ([], {'model_name': 'FLAGS.model_name'}), '(model_name=FLAGS.model_name)\n', (11336, 11365), False, 'from tensorrtserver.api import grpc_service_pb2\n'), ((11838, 11869), 'tensorrtserver.api.grpc_service_pb2.InferRequest', 'grpc_service_pb2.InferRequest', ([], {}), '()\n', (11867, 11869), False, 'from tensorrtserver.api import grpc_service_pb2\n'), ((12120, 12155), 'tensorrtserver.api.api_pb2.InferRequestHeader.Output', 'api_pb2.InferRequestHeader.Output', ([], {}), '()\n', (12153, 12155), False, 'from tensorrtserver.api import api_pb2\n'), ((12418, 12453), 'os.path.isdir', 'os.path.isdir', (['FLAGS.image_filename'], {}), '(FLAGS.image_filename)\n', (12431, 12453), False, 'import os\n'), ((7238, 7269), 'numpy.transpose', 'np.transpose', (['scaled', '(2, 0, 1)'], {}), '(scaled, (2, 0, 1))\n', (7250, 7269), True, 'import numpy as np\n'), ((14497, 14529), 'PIL.Image.open', 'Image.open', (['FLAGS.image_filename'], {}), '(FLAGS.image_filename)\n', (14507, 14529), False, 'from PIL import Image\n'), ((14993, 15020), 'builtins.range', 'range', (['(FLAGS.batch_size - 1)'], {}), '(FLAGS.batch_size - 1)\n', (14998, 15020), False, 'from builtins import range\n'), ((15211, 15222), 'builtins.range', 'range', (['(2000)'], {}), '(2000)\n', (15216, 15222), False, 'from builtins import range\n'), ((15591, 15631), 'pandas.DataFrame', 'pd.DataFrame', (["{'duration_ms': durations}"], {}), "({'duration_ms': durations})\n", (15603, 15631), True, 'import pandas as pd\n'), ((15244, 15263), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (15261, 15263), False, 'import time\n'), ((15337, 15356), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (15354, 15356), False, 'import time\n'), ((15709, 15737), 'numpy.percentile', 'np.percentile', (['durations', '(99)'], {}), '(durations, 99)\n', (15722, 15737), True, 'import numpy as np\n'), ((3966, 4014), 'tensorrtserver.api.model_config_pb2.DataType.Name', 'model_config_pb2.DataType.Name', (['output.data_type'], {}), '(output.data_type)\n', (3996, 4014), False, 'from tensorrtserver.api import model_config_pb2\n'), ((5718, 5803), 'tensorrtserver.api.model_config_pb2.ModelInput.Format.Name', 'model_config_pb2.ModelInput.Format.Name', (['model_config_pb2.ModelInput.FORMAT_NHWC'], {}), '(model_config_pb2.ModelInput.FORMAT_NHWC\n )\n', (5757, 5803), False, 'from tensorrtserver.api import model_config_pb2\n'), ((12483, 12515), 'os.listdir', 'os.listdir', (['FLAGS.image_filename'], {}), '(FLAGS.image_filename)\n', (12493, 12515), False, 'import os\n'), ((13044, 13090), 'os.path.join', 'os.path.join', (['FLAGS.image_filename', 'files[idx]'], {}), '(FLAGS.image_filename, files[idx])\n', (13056, 13090), False, 'import os\n'), ((6981, 7012), 'numpy.asarray', 'np.asarray', (['(128,)'], {'dtype': 'dtype'}), '((128,), dtype=dtype)\n', (6991, 7012), True, 'import numpy as np\n'), ((7056, 7096), 'numpy.asarray', 'np.asarray', (['(123, 117, 104)'], {'dtype': 'dtype'}), '((123, 117, 104), dtype=dtype)\n', (7066, 7096), True, 'import numpy as np\n'), ((12546, 12583), 'os.path.join', 'os.path.join', (['FLAGS.image_filename', 'f'], {}), '(FLAGS.image_filename, f)\n', (12558, 12583), False, 'import os\n'), ((5578, 5663), 'tensorrtserver.api.model_config_pb2.ModelInput.Format.Name', 'model_config_pb2.ModelInput.Format.Name', (['model_config_pb2.ModelInput.FORMAT_NCHW'], {}), '(model_config_pb2.ModelInput.FORMAT_NCHW\n )\n', (5617, 5663), False, 'from tensorrtserver.api import model_config_pb2\n'), ((5457, 5510), 'tensorrtserver.api.model_config_pb2.ModelInput.Format.Name', 'model_config_pb2.ModelInput.Format.Name', (['input.format'], {}), '(input.format)\n', (5496, 5510), False, 'from tensorrtserver.api import model_config_pb2\n')]
from __future__ import absolute_import from __future__ import division from __future__ import print_function import sys import matplotlib.pyplot as plt import numpy as np from sklearn.ensemble import RandomForestClassifier from sklearn.utils import shuffle from sklearn.metrics import confusion_matrix from sklearn.utils.multiclass import unique_labels sys.path.append('..') from libs.data.mass import Mass from libs.data.utils import power_spectrum def plot_confusion_matrix(y_true, y_pred, normalize=False, title=None, cmap=plt.cm.Blues): """ This function prints and plots the confusion matrix. Normalization can be applied by setting `normalize=True`. """ if not title: if normalize: title = 'Normalized confusion matrix' else: title = 'Confusion matrix, without normalization' # Compute confusion matrix cm = confusion_matrix(y_true, y_pred) # Only use the labels that appear in the data classes = unique_labels(y_true, y_pred) if normalize: cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] print("Normalized confusion matrix") else: print('Confusion matrix, without normalization') print(cm) fig, ax = plt.subplots() im = ax.imshow(cm, interpolation='nearest', cmap=cmap) ax.figure.colorbar(im, ax=ax) # We want to show all ticks... ax.set(xticks=np.arange(cm.shape[1]), yticks=np.arange(cm.shape[0]), # ... and label them with the respective list entries xticklabels=classes, yticklabels=classes, title=title, ylabel='True label', xlabel='Predicted label') # Rotate the tick labels and set their alignment. plt.setp(ax.get_xticklabels(), rotation=45, ha="right", rotation_mode="anchor") # Loop over data dimensions and create text annotations. fmt = '.2f' if normalize else 'd' thresh = cm.max() / 2. for i in range(cm.shape[0]): for j in range(cm.shape[1]): ax.text(j, i, format(cm[i, j], fmt), ha="center", va="center", color="white" if cm[i, j] > thresh else "black") fig.tight_layout() return ax if __name__ == '__main__': dataset = Mass(load_checkpoint=True) subject_id = 1 original_fs = dataset.fs page_duration = dataset.page_duration signal_names = dataset.get_signal_names() stage2int_dict = { '?': 2, 'W': 1, 'R': 0, 'N1': -1, 'N2': -2, 'N3': -3 } # Get database output_fs = 100 x_train, y_train = dataset.get_subset_data( subject_id_list=dataset.get_train_ids(), output_fs=output_fs, border_duration=0, ignore_unknown=True) x_test, y_test = dataset.get_subset_data( subject_id_list=dataset.get_test_ids(), output_fs=output_fs, border_duration=0, ignore_unknown=True) x_train = np.concatenate(x_train, axis=0) y_train = np.concatenate(y_train, axis=0) x_test = np.concatenate(x_test, axis=0) y_test = np.concatenate(y_test, axis=0) print('%d segments in train set. %d segments in test set' % (y_train.size, y_test.size)) # Check class frequency print('') print('Training set') values, counts = np.unique(y_train, return_counts=True) for value, count in zip(values, counts): print('%s: %d segments (%1.2f %% of total)' % (value, count, 100*count/y_train.size)) print('') print('Test set') values, counts = np.unique(y_test, return_counts=True) for value, count in zip(values, counts): print('%s: %d segments (%1.2f %% of total)' % (value, count, 100 * count / y_test.size)) print('') # Compute simple features using FFT print('Computing Training set features') x_train_features = [] for i in range(x_train.shape[0]): example_feats = [] for chn in range(x_train.shape[2]): single_channel = x_train[i, :, chn] power, freq = power_spectrum(single_channel, output_fs) delta_idx = np.where((freq >= 0) & (freq <= 4))[0] theta_idx = np.where((freq >= 4) & (freq <= 7.5))[0] alpha_idx = np.where((freq >= 7.5) & (freq <= 15.5))[0] beta_idx = np.where((freq >= 15.5) & (freq <= 31))[0] gamma_idx = np.where(freq >= 31)[0] example_feats.append([ power[delta_idx].sum(), power[theta_idx].sum(), power[alpha_idx].sum(), power[beta_idx].sum(), power[gamma_idx].sum() ]) example_feats = np.concatenate(example_feats).flatten() x_train_features.append(example_feats) x_train_features = np.stack(x_train_features, axis=0) print('Computing Test set features') x_test_features = [] for i in range(x_test.shape[0]): example_feats = [] for chn in range(x_test.shape[2]): single_channel = x_test[i, :, chn] power, freq = power_spectrum(single_channel, output_fs) delta_idx = np.where((freq >= 0) & (freq <= 4))[0] theta_idx = np.where((freq >= 4) & (freq <= 7.5))[0] alpha_idx = np.where((freq >= 7.5) & (freq <= 15.5))[0] beta_idx = np.where((freq >= 15.5) & (freq <= 31))[0] gamma_idx = np.where(freq >= 31)[0] example_feats.append([ power[delta_idx].sum(), power[theta_idx].sum(), power[alpha_idx].sum(), power[beta_idx].sum(), power[gamma_idx].sum() ]) example_feats = np.concatenate(example_feats).flatten() x_test_features.append(example_feats) x_test_features = np.stack(x_test_features, axis=0) # Train a simple classifier to solve the task x_train_features, y_train = shuffle( x_train_features, y_train, random_state=0) clf = RandomForestClassifier( n_estimators=50, max_depth=4, class_weight="balanced", random_state=0) clf = clf.fit(x_train_features, y_train) # Predict on test data y_hat_test = clf.predict(x_test_features) # Evaluate performance np.set_printoptions(precision=2) # Plot non-normalized confusion matrix plot_confusion_matrix(y_test, y_hat_test, title='Confusion matrix, without normalization') plt.show() # Plot normalized confusion matrix plot_confusion_matrix(y_test, y_hat_test, normalize=True, title='Normalized confusion matrix') plt.show()
[ "libs.data.mass.Mass", "numpy.unique", "matplotlib.pyplot.show", "numpy.where", "sklearn.utils.shuffle", "numpy.set_printoptions", "sklearn.ensemble.RandomForestClassifier", "numpy.stack", "libs.data.utils.power_spectrum", "numpy.concatenate", "sklearn.utils.multiclass.unique_labels", "sys.pat...
[((356, 377), 'sys.path.append', 'sys.path.append', (['""".."""'], {}), "('..')\n", (371, 377), False, 'import sys\n'), ((967, 999), 'sklearn.metrics.confusion_matrix', 'confusion_matrix', (['y_true', 'y_pred'], {}), '(y_true, y_pred)\n', (983, 999), False, 'from sklearn.metrics import confusion_matrix\n'), ((1064, 1093), 'sklearn.utils.multiclass.unique_labels', 'unique_labels', (['y_true', 'y_pred'], {}), '(y_true, y_pred)\n', (1077, 1093), False, 'from sklearn.utils.multiclass import unique_labels\n'), ((1318, 1332), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (1330, 1332), True, 'import matplotlib.pyplot as plt\n'), ((2349, 2375), 'libs.data.mass.Mass', 'Mass', ([], {'load_checkpoint': '(True)'}), '(load_checkpoint=True)\n', (2353, 2375), False, 'from libs.data.mass import Mass\n'), ((3026, 3057), 'numpy.concatenate', 'np.concatenate', (['x_train'], {'axis': '(0)'}), '(x_train, axis=0)\n', (3040, 3057), True, 'import numpy as np\n'), ((3072, 3103), 'numpy.concatenate', 'np.concatenate', (['y_train'], {'axis': '(0)'}), '(y_train, axis=0)\n', (3086, 3103), True, 'import numpy as np\n'), ((3117, 3147), 'numpy.concatenate', 'np.concatenate', (['x_test'], {'axis': '(0)'}), '(x_test, axis=0)\n', (3131, 3147), True, 'import numpy as np\n'), ((3161, 3191), 'numpy.concatenate', 'np.concatenate', (['y_test'], {'axis': '(0)'}), '(y_test, axis=0)\n', (3175, 3191), True, 'import numpy as np\n'), ((3386, 3424), 'numpy.unique', 'np.unique', (['y_train'], {'return_counts': '(True)'}), '(y_train, return_counts=True)\n', (3395, 3424), True, 'import numpy as np\n'), ((3635, 3672), 'numpy.unique', 'np.unique', (['y_test'], {'return_counts': '(True)'}), '(y_test, return_counts=True)\n', (3644, 3672), True, 'import numpy as np\n'), ((4874, 4908), 'numpy.stack', 'np.stack', (['x_train_features'], {'axis': '(0)'}), '(x_train_features, axis=0)\n', (4882, 4908), True, 'import numpy as np\n'), ((5890, 5923), 'numpy.stack', 'np.stack', (['x_test_features'], {'axis': '(0)'}), '(x_test_features, axis=0)\n', (5898, 5923), True, 'import numpy as np\n'), ((6007, 6057), 'sklearn.utils.shuffle', 'shuffle', (['x_train_features', 'y_train'], {'random_state': '(0)'}), '(x_train_features, y_train, random_state=0)\n', (6014, 6057), False, 'from sklearn.utils import shuffle\n'), ((6077, 6175), 'sklearn.ensemble.RandomForestClassifier', 'RandomForestClassifier', ([], {'n_estimators': '(50)', 'max_depth': '(4)', 'class_weight': '"""balanced"""', 'random_state': '(0)'}), "(n_estimators=50, max_depth=4, class_weight=\n 'balanced', random_state=0)\n", (6099, 6175), False, 'from sklearn.ensemble import RandomForestClassifier\n'), ((6331, 6363), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'precision': '(2)'}), '(precision=2)\n', (6350, 6363), True, 'import numpy as np\n'), ((6533, 6543), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (6541, 6543), True, 'import matplotlib.pyplot as plt\n'), ((6713, 6723), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (6721, 6723), True, 'import matplotlib.pyplot as plt\n'), ((1479, 1501), 'numpy.arange', 'np.arange', (['cm.shape[1]'], {}), '(cm.shape[1])\n', (1488, 1501), True, 'import numpy as np\n'), ((1521, 1543), 'numpy.arange', 'np.arange', (['cm.shape[0]'], {}), '(cm.shape[0])\n', (1530, 1543), True, 'import numpy as np\n'), ((4138, 4179), 'libs.data.utils.power_spectrum', 'power_spectrum', (['single_channel', 'output_fs'], {}), '(single_channel, output_fs)\n', (4152, 4179), False, 'from libs.data.utils import power_spectrum\n'), ((5156, 5197), 'libs.data.utils.power_spectrum', 'power_spectrum', (['single_channel', 'output_fs'], {}), '(single_channel, output_fs)\n', (5170, 5197), False, 'from libs.data.utils import power_spectrum\n'), ((4204, 4239), 'numpy.where', 'np.where', (['((freq >= 0) & (freq <= 4))'], {}), '((freq >= 0) & (freq <= 4))\n', (4212, 4239), True, 'import numpy as np\n'), ((4267, 4304), 'numpy.where', 'np.where', (['((freq >= 4) & (freq <= 7.5))'], {}), '((freq >= 4) & (freq <= 7.5))\n', (4275, 4304), True, 'import numpy as np\n'), ((4332, 4372), 'numpy.where', 'np.where', (['((freq >= 7.5) & (freq <= 15.5))'], {}), '((freq >= 7.5) & (freq <= 15.5))\n', (4340, 4372), True, 'import numpy as np\n'), ((4399, 4438), 'numpy.where', 'np.where', (['((freq >= 15.5) & (freq <= 31))'], {}), '((freq >= 15.5) & (freq <= 31))\n', (4407, 4438), True, 'import numpy as np\n'), ((4466, 4486), 'numpy.where', 'np.where', (['(freq >= 31)'], {}), '(freq >= 31)\n', (4474, 4486), True, 'import numpy as np\n'), ((4764, 4793), 'numpy.concatenate', 'np.concatenate', (['example_feats'], {}), '(example_feats)\n', (4778, 4793), True, 'import numpy as np\n'), ((5222, 5257), 'numpy.where', 'np.where', (['((freq >= 0) & (freq <= 4))'], {}), '((freq >= 0) & (freq <= 4))\n', (5230, 5257), True, 'import numpy as np\n'), ((5285, 5322), 'numpy.where', 'np.where', (['((freq >= 4) & (freq <= 7.5))'], {}), '((freq >= 4) & (freq <= 7.5))\n', (5293, 5322), True, 'import numpy as np\n'), ((5350, 5390), 'numpy.where', 'np.where', (['((freq >= 7.5) & (freq <= 15.5))'], {}), '((freq >= 7.5) & (freq <= 15.5))\n', (5358, 5390), True, 'import numpy as np\n'), ((5417, 5456), 'numpy.where', 'np.where', (['((freq >= 15.5) & (freq <= 31))'], {}), '((freq >= 15.5) & (freq <= 31))\n', (5425, 5456), True, 'import numpy as np\n'), ((5484, 5504), 'numpy.where', 'np.where', (['(freq >= 31)'], {}), '(freq >= 31)\n', (5492, 5504), True, 'import numpy as np\n'), ((5782, 5811), 'numpy.concatenate', 'np.concatenate', (['example_feats'], {}), '(example_feats)\n', (5796, 5811), True, 'import numpy as np\n')]
import os import cv2 import numpy as np def find_image_files(input_dir): """ Recursively searches for .jpg/.png images. """ for root_dir, found_dirs, found_files in os.walk(input_dir): for found_file in found_files: if os.path.splitext(found_file)[-1].lower() in ['.jpg', '.png']: yield os.path.join(root_dir, found_file) def load_image(input_file, output_color_space='RGB'): """ Load image, normalize, and convert color space. """ if not os.path.exists(input_file): raise IOError(input_file + ' does not exist or could not be loaded') input_image = cv2.imread(input_file).astype(np.float32) / 255 if output_color_space == 'BGR': output_image = input_image elif output_color_space == 'RGB': output_image = cv2.cvtColor(input_image, cv2.COLOR_BGR2RGB) elif output_color_space == 'GRAY': output_image = cv2.cvtColor(input_image, cv2.COLOR_BGR2GRAY) elif output_color_space == 'HSV': output_image = cv2.cvtColor(input_image, cv2.COLOR_BGR2HSV) elif output_color_space == 'LUV': output_image = cv2.cvtColor(input_image, cv2.COLOR_BGR2LUV) elif output_color_space == 'YUV': output_image = cv2.cvtColor(input_image, cv2.COLOR_BGR2YUV) elif output_color_space == 'YCrCb': output_image = cv2.cvtColor(input_image, cv2.COLOR_BGR2YCrCb) else: raise IOError('invalid color_space: {}'.format(output_color_space)) return output_image def save_image(input_image, output_path, output_type=None, input_color_space='RGB'): """ Convert color space, de-normalize and save image. """ if input_image.dtype != np.uint8: input_image = (input_image * 255).astype(np.uint8) if input_color_space == 'BGR': output_image = input_image elif input_color_space == 'RGB': output_image = cv2.cvtColor(input_image, cv2.COLOR_RGB2BGR) elif input_color_space == 'GRAY': output_image = cv2.cvtColor(input_image, cv2.COLOR_GRAY2BGR) elif input_color_space == 'HSV': output_image = cv2.cvtColor(input_image, cv2.COLOR_HSV2BGR) elif input_color_space == 'LUV': output_image = cv2.cvtColor(input_image, cv2.COLOR_LUV2BGR) elif input_color_space == 'YUV': output_image = cv2.cvtColor(input_image, cv2.COLOR_YUV2BGR) elif input_color_space == 'YCrCb': output_image = cv2.cvtColor(input_image, cv2.COLOR_YCrCb2BGR) else: raise IOError('invalid color_space: {}'.format(input_color_space)) # Create directories output_dir = os.path.dirname(output_path) output_name = os.path.basename(output_path) output_base, output_ext = os.path.splitext(output_name) if not os.path.isdir(output_dir): os.makedirs(output_dir) # Save files if output_type is None: cv2.imwrite(os.path.join(output_dir, '{}.png'.format(output_base)), output_image) else: type_dir = '{}/by_type/{}'.format(output_dir, output_type) if not os.path.isdir(type_dir): os.makedirs(type_dir) name_dir = '{}/by_name/{}'.format(output_dir, output_base) if not os.path.isdir(name_dir): os.makedirs(name_dir) cv2.imwrite( os.path.join(type_dir, '{}_{}.png'.format(output_base, output_type)), output_image) cv2.imwrite( os.path.join(name_dir, '{}_{}.png'.format(output_base, output_type)), output_image) def get_image_histogram(input_image, histogram_bins=32, bins_range=(0, 256)): """ Builds image histogram. """ return np.concatenate( [np.histogram(input_image[:, :, input_channel], histogram_bins, bins_range)[0] for input_channel in range(input_image.shape[-1])]) / (input_image.shape[0] * input_image.shape[1]) def resize_and_vectorize_image(input_image, output_size=(32, 32)): """ Scale and vectorize image. """ return cv2.resize(input_image, output_size).ravel() def convert_video_colorspace(input_frame, output_color_space='RGB'): """ Convert video frame color space. """ if input_frame.dtype != np.float32: input_frame = input_frame.astype(np.float32) / 255 if output_color_space == 'RGB': output_frame = input_frame elif output_color_space == 'GRAY': output_frame = cv2.cvtColor(input_frame, cv2.COLOR_RGB2GRAY) elif output_color_space == 'BGR': output_frame = cv2.cvtColor(input_frame, cv2.COLOR_RGB2BGR) elif output_color_space == 'HSV': output_frame = cv2.cvtColor(input_frame, cv2.COLOR_RGB2HSV) elif output_color_space == 'LUV': output_frame = cv2.cvtColor(input_frame, cv2.COLOR_RGB2LUV) elif output_color_space == 'YUV': output_frame = cv2.cvtColor(input_frame, cv2.COLOR_RGB2YUV) elif output_color_space == 'YCrCb': output_frame = cv2.cvtColor(input_frame, cv2.COLOR_RGB2YCrCb) else: raise IOError('invalid color_space: {}'.format(output_color_space)) return output_frame def convert_image_to_rgb(input_image, input_color_space): """ Convert image color space. """ if input_color_space == 'GRAY': output_image = cv2.cvtColor(input_image, cv2.COLOR_GRAY2RGB) elif input_color_space == 'BGR': output_image = cv2.cvtColor(input_image, cv2.COLOR_BGR2RGB) elif input_color_space == 'HSV': output_image = cv2.cvtColor(input_image, cv2.COLOR_HSV2RGB) elif input_color_space == 'LUV': output_image = cv2.cvtColor(input_image, cv2.COLOR_LUV2RGB) elif input_color_space == 'YUV': output_image = cv2.cvtColor(input_image, cv2.COLOR_YUV2RGB) elif input_color_space == 'YCrCb': output_image = cv2.cvtColor(input_image, cv2.COLOR_YCrCb2RGB) else: raise IOError('invalid color_space: {}'.format(input_color_space)) if output_image.dtype != np.uint8: output_image = (output_image * 255).astype(np.uint8) return output_image
[ "os.path.exists", "numpy.histogram", "os.makedirs", "os.path.splitext", "os.path.join", "os.path.dirname", "os.path.isdir", "os.path.basename", "cv2.cvtColor", "cv2.resize", "cv2.imread", "os.walk" ]
[((184, 202), 'os.walk', 'os.walk', (['input_dir'], {}), '(input_dir)\n', (191, 202), False, 'import os\n'), ((2655, 2683), 'os.path.dirname', 'os.path.dirname', (['output_path'], {}), '(output_path)\n', (2670, 2683), False, 'import os\n'), ((2702, 2731), 'os.path.basename', 'os.path.basename', (['output_path'], {}), '(output_path)\n', (2718, 2731), False, 'import os\n'), ((2762, 2791), 'os.path.splitext', 'os.path.splitext', (['output_name'], {}), '(output_name)\n', (2778, 2791), False, 'import os\n'), ((527, 553), 'os.path.exists', 'os.path.exists', (['input_file'], {}), '(input_file)\n', (541, 553), False, 'import os\n'), ((2804, 2829), 'os.path.isdir', 'os.path.isdir', (['output_dir'], {}), '(output_dir)\n', (2817, 2829), False, 'import os\n'), ((2839, 2862), 'os.makedirs', 'os.makedirs', (['output_dir'], {}), '(output_dir)\n', (2850, 2862), False, 'import os\n'), ((5337, 5382), 'cv2.cvtColor', 'cv2.cvtColor', (['input_image', 'cv2.COLOR_GRAY2RGB'], {}), '(input_image, cv2.COLOR_GRAY2RGB)\n', (5349, 5382), False, 'import cv2\n'), ((830, 874), 'cv2.cvtColor', 'cv2.cvtColor', (['input_image', 'cv2.COLOR_BGR2RGB'], {}), '(input_image, cv2.COLOR_BGR2RGB)\n', (842, 874), False, 'import cv2\n'), ((1951, 1995), 'cv2.cvtColor', 'cv2.cvtColor', (['input_image', 'cv2.COLOR_RGB2BGR'], {}), '(input_image, cv2.COLOR_RGB2BGR)\n', (1963, 1995), False, 'import cv2\n'), ((3091, 3114), 'os.path.isdir', 'os.path.isdir', (['type_dir'], {}), '(type_dir)\n', (3104, 3114), False, 'import os\n'), ((3128, 3149), 'os.makedirs', 'os.makedirs', (['type_dir'], {}), '(type_dir)\n', (3139, 3149), False, 'import os\n'), ((3232, 3255), 'os.path.isdir', 'os.path.isdir', (['name_dir'], {}), '(name_dir)\n', (3245, 3255), False, 'import os\n'), ((3269, 3290), 'os.makedirs', 'os.makedirs', (['name_dir'], {}), '(name_dir)\n', (3280, 3290), False, 'import os\n'), ((4024, 4060), 'cv2.resize', 'cv2.resize', (['input_image', 'output_size'], {}), '(input_image, output_size)\n', (4034, 4060), False, 'import cv2\n'), ((4455, 4500), 'cv2.cvtColor', 'cv2.cvtColor', (['input_frame', 'cv2.COLOR_RGB2GRAY'], {}), '(input_frame, cv2.COLOR_RGB2GRAY)\n', (4467, 4500), False, 'import cv2\n'), ((5443, 5487), 'cv2.cvtColor', 'cv2.cvtColor', (['input_image', 'cv2.COLOR_BGR2RGB'], {}), '(input_image, cv2.COLOR_BGR2RGB)\n', (5455, 5487), False, 'import cv2\n'), ((650, 672), 'cv2.imread', 'cv2.imread', (['input_file'], {}), '(input_file)\n', (660, 672), False, 'import cv2\n'), ((937, 982), 'cv2.cvtColor', 'cv2.cvtColor', (['input_image', 'cv2.COLOR_BGR2GRAY'], {}), '(input_image, cv2.COLOR_BGR2GRAY)\n', (949, 982), False, 'import cv2\n'), ((2057, 2102), 'cv2.cvtColor', 'cv2.cvtColor', (['input_image', 'cv2.COLOR_GRAY2BGR'], {}), '(input_image, cv2.COLOR_GRAY2BGR)\n', (2069, 2102), False, 'import cv2\n'), ((4562, 4606), 'cv2.cvtColor', 'cv2.cvtColor', (['input_frame', 'cv2.COLOR_RGB2BGR'], {}), '(input_frame, cv2.COLOR_RGB2BGR)\n', (4574, 4606), False, 'import cv2\n'), ((5548, 5592), 'cv2.cvtColor', 'cv2.cvtColor', (['input_image', 'cv2.COLOR_HSV2RGB'], {}), '(input_image, cv2.COLOR_HSV2RGB)\n', (5560, 5592), False, 'import cv2\n'), ((342, 376), 'os.path.join', 'os.path.join', (['root_dir', 'found_file'], {}), '(root_dir, found_file)\n', (354, 376), False, 'import os\n'), ((1044, 1088), 'cv2.cvtColor', 'cv2.cvtColor', (['input_image', 'cv2.COLOR_BGR2HSV'], {}), '(input_image, cv2.COLOR_BGR2HSV)\n', (1056, 1088), False, 'import cv2\n'), ((2163, 2207), 'cv2.cvtColor', 'cv2.cvtColor', (['input_image', 'cv2.COLOR_HSV2BGR'], {}), '(input_image, cv2.COLOR_HSV2BGR)\n', (2175, 2207), False, 'import cv2\n'), ((3710, 3784), 'numpy.histogram', 'np.histogram', (['input_image[:, :, input_channel]', 'histogram_bins', 'bins_range'], {}), '(input_image[:, :, input_channel], histogram_bins, bins_range)\n', (3722, 3784), True, 'import numpy as np\n'), ((4668, 4712), 'cv2.cvtColor', 'cv2.cvtColor', (['input_frame', 'cv2.COLOR_RGB2HSV'], {}), '(input_frame, cv2.COLOR_RGB2HSV)\n', (4680, 4712), False, 'import cv2\n'), ((5653, 5697), 'cv2.cvtColor', 'cv2.cvtColor', (['input_image', 'cv2.COLOR_LUV2RGB'], {}), '(input_image, cv2.COLOR_LUV2RGB)\n', (5665, 5697), False, 'import cv2\n'), ((1150, 1194), 'cv2.cvtColor', 'cv2.cvtColor', (['input_image', 'cv2.COLOR_BGR2LUV'], {}), '(input_image, cv2.COLOR_BGR2LUV)\n', (1162, 1194), False, 'import cv2\n'), ((2268, 2312), 'cv2.cvtColor', 'cv2.cvtColor', (['input_image', 'cv2.COLOR_LUV2BGR'], {}), '(input_image, cv2.COLOR_LUV2BGR)\n', (2280, 2312), False, 'import cv2\n'), ((4774, 4818), 'cv2.cvtColor', 'cv2.cvtColor', (['input_frame', 'cv2.COLOR_RGB2LUV'], {}), '(input_frame, cv2.COLOR_RGB2LUV)\n', (4786, 4818), False, 'import cv2\n'), ((5758, 5802), 'cv2.cvtColor', 'cv2.cvtColor', (['input_image', 'cv2.COLOR_YUV2RGB'], {}), '(input_image, cv2.COLOR_YUV2RGB)\n', (5770, 5802), False, 'import cv2\n'), ((258, 286), 'os.path.splitext', 'os.path.splitext', (['found_file'], {}), '(found_file)\n', (274, 286), False, 'import os\n'), ((1256, 1300), 'cv2.cvtColor', 'cv2.cvtColor', (['input_image', 'cv2.COLOR_BGR2YUV'], {}), '(input_image, cv2.COLOR_BGR2YUV)\n', (1268, 1300), False, 'import cv2\n'), ((2373, 2417), 'cv2.cvtColor', 'cv2.cvtColor', (['input_image', 'cv2.COLOR_YUV2BGR'], {}), '(input_image, cv2.COLOR_YUV2BGR)\n', (2385, 2417), False, 'import cv2\n'), ((4880, 4924), 'cv2.cvtColor', 'cv2.cvtColor', (['input_frame', 'cv2.COLOR_RGB2YUV'], {}), '(input_frame, cv2.COLOR_RGB2YUV)\n', (4892, 4924), False, 'import cv2\n'), ((5865, 5911), 'cv2.cvtColor', 'cv2.cvtColor', (['input_image', 'cv2.COLOR_YCrCb2RGB'], {}), '(input_image, cv2.COLOR_YCrCb2RGB)\n', (5877, 5911), False, 'import cv2\n'), ((1364, 1410), 'cv2.cvtColor', 'cv2.cvtColor', (['input_image', 'cv2.COLOR_BGR2YCrCb'], {}), '(input_image, cv2.COLOR_BGR2YCrCb)\n', (1376, 1410), False, 'import cv2\n'), ((2480, 2526), 'cv2.cvtColor', 'cv2.cvtColor', (['input_image', 'cv2.COLOR_YCrCb2BGR'], {}), '(input_image, cv2.COLOR_YCrCb2BGR)\n', (2492, 2526), False, 'import cv2\n'), ((4988, 5034), 'cv2.cvtColor', 'cv2.cvtColor', (['input_frame', 'cv2.COLOR_RGB2YCrCb'], {}), '(input_frame, cv2.COLOR_RGB2YCrCb)\n', (5000, 5034), False, 'import cv2\n')]
""" Program's entry-point :authors: [<NAME>, <NAME>, <NAME>] :url: https://github.com/pBouillon/TELECOM_TAN :license: [MIT](https://github.com/pBouillon/TELECOM_TAN/blob/master/LICENSE) """ import matplotlib.pyplot as plt import pyaudio import numpy as np from utils.constants import * from utils.data_objects import Sample, Phoneme, Spectrum from utils.sound_utils import wav_to_normalized_h_1, wav_to_normalized_h_2, h_2, \ scalar_product, h_1 from utils.easy_thread import ThreadPool, DebugLevel """Default audio file to load """ DEFAULT_PLAYED_FILE = './assets/o_pbouillon_3.wav' PHONEMES = [ "a", "an", "e", "i", "in", "o", "on", "ou", "u", "è", "é" ] AUTHORS = [ {"name": "pbouillon", "style": "-."}, {"name": "fvogt", "style": "-"}, # {"name": "tbagrel", "style": "--"} ] PITCHES = [ {"num": 1, "color": "orangered"}, {"num": 2, "color": "red"}, {"num": 3, "color": "brown"} ] FORMAT = pyaudio.paInt16 CHANNELS = 1 RATE = 44100 def record(): input("Press enter to start recording...") stop = False def ask_for_stop(): nonlocal stop input("Press enter to stop recording...") stop = True audio = pyaudio.PyAudio() stream = audio.open( format=FORMAT, channels=CHANNELS, rate=RATE, input=True, frames_per_buffer=N_2) ThreadPool(debug_level=DebugLevel.ERROR).add(1, ask_for_stop) dt = np.dtype("i2") while not stop: data = np.frombuffer(stream.read(N_2), dtype=dt) yield data BLANK_STD_THRESHOLD = 300 def is_blank(sample): std = np.std(sample) print(std) return std < BLANK_STD_THRESHOLD def drop_blanks(record_gen): for i, sample in enumerate(record_gen): if i > 1 and not is_blank(sample): yield sample def process_samples(record_gen): for sample in record_gen: yield h_2(Sample( phoneme=Phoneme.UNKNOWN, file_name='<audio input stream>', data=sample )) from time import time import os from os import path import wave NEW_SAMPLES_STORE = "./assets/new" ASSETS_SAMPLES_STORE = "./assets/samples/" def record_and_store(): hs = [] for i, h in enumerate(process_samples(drop_blanks(record()))): hs.append(h.data) hs = np.array(hs) h_avg = hs.mean(0) phoneme = input("Phoneme : ") if phoneme not in PHONEMES: print("\"{}\" n'est pas reconnu. Réessayez.".format(phoneme)) phoneme = input("Phoneme : ") filename = "{}_{}".format(phoneme, int(time())) filepath = path.join(NEW_SAMPLES_STORE, filename) plt.plot(h_avg) plt.show() if input("Est-ce un bon échantillon ? (Y/N)") in 'YOyo': np.save(filepath, h_avg) print("Phonème enregistré sous le nom {}".format(filepath)) else: print("Phonème non enregistré") def load_samples(): data_bank = [] for r, d, f in os.walk(NEW_SAMPLES_STORE): for filepath in f: filename = path.basename(filepath) if filename.startswith("."): continue phoneme = filename.split("_")[0] assert(phoneme in PHONEMES) data_bank.append(Spectrum( data=np.load(path.join(NEW_SAMPLES_STORE,filepath)), freq=None, file_name=filepath, phoneme=Phoneme(phoneme) )) return data_bank def convert_wav_to_npy(save = True, forceSave = False): def convert(wav_filename, save = True, forcesave = False): hs = [] def record(): t = 0.0 wf = wave.open(wav_filename, 'rb') dt = np.dtype("i2") while t < 3: raw_data = wf.readframes(N_2) # print(type(raw_data), len(raw_data)) if len(raw_data) < 2 * N_2: break data = np.frombuffer(raw_data, dtype=dt) t += T yield data for i, h in enumerate(process_samples(drop_blanks(record()))): hs.append(h.data) hs = np.array(hs) h_avg = hs.mean(0) wav_filename_splitted = path.basename(wav_filename).split('_') phoneme = wav_filename_splitted[0] if phoneme not in PHONEMES: print("\"{}\" n'est pas reconnu. Réessayez.".format(phoneme)) phoneme = input("Phoneme : ") else: print("Fichier traité : {}".format(wav_filename)) filename = wav_filename filepath = path.join(NEW_SAMPLES_STORE, path.basename(filename)) if not forcesave: plt.plot(h_avg) plt.show() if forcesave or save and input("Est-ce un bon échantillon ? (Y/N)") in 'YOyo': np.save(filepath, h_avg) print("Phonème enregistré sous le nom {}".format(filepath)) else: print("Phonème non enregistré") for r, d, f in os.walk(ASSETS_SAMPLES_STORE): for fp in f: convert(path.join(r, path.basename(fp)), save, forceSave) print("Went through all wav files c:") def main_2(): data_bank = load_samples() while True: results = {} count = {} hs = [] for phoneme in PHONEMES: results[phoneme] = 0.0 count[phoneme] = 0 for i, h in enumerate(process_samples(drop_blanks(record()))): hs.append(h.data) hs = np.array(hs) h_avg = hs.mean(0) best_result = 0 best_hh_data = None best_hh = None best_phoneme = None for hh in data_bank: score = float(scalar_product(h_avg, hh.data)) print(h_avg.shape, hh.data.shape, type(score), score) print(hh.file_name) if score > best_result: best_hh = hh best_hh_data = hh.data best_result = score best_phoneme = hh.phoneme.value print("Identified: {} with score {} --> {}".format(best_phoneme, best_result, best_hh.file_name)) plt.plot(np.arange(len(h_avg)), h_avg, '-r', np.arange(len(h_avg)), best_hh_data, '-.b') plt.show() def main_1(): # fig, axs = plt.subplots(3, 4) data_bank = [] for i, phoneme in enumerate(PHONEMES): # ax = axs[i // 4, i % 4] # ax.set_title(f'Phonème {phoneme}') for pitch in PITCHES: for author in AUTHORS: played_file = f'./assets/{phoneme}_{author["name"]}_{pitch["num"]}.wav' print(f'# Phonème {phoneme} par {author["name"]} : pitch {pitch["num"]}') h = wav_to_normalized_h_2(played_file) # ax.plot(h.freq, h.data, linestyle=author["style"], color=pitch["color"]) data_bank.append(h) # plt.show() while True: results = {} count = {} hs = [] for phoneme in PHONEMES: results[phoneme] = 0.0 count[phoneme] = 0 for i, h in enumerate(process_samples(drop_blanks(record()))): hs.append(h.data) for hh in data_bank: results[hh.phoneme.value] += scalar_product(h, hh) ** 2 count[hh.phoneme.value] += 1 for phoneme in PHONEMES: if count[phoneme] != 0: results[phoneme] /= count[phoneme] best_result = 0 best_phoneme = None for phoneme in PHONEMES: if results[phoneme] > best_result: best_phoneme = phoneme best_result = results[phoneme] print("Identified: {} with score {}".format(best_phoneme, best_result)) print(results) hs = np.array(hs) h_avg = hs.mean(0) plt.plot(h_avg) plt.show() def main_main(): method = input("""Please enter your choice : To recognize a Phonem : (1) Use assets base (2) Use live (recorded) base --------------------- Configurations : (3) Add a sound to the live base (4) Convert all assets ressources to live base\n""") if method == '1': main_1() elif method == '2': main_2() elif method == '3': while(True): record_and_store() elif method == '4': convert_wav_to_npy(False, forceSave = True) else: print("Didn't recognized your input : {}".format(method)) if __name__ == "__main__": main_main()
[ "utils.data_objects.Phoneme", "wave.open", "utils.sound_utils.scalar_product", "matplotlib.pyplot.plot", "os.path.join", "numpy.array", "utils.easy_thread.ThreadPool", "utils.data_objects.Sample", "os.path.basename", "numpy.save", "numpy.std", "utils.sound_utils.wav_to_normalized_h_2", "nump...
[((1201, 1218), 'pyaudio.PyAudio', 'pyaudio.PyAudio', ([], {}), '()\n', (1216, 1218), False, 'import pyaudio\n'), ((1425, 1439), 'numpy.dtype', 'np.dtype', (['"""i2"""'], {}), "('i2')\n", (1433, 1439), True, 'import numpy as np\n'), ((1599, 1613), 'numpy.std', 'np.std', (['sample'], {}), '(sample)\n', (1605, 1613), True, 'import numpy as np\n'), ((2302, 2314), 'numpy.array', 'np.array', (['hs'], {}), '(hs)\n', (2310, 2314), True, 'import numpy as np\n'), ((2579, 2617), 'os.path.join', 'path.join', (['NEW_SAMPLES_STORE', 'filename'], {}), '(NEW_SAMPLES_STORE, filename)\n', (2588, 2617), False, 'from os import path\n'), ((2622, 2637), 'matplotlib.pyplot.plot', 'plt.plot', (['h_avg'], {}), '(h_avg)\n', (2630, 2637), True, 'import matplotlib.pyplot as plt\n'), ((2642, 2652), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2650, 2652), True, 'import matplotlib.pyplot as plt\n'), ((2924, 2950), 'os.walk', 'os.walk', (['NEW_SAMPLES_STORE'], {}), '(NEW_SAMPLES_STORE)\n', (2931, 2950), False, 'import os\n'), ((4939, 4968), 'os.walk', 'os.walk', (['ASSETS_SAMPLES_STORE'], {}), '(ASSETS_SAMPLES_STORE)\n', (4946, 4968), False, 'import os\n'), ((2722, 2746), 'numpy.save', 'np.save', (['filepath', 'h_avg'], {}), '(filepath, h_avg)\n', (2729, 2746), True, 'import numpy as np\n'), ((4101, 4113), 'numpy.array', 'np.array', (['hs'], {}), '(hs)\n', (4109, 4113), True, 'import numpy as np\n'), ((5461, 5473), 'numpy.array', 'np.array', (['hs'], {}), '(hs)\n', (5469, 5473), True, 'import numpy as np\n'), ((6198, 6208), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (6206, 6208), True, 'import matplotlib.pyplot as plt\n'), ((7732, 7744), 'numpy.array', 'np.array', (['hs'], {}), '(hs)\n', (7740, 7744), True, 'import numpy as np\n'), ((7780, 7795), 'matplotlib.pyplot.plot', 'plt.plot', (['h_avg'], {}), '(h_avg)\n', (7788, 7795), True, 'import matplotlib.pyplot as plt\n'), ((7804, 7814), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (7812, 7814), True, 'import matplotlib.pyplot as plt\n'), ((1353, 1393), 'utils.easy_thread.ThreadPool', 'ThreadPool', ([], {'debug_level': 'DebugLevel.ERROR'}), '(debug_level=DebugLevel.ERROR)\n', (1363, 1393), False, 'from utils.easy_thread import ThreadPool, DebugLevel\n'), ((2555, 2561), 'time.time', 'time', ([], {}), '()\n', (2559, 2561), False, 'from time import time\n'), ((3002, 3025), 'os.path.basename', 'path.basename', (['filepath'], {}), '(filepath)\n', (3015, 3025), False, 'from os import path\n'), ((3620, 3649), 'wave.open', 'wave.open', (['wav_filename', '"""rb"""'], {}), "(wav_filename, 'rb')\n", (3629, 3649), False, 'import wave\n'), ((3668, 3682), 'numpy.dtype', 'np.dtype', (['"""i2"""'], {}), "('i2')\n", (3676, 3682), True, 'import numpy as np\n'), ((4563, 4586), 'os.path.basename', 'path.basename', (['filename'], {}), '(filename)\n', (4576, 4586), False, 'from os import path\n'), ((4626, 4641), 'matplotlib.pyplot.plot', 'plt.plot', (['h_avg'], {}), '(h_avg)\n', (4634, 4641), True, 'import matplotlib.pyplot as plt\n'), ((4654, 4664), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4662, 4664), True, 'import matplotlib.pyplot as plt\n'), ((4764, 4788), 'numpy.save', 'np.save', (['filepath', 'h_avg'], {}), '(filepath, h_avg)\n', (4771, 4788), True, 'import numpy as np\n'), ((1892, 1970), 'utils.data_objects.Sample', 'Sample', ([], {'phoneme': 'Phoneme.UNKNOWN', 'file_name': '"""<audio input stream>"""', 'data': 'sample'}), "(phoneme=Phoneme.UNKNOWN, file_name='<audio input stream>', data=sample)\n", (1898, 1970), False, 'from utils.data_objects import Sample, Phoneme, Spectrum\n'), ((3902, 3935), 'numpy.frombuffer', 'np.frombuffer', (['raw_data'], {'dtype': 'dt'}), '(raw_data, dtype=dt)\n', (3915, 3935), True, 'import numpy as np\n'), ((4173, 4200), 'os.path.basename', 'path.basename', (['wav_filename'], {}), '(wav_filename)\n', (4186, 4200), False, 'from os import path\n'), ((5668, 5698), 'utils.sound_utils.scalar_product', 'scalar_product', (['h_avg', 'hh.data'], {}), '(h_avg, hh.data)\n', (5682, 5698), False, 'from utils.sound_utils import wav_to_normalized_h_1, wav_to_normalized_h_2, h_2, scalar_product, h_1\n'), ((6670, 6704), 'utils.sound_utils.wav_to_normalized_h_2', 'wav_to_normalized_h_2', (['played_file'], {}), '(played_file)\n', (6691, 6704), False, 'from utils.sound_utils import wav_to_normalized_h_1, wav_to_normalized_h_2, h_2, scalar_product, h_1\n'), ((5024, 5041), 'os.path.basename', 'path.basename', (['fp'], {}), '(fp)\n', (5037, 5041), False, 'from os import path\n'), ((7202, 7223), 'utils.sound_utils.scalar_product', 'scalar_product', (['h', 'hh'], {}), '(h, hh)\n', (7216, 7223), False, 'from utils.sound_utils import wav_to_normalized_h_1, wav_to_normalized_h_2, h_2, scalar_product, h_1\n'), ((3372, 3388), 'utils.data_objects.Phoneme', 'Phoneme', (['phoneme'], {}), '(phoneme)\n', (3379, 3388), False, 'from utils.data_objects import Sample, Phoneme, Spectrum\n'), ((3245, 3283), 'os.path.join', 'path.join', (['NEW_SAMPLES_STORE', 'filepath'], {}), '(NEW_SAMPLES_STORE, filepath)\n', (3254, 3283), False, 'from os import path\n')]
import argparse import numpy as np import gym import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F from utils import logz from utils.tools import get_output_folder, OUNoise, hard_update, soft_update from utils.buffer import ReplayBuffer FloatTensor = torch.FloatTensor """ Actor 和 Critic 分开训练 """ class Actor(nn.Module): def __init__(self, state_dim, action_dim, max_action, args): super(Actor, self).__init__() self.l1 = nn.Linear(state_dim, action_dim, bias=False) self.max_action = max_action self.optim = optim.Adam(self.parameters(), lr=args.critic_lr) self.loss = nn.MSELoss() def forward(self, x): out = self.l1(x) # abs_out = torch.abs(out) # abs_out_sum = torch.sum(abs_out).view(-1, 1) # abs_out_mean = abs_out_sum / self.action_dim / self.theta # ones = torch.ones(abs_out_mean.size()) # ones = ones.cuda() # mod = torch.where(abs_out_mean >= 1, abs_out_mean, ones) # out = out / mod # out = self.max_action * torch.tanh(out) return out def update(self, memory, batch_size, critic, actor_t): # Sample replay buffer states, _, _, _, _ = memory.sample(batch_size) # Compute actor loss actor_loss = - critic(states, self(states)).mean() # Optimize the policy self.optim.zero_grad() actor_loss.backward() self.optim.step() grads = self.get_grads() # Get policy gradients return grads def get_grads(self): grads = [v.grad.data.numpy() for v in self.parameters()] return grads[0] def get_params(self): params = [v.data.numpy() for v in self.parameters()] return params[0] def set_params(self, w): for i, param in enumerate(self.parameters()): param.data.copy_(torch.from_numpy(w).view(param.size())) class Critic(nn.Module): def __init__(self, state_dim, action_dim, args): super(Critic, self).__init__() l1_dim, l2_dim = 400, 300 self.l1 = nn.Linear(state_dim + action_dim, l1_dim) self.l2 = nn.Linear(l1_dim, l2_dim) self.l3 = nn.Linear(l2_dim, 1) if args.layer_norm: self.n1 = nn.LayerNorm(l1_dim) self.n2 = nn.LayerNorm(l2_dim) self.layer_norm = args.layer_norm self.discount = args.discount self.optim = optim.Adam(self.parameters(), lr=args.critic_lr) self.loss = nn.MSELoss() def forward(self, x, u): if not self.layer_norm: x = F.leaky_relu(self.l1(torch.cat([x, u], 1))) x = F.leaky_relu(self.l2(x)) x = self.l3(x) else: x = F.leaky_relu(self.n1(self.l1(torch.cat([x, u], 1)))) x = F.leaky_relu(self.n2(self.l2(x))) x = self.l3(x) return x def update(self, buffer, batch_size, actor_t, critic_t): # Sample replay buffer states, n_states, actions, rewards, dones = buffer.sample(batch_size) # Compute q target next_q = critic_t(n_states, actor_t(n_states)) q_target = (rewards + self.discount * (1 - dones.float()) * next_q).detach() # Compute q predict q_predict = self(states, actions) # Compute critic loss critic_loss = self.loss(q_target, q_predict) # Optimize the critic self.optim.zero_grad() critic_loss.backward() self.optim.step() class DDPG: def __init__(self, state_dim, action_dim, max_action, args): self.state_dim = state_dim self.action_dim = action_dim self.max_action = max_action self._init_parameters(args) self._init_nets(args) self.replay_buffer = ReplayBuffer(self.buffer_size, self.state_dim, self.action_dim) def _init_parameters(self, args): self.actor_lr = args.actor_lr self.critic_lr = args.critic_lr self.discount = args.discount self.tau = args.tau self.buffer_size = args.buffer_size self.batch_size = args.batch_size def _init_nets(self, args): self.actor = Actor(self.state_dim, self.action_dim, self.max_action, args) self.actor_t = Actor(self.state_dim, self.action_dim, self.max_action, args) self.critic = Critic(self.state_dim, self.action_dim, args) self.critic_t = Critic(self.state_dim, self.action_dim, args) hard_update(self.actor_t, self.actor) hard_update(self.critic_t, self.critic) def train(self): self.critic.update(self.replay_buffer, self.batch_size, self.actor, self.critic_t) grad = self.actor.update(self.replay_buffer, self.batch_size, self.critic, self.actor_t) return grad def update_nets(self): soft_update(self.actor_t, self.actor, self.tau) soft_update(self.critic_t, self.critic, self.tau) def run(args): log_dir = args.dir_path env = gym.make(args.env) state_dim = env.observation_space.shape[0] action_dim = env.action_space.shape[0] max_action = int(env.action_space.high[0]) env.seed(args.seed) np.random.seed(args.seed) torch.manual_seed(args.seed) ddpg = DDPG(state_dim, action_dim, max_action, args) ounoise = OUNoise(action_dim) def get_action(state, noise=None): action = ddpg.actor(FloatTensor(state)) action = (action.data.numpy() + noise.add()) if noise else action.data.numpy() return np.clip(action, -max_action, max_action) def rollout(eval=False): state, done, ep_reward, ep_len = env.reset(), False, 0.0, 0 while not done and ep_len < args.max_ep_len: if not eval: action = get_action(state, noise=ounoise) else: action = get_action(state) next_state, reward, done, _ = env.step(action) if not eval: done = False if ep_len + 1 == args.max_ep_len else done ddpg.replay_buffer.store((state, next_state, action, reward, done)) ep_reward += reward ep_len += 1 state = next_state return ep_reward, ep_len for epoch in range(args.epochs): ep_reward, ep_len = rollout(eval=False) if epoch > args.start_epoch: for _ in range(ep_len): ddpg.train() ddpg.update_nets() if epoch % args.save_freq == 0: test_rewards = [] for i in range(10): reward, _ = rollout() test_rewards.append(reward) test_rewards = np.array(test_rewards) np.savez(log_dir + '/policy_weights', ddpg.actor.get_params()) logz.log_tabular("Epoch", epoch) logz.log_tabular("AverageTestReward", np.mean(test_rewards)) logz.log_tabular("StdTestRewards", np.std(test_rewards)) logz.log_tabular("MaxTestRewardRollout", np.max(test_rewards)) logz.log_tabular("MinTestRewardRollout", np.min(test_rewards)) logz.dump_tabular() if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--env', type=str, default='HalfCheetah-v2') # RL parameters parser.add_argument('--actor_lr', type=float, default=0.0001) parser.add_argument('--critic_lr', type=float, default=0.0001) parser.add_argument('--discount', type=float, default=0.99) parser.add_argument('--tau', type=float, default=0.005) parser.add_argument('--batch_size', type=int, default=100) parser.add_argument('--buffer_size', type=int, default=1000000) parser.add_argument('--max_ep_len', type=int, default=1000) parser.add_argument('--layer_norm', type=bool, default=True) parser.add_argument('--epochs', type=int, default=1000) parser.add_argument('--start_epoch', type=int, default=10) parser.add_argument('--save_freq', type=int, default=5) parser.add_argument('--seed', type=int, default=1) parser.add_argument('--dir_path', type=str, default='results_v1/') args = parser.parse_args() output_path = args.dir_path for seed in range(1, 11): args.seed = seed args.dir_path = get_output_folder(output_path, args.env, args.seed) logz.configure_output_dir(args.dir_path) logz.save_params(vars(args)) run(args)
[ "numpy.clip", "torch.from_numpy", "torch.nn.MSELoss", "numpy.array", "gym.make", "utils.logz.dump_tabular", "torch.tanh", "numpy.mean", "utils.buffer.ReplayBuffer", "argparse.ArgumentParser", "torch.nn.LayerNorm", "numpy.max", "utils.tools.hard_update", "utils.tools.OUNoise", "numpy.rand...
[((5011, 5029), 'gym.make', 'gym.make', (['args.env'], {}), '(args.env)\n', (5019, 5029), False, 'import gym\n'), ((5196, 5221), 'numpy.random.seed', 'np.random.seed', (['args.seed'], {}), '(args.seed)\n', (5210, 5221), True, 'import numpy as np\n'), ((5226, 5254), 'torch.manual_seed', 'torch.manual_seed', (['args.seed'], {}), '(args.seed)\n', (5243, 5254), False, 'import torch\n'), ((5327, 5346), 'utils.tools.OUNoise', 'OUNoise', (['action_dim'], {}), '(action_dim)\n', (5334, 5346), False, 'from utils.tools import get_output_folder, OUNoise, hard_update, soft_update\n'), ((7178, 7203), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (7201, 7203), False, 'import argparse\n'), ((496, 540), 'torch.nn.Linear', 'nn.Linear', (['state_dim', 'action_dim'], {'bias': '(False)'}), '(state_dim, action_dim, bias=False)\n', (505, 540), True, 'import torch.nn as nn\n'), ((668, 680), 'torch.nn.MSELoss', 'nn.MSELoss', ([], {}), '()\n', (678, 680), True, 'import torch.nn as nn\n'), ((2124, 2165), 'torch.nn.Linear', 'nn.Linear', (['(state_dim + action_dim)', 'l1_dim'], {}), '(state_dim + action_dim, l1_dim)\n', (2133, 2165), True, 'import torch.nn as nn\n'), ((2184, 2209), 'torch.nn.Linear', 'nn.Linear', (['l1_dim', 'l2_dim'], {}), '(l1_dim, l2_dim)\n', (2193, 2209), True, 'import torch.nn as nn\n'), ((2228, 2248), 'torch.nn.Linear', 'nn.Linear', (['l2_dim', '(1)'], {}), '(l2_dim, 1)\n', (2237, 2248), True, 'import torch.nn as nn\n'), ((2534, 2546), 'torch.nn.MSELoss', 'nn.MSELoss', ([], {}), '()\n', (2544, 2546), True, 'import torch.nn as nn\n'), ((3813, 3876), 'utils.buffer.ReplayBuffer', 'ReplayBuffer', (['self.buffer_size', 'self.state_dim', 'self.action_dim'], {}), '(self.buffer_size, self.state_dim, self.action_dim)\n', (3825, 3876), False, 'from utils.buffer import ReplayBuffer\n'), ((4496, 4533), 'utils.tools.hard_update', 'hard_update', (['self.actor_t', 'self.actor'], {}), '(self.actor_t, self.actor)\n', (4507, 4533), False, 'from utils.tools import get_output_folder, OUNoise, hard_update, soft_update\n'), ((4542, 4581), 'utils.tools.hard_update', 'hard_update', (['self.critic_t', 'self.critic'], {}), '(self.critic_t, self.critic)\n', (4553, 4581), False, 'from utils.tools import get_output_folder, OUNoise, hard_update, soft_update\n'), ((4848, 4895), 'utils.tools.soft_update', 'soft_update', (['self.actor_t', 'self.actor', 'self.tau'], {}), '(self.actor_t, self.actor, self.tau)\n', (4859, 4895), False, 'from utils.tools import get_output_folder, OUNoise, hard_update, soft_update\n'), ((4904, 4953), 'utils.tools.soft_update', 'soft_update', (['self.critic_t', 'self.critic', 'self.tau'], {}), '(self.critic_t, self.critic, self.tau)\n', (4915, 4953), False, 'from utils.tools import get_output_folder, OUNoise, hard_update, soft_update\n'), ((5537, 5577), 'numpy.clip', 'np.clip', (['action', '(-max_action)', 'max_action'], {}), '(action, -max_action, max_action)\n', (5544, 5577), True, 'import numpy as np\n'), ((8265, 8316), 'utils.tools.get_output_folder', 'get_output_folder', (['output_path', 'args.env', 'args.seed'], {}), '(output_path, args.env, args.seed)\n', (8282, 8316), False, 'from utils.tools import get_output_folder, OUNoise, hard_update, soft_update\n'), ((8325, 8365), 'utils.logz.configure_output_dir', 'logz.configure_output_dir', (['args.dir_path'], {}), '(args.dir_path)\n', (8350, 8365), False, 'from utils import logz\n'), ((1105, 1120), 'torch.tanh', 'torch.tanh', (['out'], {}), '(out)\n', (1115, 1120), False, 'import torch\n'), ((2300, 2320), 'torch.nn.LayerNorm', 'nn.LayerNorm', (['l1_dim'], {}), '(l1_dim)\n', (2312, 2320), True, 'import torch.nn as nn\n'), ((2343, 2363), 'torch.nn.LayerNorm', 'nn.LayerNorm', (['l2_dim'], {}), '(l2_dim)\n', (2355, 2363), True, 'import torch.nn as nn\n'), ((6667, 6689), 'numpy.array', 'np.array', (['test_rewards'], {}), '(test_rewards)\n', (6675, 6689), True, 'import numpy as np\n'), ((6778, 6810), 'utils.logz.log_tabular', 'logz.log_tabular', (['"""Epoch"""', 'epoch'], {}), "('Epoch', epoch)\n", (6794, 6810), False, 'from utils import logz\n'), ((7115, 7134), 'utils.logz.dump_tabular', 'logz.dump_tabular', ([], {}), '()\n', (7132, 7134), False, 'from utils import logz\n'), ((6861, 6882), 'numpy.mean', 'np.mean', (['test_rewards'], {}), '(test_rewards)\n', (6868, 6882), True, 'import numpy as np\n'), ((6931, 6951), 'numpy.std', 'np.std', (['test_rewards'], {}), '(test_rewards)\n', (6937, 6951), True, 'import numpy as np\n'), ((7006, 7026), 'numpy.max', 'np.max', (['test_rewards'], {}), '(test_rewards)\n', (7012, 7026), True, 'import numpy as np\n'), ((7081, 7101), 'numpy.min', 'np.min', (['test_rewards'], {}), '(test_rewards)\n', (7087, 7101), True, 'import numpy as np\n'), ((2646, 2666), 'torch.cat', 'torch.cat', (['[x, u]', '(1)'], {}), '([x, u], 1)\n', (2655, 2666), False, 'import torch\n'), ((1912, 1931), 'torch.from_numpy', 'torch.from_numpy', (['w'], {}), '(w)\n', (1928, 1931), False, 'import torch\n'), ((2796, 2816), 'torch.cat', 'torch.cat', (['[x, u]', '(1)'], {}), '([x, u], 1)\n', (2805, 2816), False, 'import torch\n')]
import sys import numpy as np import scipy.ndimage import matplotlib.pyplot as plt import soundfile # Test of pitch-shift quality without PVC if __name__ == "__main__": block_size = 4096 n_blocks = 4 FILT_SIZE = 8 if len(sys.argv) < 5: print( "Usage: {} <in_filename> <out_filename> <length_mult> <pitch_mult> [block_size={}] [n_blocks={}]".format( sys.argv[0], block_size, n_blocks ) ) sys.exit() in_filename = sys.argv[1] out_filename = sys.argv[2] length_mult = float(sys.argv[3]) pitch_mult = float(sys.argv[4]) if len(sys.argv) >= 6: block_size = int(sys.argv[5]) if len(sys.argv) >= 7: n_blocks = int(sys.argv[6]) in_shift = block_size // n_blocks out_shift = int(in_shift * length_mult) in_file = soundfile.SoundFile(in_filename) rate = in_file.samplerate n_blocks = np.ceil(in_file.frames / in_shift) out_length = int(n_blocks * out_shift + block_size) # print("from", in_file.frames, "to", out_length) out_data = np.zeros((out_length, in_file.channels)) indices = np.arange(block_size // 2 + 1) window = np.hanning(block_size) t = 0 for block in in_file.blocks( blocksize=block_size, overlap=(block_size - in_shift), always_2d=True ): if block.shape[0] != block_size: block = np.pad(block, ((0, block_size - block.shape[0]), (0, 0))) for channel in range(in_file.channels): fft = np.fft.rfft(block[:, channel] * window) fft_mag = np.abs(fft) fft_phase = np.angle(fft) if pitch_mult != 1: contour = np.maximum( scipy.ndimage.maximum_filter1d(fft_mag, FILT_SIZE), 0.001 ) # plt.plot(contour) # plt.plot(magnitude) # plt.show() fft_mag = fft_mag / contour # stretch or squeeze in the frequency domain to perform pitch shifting fft_mag = np.interp(indices / pitch_mult, indices, fft_mag, 0, 0) fft_phase = np.interp( indices / pitch_mult, indices, fft_phase, period=np.pi * 2 ) # phase = np.interp(indices/pitch_mult,indices,fft_phase,period=np.pi*2) fft_mag = fft_mag * contour fft = fft_mag * np.exp(1j * fft_phase) out_block = np.fft.irfft(fft) * window out_data[t : t + block_size, channel] += out_block t += out_shift out_data = out_data / np.max(np.abs(out_data)) soundfile.write(out_filename, out_data, rate) in_file.close()
[ "numpy.hanning", "numpy.abs", "numpy.ceil", "numpy.fft.irfft", "numpy.angle", "soundfile.write", "numpy.fft.rfft", "numpy.zeros", "numpy.exp", "numpy.interp", "sys.exit", "numpy.pad", "soundfile.SoundFile", "numpy.arange" ]
[((845, 877), 'soundfile.SoundFile', 'soundfile.SoundFile', (['in_filename'], {}), '(in_filename)\n', (864, 877), False, 'import soundfile\n'), ((924, 958), 'numpy.ceil', 'np.ceil', (['(in_file.frames / in_shift)'], {}), '(in_file.frames / in_shift)\n', (931, 958), True, 'import numpy as np\n'), ((1086, 1126), 'numpy.zeros', 'np.zeros', (['(out_length, in_file.channels)'], {}), '((out_length, in_file.channels))\n', (1094, 1126), True, 'import numpy as np\n'), ((1142, 1172), 'numpy.arange', 'np.arange', (['(block_size // 2 + 1)'], {}), '(block_size // 2 + 1)\n', (1151, 1172), True, 'import numpy as np\n'), ((1187, 1209), 'numpy.hanning', 'np.hanning', (['block_size'], {}), '(block_size)\n', (1197, 1209), True, 'import numpy as np\n'), ((2642, 2687), 'soundfile.write', 'soundfile.write', (['out_filename', 'out_data', 'rate'], {}), '(out_filename, out_data, rate)\n', (2657, 2687), False, 'import soundfile\n'), ((472, 482), 'sys.exit', 'sys.exit', ([], {}), '()\n', (480, 482), False, 'import sys\n'), ((1400, 1457), 'numpy.pad', 'np.pad', (['block', '((0, block_size - block.shape[0]), (0, 0))'], {}), '(block, ((0, block_size - block.shape[0]), (0, 0)))\n', (1406, 1457), True, 'import numpy as np\n'), ((1524, 1563), 'numpy.fft.rfft', 'np.fft.rfft', (['(block[:, channel] * window)'], {}), '(block[:, channel] * window)\n', (1535, 1563), True, 'import numpy as np\n'), ((1587, 1598), 'numpy.abs', 'np.abs', (['fft'], {}), '(fft)\n', (1593, 1598), True, 'import numpy as np\n'), ((1623, 1636), 'numpy.angle', 'np.angle', (['fft'], {}), '(fft)\n', (1631, 1636), True, 'import numpy as np\n'), ((2619, 2635), 'numpy.abs', 'np.abs', (['out_data'], {}), '(out_data)\n', (2625, 2635), True, 'import numpy as np\n'), ((2067, 2122), 'numpy.interp', 'np.interp', (['(indices / pitch_mult)', 'indices', 'fft_mag', '(0)', '(0)'], {}), '(indices / pitch_mult, indices, fft_mag, 0, 0)\n', (2076, 2122), True, 'import numpy as np\n'), ((2151, 2220), 'numpy.interp', 'np.interp', (['(indices / pitch_mult)', 'indices', 'fft_phase'], {'period': '(np.pi * 2)'}), '(indices / pitch_mult, indices, fft_phase, period=np.pi * 2)\n', (2160, 2220), True, 'import numpy as np\n'), ((2422, 2446), 'numpy.exp', 'np.exp', (['(1.0j * fft_phase)'], {}), '(1.0j * fft_phase)\n', (2428, 2446), True, 'import numpy as np\n'), ((2470, 2487), 'numpy.fft.irfft', 'np.fft.irfft', (['fft'], {}), '(fft)\n', (2482, 2487), True, 'import numpy as np\n')]
import asyncio import datetime from collections import deque import cv2 import numpy as np from .app import MeasurementStep _message_action = { MeasurementStep.NOT_READY: "", MeasurementStep.READY: "Press 's' to start", MeasurementStep.USER_STARTED: "", MeasurementStep.MEASURING: "Press Esc to cancel", MeasurementStep.WAITING_RESULTS: "Press Esc to cancel", MeasurementStep.COMPLETED: "Press Esc to exit", MeasurementStep.USER_CANCELLED: "", MeasurementStep.FAILED: "Press Esc to exit" } _message_state = { MeasurementStep.NOT_READY: "Not ready to measure", MeasurementStep.READY: "Ready to measure", MeasurementStep.USER_STARTED: "Starting", MeasurementStep.MEASURING: "", MeasurementStep.WAITING_RESULTS: "Waiting for results", MeasurementStep.COMPLETED: "Measurement completed successfully", MeasurementStep.USER_CANCELLED: "Measurement cancelled by user", MeasurementStep.FAILED: "Measurement failed" } class Renderer(): def __init__(self, version, image_src_name, fps, app, sf=1.0): self._render_queue = asyncio.Queue(1) self._version = version self._image_src_name = image_src_name self._fps = fps self._app = app self._feedback = "" self._results = {} self._sf = sf if sf > 0 else 1.0 self._rendering_last = False self._recv_chunk = None self._sent_chunk = None self._timestamps_ns = deque(maxlen=11) self._last_frame_number = None async def render(self): render_image, meta = None, None cancelled = False while not self._rendering_last: try: render_image, meta = self._render_queue.get_nowait() render_image_copy = np.copy(render_image) self._draw_on_image(render_image_copy, meta) cv2.imshow(f"dfxdemo {self._version}", render_image_copy) k = cv2.waitKey(1) if k in [ord('q'), 27]: cancelled = True self._app.step = MeasurementStep.USER_CANCELLED break if self._app.step == MeasurementStep.READY and k in [ord('s'), ord(' ')]: self._app.step = MeasurementStep.USER_STARTED elif self._app.step == MeasurementStep.FAILED and k in [ord('r')]: self._app.step = MeasurementStep.NOT_READY except asyncio.QueueEmpty: pass finally: await asyncio.sleep(0) if cancelled: return cancelled # Keep rendering the last frame at 10fps as we display results while self._rendering_last: await asyncio.sleep(0.1) render_image_copy = np.copy(render_image) self._draw_on_image(render_image_copy, meta) cv2.imshow(f"dfxdemo {self._version}", render_image_copy) k = cv2.waitKey(1) if k in [ord('q'), 27]: if self._app.step == MeasurementStep.WAITING_RESULTS: self._app.step = MeasurementStep.USER_CANCELLED cancelled = True break return cancelled async def put_nowait(self, render_info): try: image, meta = render_info if self._sf == 1.0: rimage = np.copy(image) elif self._sf < 1.0: rimage = cv2.resize(image, (0, 0), fx=self._sf, fy=self._sf, interpolation=cv2.INTER_AREA) else: rimage = cv2.resize(image, (0, 0), fx=self._sf, fy=self._sf, interpolation=cv2.INTER_LINEAR) self._render_queue.put_nowait((rimage, meta)) except asyncio.QueueFull: pass def keep_render_last_frame(self): self._rendering_last = True def set_constraints_feedback(self, feedback): self._feedback = feedback def set_results(self, results): recv_chunk = int(results["chunk_number"]) if self._recv_chunk is None or recv_chunk > self._recv_chunk: self._recv_chunk = recv_chunk del results["chunk_number"] self._results = results def set_sent(self, sent_number): self._sent_chunk = int(sent_number) def _draw_on_image(self, render_image, image_meta): dfxframe, frame_number, frame_timestamp_ns = image_meta # Render the target_rect if self._app.constraints_cfg is not None: w = render_image.shape[1] * self._app.constraints_cfg.boxWidth_pct / 100 h = render_image.shape[0] * self._app.constraints_cfg.boxHeight_pct / 100 xc = render_image.shape[1] * self._app.constraints_cfg.boxCenterX_pct / 100 yc = render_image.shape[0] * self._app.constraints_cfg.boxCenterY_pct / 100 cv2.rectangle(render_image, (int(xc - w / 2), int(yc - h / 2)), (int(xc + w / 2), int(yc + h / 2)), color=(255, 0, 0), thickness=1, lineType=cv2.LINE_AA) # Render the face polygons for faceID in dfxframe.getFaceIdentifiers(): for regionID in dfxframe.getRegionNames(faceID): if dfxframe.getRegionIntProperty(faceID, regionID, "draw") != 0: polygon = dfxframe.getRegionPolygon(faceID, regionID) cv2.polylines(render_image, [np.round(np.array(polygon) * self._sf).astype(int)], isClosed=True, color=(255, 255, 0), thickness=1, lineType=cv2.LINE_AA) # Render the current time (so user knows things aren't frozen) now = datetime.datetime.now() self._draw_text(f"{now.strftime('%X')}", render_image, (render_image.shape[1] - 70, 15), fg=(0, 128, 0) if now.second % 2 == 0 else (0, 0, 0)) # Render filename, framerate of last 10 frames and expected framerate c = 2 r = 15 if not self._app.is_camera: msg = f"{self._image_src_name}: {self._fps:.2f} fps" else: if not self._rendering_last: self._timestamps_ns.append(frame_timestamp_ns) if len(self._timestamps_ns) >= 2: deltas = [self._timestamps_ns[i + 1] - self._timestamps_ns[i] for i in range(len(self._timestamps_ns) - 1)] avg_delta = sum(deltas) / len(deltas) fps_now = 1000_000_000.0 / avg_delta else: fps_now = self._fps msg = f"{self._image_src_name}: {self._fps:.2f} fps | {fps_now:.2f} fps" r = self._draw_text(msg, render_image, (c, r)) # Render the message message_action = _message_action[self._app.step] if message_action: r = self._draw_text(message_action, render_image, (c, r), fg=(255, 0, 0)) # Render progress if self._app.step == MeasurementStep.MEASURING: if self._app.begin_frame > 0: r = self._draw_text( f"Extracting frame {frame_number} of {self._app.begin_frame} to {self._app.end_frame + 1}", render_image, (c, r)) else: r = self._draw_text(f"Extracting frame {frame_number} of {self._app.end_frame + 1}", render_image, (c, r)) elif self._app.step == MeasurementStep.WAITING_RESULTS: if self._app.begin_frame > 0: r = self._draw_text( f"Extracted all {self._app.end_frame - self._app.begin_frame + 1} frames from " f"{self._app.begin_frame} to {self._app.end_frame + 1}", render_image, (c, r)) else: r = self._draw_text(f"Extracted all {self._app.end_frame - self._app.begin_frame + 1} frames", render_image, (c, r)) dots = "..." if now.second % 2 == 0 else "" r = self._draw_text(_message_state[self._app.step] + dots, render_image, (c, r)) else: r = self._draw_text(_message_state[self._app.step], render_image, (c, r)) # Render the constraints feedback if self._feedback: r = self._draw_text(self._feedback, render_image, (c, r), fg=(0, 0, 255)) # Render chunk numbers and results if self._sent_chunk is not None: r = self._draw_text(f"Sent chunk: {self._sent_chunk + 1} of {self._app.number_chunks}", render_image, (c, r)) if self._results: r = self._draw_text(f"Received result: {self._recv_chunk + 1} of {self._app.number_chunks}", render_image, (c, r)) for k, v in self._results.items(): r = self._draw_text(f"{k}: {v}", render_image, (c + 10, r), fs=0.8) def _draw_text(self, msg, render_image, origin, fs=None, fg=None, bg=None): FONT = cv2.FONT_HERSHEY_SIMPLEX AA = cv2.LINE_AA THICK = 1 PAD = 3 fs = 0.45 if fs is None else fs * 0.45 fg = (0, 0, 0) if fg is None else fg bg = (255, 255, 255) if bg is None else bg sz, baseline = cv2.getTextSize(msg, FONT, fs, THICK) cv2.rectangle(render_image, (origin[0] - PAD, origin[1] - sz[1] - PAD), (origin[0] + sz[0] + PAD, origin[1] + sz[1] - baseline * 2 + PAD), bg, thickness=-1) cv2.putText(render_image, msg, origin, FONT, fs, fg, THICK, AA) return origin[1] + sz[1] + baseline + 1 class NullRenderer(): async def render(self): pass async def put_nowait(self, _): pass def keep_render_last_frame(self): pass def set_constraints_feedback(self, _): pass def set_results(self, _): pass def set_sent(self, _): pass
[ "cv2.rectangle", "numpy.copy", "collections.deque", "cv2.resize", "asyncio.Queue", "cv2.putText", "cv2.imshow", "datetime.datetime.now", "numpy.array", "asyncio.sleep", "cv2.getTextSize", "cv2.waitKey" ]
[((1094, 1110), 'asyncio.Queue', 'asyncio.Queue', (['(1)'], {}), '(1)\n', (1107, 1110), False, 'import asyncio\n'), ((1464, 1480), 'collections.deque', 'deque', ([], {'maxlen': '(11)'}), '(maxlen=11)\n', (1469, 1480), False, 'from collections import deque\n'), ((5791, 5814), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (5812, 5814), False, 'import datetime\n'), ((9341, 9378), 'cv2.getTextSize', 'cv2.getTextSize', (['msg', 'FONT', 'fs', 'THICK'], {}), '(msg, FONT, fs, THICK)\n', (9356, 9378), False, 'import cv2\n'), ((9387, 9552), 'cv2.rectangle', 'cv2.rectangle', (['render_image', '(origin[0] - PAD, origin[1] - sz[1] - PAD)', '(origin[0] + sz[0] + PAD, origin[1] + sz[1] - baseline * 2 + PAD)', 'bg'], {'thickness': '(-1)'}), '(render_image, (origin[0] - PAD, origin[1] - sz[1] - PAD), (\n origin[0] + sz[0] + PAD, origin[1] + sz[1] - baseline * 2 + PAD), bg,\n thickness=-1)\n', (9400, 9552), False, 'import cv2\n'), ((9618, 9681), 'cv2.putText', 'cv2.putText', (['render_image', 'msg', 'origin', 'FONT', 'fs', 'fg', 'THICK', 'AA'], {}), '(render_image, msg, origin, FONT, fs, fg, THICK, AA)\n', (9629, 9681), False, 'import cv2\n'), ((2794, 2815), 'numpy.copy', 'np.copy', (['render_image'], {}), '(render_image)\n', (2801, 2815), True, 'import numpy as np\n'), ((2885, 2942), 'cv2.imshow', 'cv2.imshow', (['f"""dfxdemo {self._version}"""', 'render_image_copy'], {}), "(f'dfxdemo {self._version}', render_image_copy)\n", (2895, 2942), False, 'import cv2\n'), ((2959, 2973), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (2970, 2973), False, 'import cv2\n'), ((1779, 1800), 'numpy.copy', 'np.copy', (['render_image'], {}), '(render_image)\n', (1786, 1800), True, 'import numpy as np\n'), ((1878, 1935), 'cv2.imshow', 'cv2.imshow', (['f"""dfxdemo {self._version}"""', 'render_image_copy'], {}), "(f'dfxdemo {self._version}', render_image_copy)\n", (1888, 1935), False, 'import cv2\n'), ((1956, 1970), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (1967, 1970), False, 'import cv2\n'), ((2742, 2760), 'asyncio.sleep', 'asyncio.sleep', (['(0.1)'], {}), '(0.1)\n', (2755, 2760), False, 'import asyncio\n'), ((3387, 3401), 'numpy.copy', 'np.copy', (['image'], {}), '(image)\n', (3394, 3401), True, 'import numpy as np\n'), ((2547, 2563), 'asyncio.sleep', 'asyncio.sleep', (['(0)'], {}), '(0)\n', (2560, 2563), False, 'import asyncio\n'), ((3460, 3546), 'cv2.resize', 'cv2.resize', (['image', '(0, 0)'], {'fx': 'self._sf', 'fy': 'self._sf', 'interpolation': 'cv2.INTER_AREA'}), '(image, (0, 0), fx=self._sf, fy=self._sf, interpolation=cv2.\n INTER_AREA)\n', (3470, 3546), False, 'import cv2\n'), ((3585, 3673), 'cv2.resize', 'cv2.resize', (['image', '(0, 0)'], {'fx': 'self._sf', 'fy': 'self._sf', 'interpolation': 'cv2.INTER_LINEAR'}), '(image, (0, 0), fx=self._sf, fy=self._sf, interpolation=cv2.\n INTER_LINEAR)\n', (3595, 3673), False, 'import cv2\n'), ((5454, 5471), 'numpy.array', 'np.array', (['polygon'], {}), '(polygon)\n', (5462, 5471), True, 'import numpy as np\n')]
import tkinter as tk from tkinter import ttk from PIL import Image, ImageTk from tkinter import filedialog as fd from tkinter import messagebox as mb import matplotlib.pyplot as plt import numpy as np import cv2 class GUI(tk.Frame): def __init__(self, parent = None): tk.Frame.__init__(self, parent) self.parent = parent self.img_path = '' self.save_path = '' self.frame0 = tk.Frame(self, bd = 10) self.frame0.pack() self.path_label = tk.Label(self.frame0, text = '') self.path_label.pack(side='left') self.browseButton = tk.Button(self.frame0, text = 'Browse', command = self.openfile) self.browseButton.pack(side = 'left') self.slider_var = tk.IntVar() self.slider = tk.Scale(self, from_=1, to=20, orient= 'horizontal', variable = self.slider_var, command = self.slider_changed) self.slider.pack(pady = 10) self.goButton = tk.Button(self, text = 'Paint', command = self.go, width = 20) self.goButton.pack(pady = 10) self.addButton = tk.Button(self, text = 'Add Area', command = self.add_area, width = 20) self.addButton.pack(pady = 10) self.saveButton = tk.Button(self, text = 'Save as...', command = self.savefile, width = 20) self.saveButton.pack(pady = 10) self.mark_val = 1 self.oval_size = 1 def paint(self, event): python_green = "#476042" x1, y1 = ( event.x - self.oval_size ), ( event.y - self.oval_size ) x2, y2 = ( event.x + self.oval_size ), ( event.y + self.oval_size ) for x in range(x1, x2+1) : for y in range(y1, y2 + 1): self.image_mask[y][x][0] = self.mark_val self.image_mask[y][x][1] = self.mark_val self.image_mask[y][x][2] = self.mark_val self.canvas.create_oval( x1, y1, x2, y2, fill = python_green ) def add_area(self): self.mark_val += 1 def slider_changed(self, event): self.oval_size = self.slider_var.get() # print(self.slider_var.get()) def go(self): if (len(self.img_path) == 0): mb.showinfo('No image selected', 'Please browse an image to be resized') return # img = plt.imread(self.img_path) img = ImageTk.PhotoImage(Image.open(self.img_path)) offspring = tk.Toplevel() offspring.title(self.img_path.split('/')[-1]) offspring.geometry('%sx%s' % (img.width()+10, img.height()+10)) self.image_mask = np.zeros((img.height(), img.width(), 3)) self.canvas = tk.Canvas(offspring, width=img.width(), height=img.height(), borderwidth=0, highlightthickness=0) self.canvas.pack(expand=True) self.canvas.img = img # Keep reference in case this code is put into a function. self.canvas.create_image(0, 0, image=img, anchor=tk.NW) self.canvas.bind( "<B1-Motion>", self.paint ) offspring.mainloop() def openfile(self): self.img_path = fd.askopenfilename() self.path_label.config(text = self.img_path) def savefile(self): self.save_path = fd.asksaveasfilename() if len(self.save_path) == 0 : mb.showinfo('Give destination', 'Please give a destination path') return cv2.imwrite(self.save_path, self.image_mask) with open(self.save_path[:-4]+'.npy', 'wb') as f: np.save(f, np.array(self.image_mask)) if __name__ == '__main__': root = tk.Tk() root.geometry('%sx%s' % (400, 300)) gui = GUI(root) gui.pack() root.mainloop()
[ "tkinter.IntVar", "cv2.imwrite", "tkinter.Frame.__init__", "PIL.Image.open", "tkinter.filedialog.asksaveasfilename", "tkinter.Toplevel", "tkinter.Button", "tkinter.Scale", "numpy.array", "tkinter.Tk", "tkinter.Label", "tkinter.messagebox.showinfo", "tkinter.Frame", "tkinter.filedialog.asko...
[((3546, 3553), 'tkinter.Tk', 'tk.Tk', ([], {}), '()\n', (3551, 3553), True, 'import tkinter as tk\n'), ((281, 312), 'tkinter.Frame.__init__', 'tk.Frame.__init__', (['self', 'parent'], {}), '(self, parent)\n', (298, 312), True, 'import tkinter as tk\n'), ((421, 442), 'tkinter.Frame', 'tk.Frame', (['self'], {'bd': '(10)'}), '(self, bd=10)\n', (429, 442), True, 'import tkinter as tk\n'), ((498, 528), 'tkinter.Label', 'tk.Label', (['self.frame0'], {'text': '""""""'}), "(self.frame0, text='')\n", (506, 528), True, 'import tkinter as tk\n'), ((601, 661), 'tkinter.Button', 'tk.Button', (['self.frame0'], {'text': '"""Browse"""', 'command': 'self.openfile'}), "(self.frame0, text='Browse', command=self.openfile)\n", (610, 661), True, 'import tkinter as tk\n'), ((738, 749), 'tkinter.IntVar', 'tk.IntVar', ([], {}), '()\n', (747, 749), True, 'import tkinter as tk\n'), ((772, 883), 'tkinter.Scale', 'tk.Scale', (['self'], {'from_': '(1)', 'to': '(20)', 'orient': '"""horizontal"""', 'variable': 'self.slider_var', 'command': 'self.slider_changed'}), "(self, from_=1, to=20, orient='horizontal', variable=self.\n slider_var, command=self.slider_changed)\n", (780, 883), True, 'import tkinter as tk\n'), ((945, 1001), 'tkinter.Button', 'tk.Button', (['self'], {'text': '"""Paint"""', 'command': 'self.go', 'width': '(20)'}), "(self, text='Paint', command=self.go, width=20)\n", (954, 1001), True, 'import tkinter as tk\n'), ((1072, 1137), 'tkinter.Button', 'tk.Button', (['self'], {'text': '"""Add Area"""', 'command': 'self.add_area', 'width': '(20)'}), "(self, text='Add Area', command=self.add_area, width=20)\n", (1081, 1137), True, 'import tkinter as tk\n'), ((1210, 1277), 'tkinter.Button', 'tk.Button', (['self'], {'text': '"""Save as..."""', 'command': 'self.savefile', 'width': '(20)'}), "(self, text='Save as...', command=self.savefile, width=20)\n", (1219, 1277), True, 'import tkinter as tk\n'), ((2391, 2404), 'tkinter.Toplevel', 'tk.Toplevel', ([], {}), '()\n', (2402, 2404), True, 'import tkinter as tk\n'), ((3061, 3081), 'tkinter.filedialog.askopenfilename', 'fd.askopenfilename', ([], {}), '()\n', (3079, 3081), True, 'from tkinter import filedialog as fd\n'), ((3186, 3208), 'tkinter.filedialog.asksaveasfilename', 'fd.asksaveasfilename', ([], {}), '()\n', (3206, 3208), True, 'from tkinter import filedialog as fd\n'), ((3353, 3397), 'cv2.imwrite', 'cv2.imwrite', (['self.save_path', 'self.image_mask'], {}), '(self.save_path, self.image_mask)\n', (3364, 3397), False, 'import cv2\n'), ((2176, 2248), 'tkinter.messagebox.showinfo', 'mb.showinfo', (['"""No image selected"""', '"""Please browse an image to be resized"""'], {}), "('No image selected', 'Please browse an image to be resized')\n", (2187, 2248), True, 'from tkinter import messagebox as mb\n'), ((2343, 2368), 'PIL.Image.open', 'Image.open', (['self.img_path'], {}), '(self.img_path)\n', (2353, 2368), False, 'from PIL import Image, ImageTk\n'), ((3259, 3324), 'tkinter.messagebox.showinfo', 'mb.showinfo', (['"""Give destination"""', '"""Please give a destination path"""'], {}), "('Give destination', 'Please give a destination path')\n", (3270, 3324), True, 'from tkinter import messagebox as mb\n'), ((3479, 3504), 'numpy.array', 'np.array', (['self.image_mask'], {}), '(self.image_mask)\n', (3487, 3504), True, 'import numpy as np\n')]
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Contains the :class:`TSSearch` for finding transition states and reaction paths using FSM. """ import glob import logging import os import shutil import time import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import numpy as np import ard.constants as constants import ard.util as util from ard.quantum import QuantumError from ard.node import Node from ard.sm import FSM ############################################################################### class TSError(Exception): """ An exception class for errors that occur during a TS search. """ pass ############################################################################### class TSSearch(object): """ Transition state finding using FSM with subsequent exact TS search and verification of the reaction path by intrinsic reaction coordinate calculation. The attributes are: ============== ======================== =================================== Attribute Type Description ============== ======================== =================================== `name` ``str`` The name of the object and logger `reactant` :class:`node.Node` A node object containing the coordinates and atoms of the reactant molecule `product` :class:`node.Node` A node object containing the coordinates and atoms of the product molecule `ts` :class:`node.Node` The exact transition state `irc` ``list`` The IRC path corresponding to the transition state `fsm` ``list`` The FSM path `barrier` ``float`` The reaction barrier in kcal/mol `dH` ``float`` The reaction energy in kcal/mol `output_dir` ``str`` The path to the output directory `Qclass` ``class`` A class representing the quantum software `kwargs` ``dict`` Options for FSM and quantum calculations `ngrad` ``int`` The total number of gradient evaluations `logger` :class:`logging.Logger` The logger ============== ======================== =================================== """ def __init__(self, reactant, product, name='0000', **kwargs): if reactant.atoms != product.atoms: raise Exception('Atom labels of reactant and product do not match') self.reactant = reactant self.product = product self.name = name self.output_dir = kwargs.get('output_dir', '') qprog = kwargs.get('qprog', 'gau') self.Qclass = util.assignQclass(qprog) self.kwargs = kwargs self.ts = None self.irc = None self.fsm = None self.barrier = None self.dH = None self.ngrad = None # Set up log file log_level = logging.INFO filename = 'output.' + self.name + '.log' self.logger = util.initializeLog(log_level, os.path.join(self.output_dir, filename), logname=self.name) def initialize(self): """ Initialize the TS search job. """ self.logger.info('\nTS search initiated on ' + time.asctime() + '\n') self.logHeader() self.ngrad = 0 def execute(self): """ Run the string method, exact transition state search, IRC calculation, and check the results. The highest energy node is selected for the exact transition state search. """ start_time = time.time() self.initialize() reac_opt_success = self.optimizeReactant() if reac_opt_success: reac_energy = self.reactant.energy prod_opt_success = self.optimizeProduct() if prod_opt_success: prod_energy = self.product.energy self.executeStringMethod() energy_max = self.fsm[0].energy for node in self.fsm[1:-1]: if node.energy > energy_max: self.ts = node energy_max = node.energy self.executeExactTSSearch() chkfile = os.path.join(self.output_dir, 'chkf.{}.chk'.format(self.name)) self.computeFrequencies(chkfile) correct_reac, correct_prod = self.executeIRC(chkfile) if correct_reac: if not reac_opt_success: reac = self.irc[0] reac_opt, reac_opt_success = self.optimizeNode('irc_reac.' + self.name, reac) if reac_opt_success: self.reactant = reac_opt reac_energy = self.reactant.energy writeNode(self.reactant, 'reac.' + self.name, self.output_dir) if not correct_prod or not prod_opt_success: prod = self.irc[-1] prod_opt, prod_opt_success = self.optimizeNode('irc_prod.' + self.name, prod) if prod_opt_success: self.product = prod_opt prod_energy = self.product.energy writeNode(self.product, 'prod.' + self.name, self.output_dir) if reac_opt_success: self.barrier = (self.ts.energy - reac_energy) * constants.hartree_to_kcal_per_mol if prod_opt_success: self.dH = (prod_energy - reac_energy) * constants.hartree_to_kcal_per_mol self.finalize(start_time, correct_reac, correct_prod) def finalize(self, start_time, correct_reac, correct_prod): """ Finalize the job. """ fsm_energies = ['{:.1f}'.format((node.energy - self.reactant.energy) * constants.hartree_to_kcal_per_mol) for node in self.fsm] irc_energies = ['{:.1f}'.format((node.energy - self.reactant.energy) * constants.hartree_to_kcal_per_mol) for node in self.irc] self.logger.info('\nFSM path energies: ' + ' '.join(fsm_energies)) self.logger.info('IRC path energies: ' + ' '.join(irc_energies)) if self.barrier is not None: self.logger.info('Barrier height = {:.2f} kcal/mol'.format(self.barrier)) elif correct_reac: self.barrier = (self.ts.energy - self.reactant.energy) * constants.hartree_to_kcal_per_mol if self.irc is not None: barrier_irc = (self.ts.energy - self.irc[0].energy) * constants.hartree_to_kcal_per_mol self.barrier = max(self.barrier, barrier_irc) self.logger.info('Barrier height (estimate) = {:.2f} kcal/mol'.format(self.barrier)) if self.dH is not None: if self.dH < self.barrier: self.logger.info('Reaction energy = {:.2f} kcal/mol'.format(self.dH)) if not correct_prod: self.logger.info('Note: Reaction energy is based on unintended product') self.logger.info('\nTS search terminated on ' + time.asctime()) self.logger.info('Total TS search run time: {:.1f} s'.format(time.time() - start_time)) self.logger.info('Total number of gradient evaluations: {}'.format(self.ngrad)) @util.logStartAndFinish @util.timeFn def optimizeReactant(self): """ Optimize reactant geometry and set reactant energy. The optimization is done separately for each molecule in the reactant structure. Return `True` if successful, `False` otherwise. """ success = True name = 'reac_opt.' + self.name reac_mol = self.reactant.toMolecule() reac_cmat = self.reactant.toConnectivityMat() reac_node = self.reactant.copy() try: ngrad = reac_mol.optimizeGeometry(self.Qclass, name=name, **self.kwargs) except QuantumError as e: success = False self.logger.warning('Optimization of reactant structure was unsuccessful') self.logger.info('Error message: {}'.format(e)) # Read number of gradients even if the optimization failed ngrad = 0 for logname in glob.glob('{}*.log'.format(name)): q = self.Qclass(logfile=os.path.join(self.output_dir, logname)) ngrad += q.getNumGrad() self.logger.info('\nNumber of gradient evaluations during failed reactant optimization: {}'.format(ngrad)) self.logger.info('Proceeding with force field or partially optimized geometry\n') self.reactant = reac_mol.toNode() else: self.reactant = reac_mol.toNode() self.logger.info('Optimized reactant structure:\n' + str(self.reactant)) self.logger.info('Energy ({}) = {}'.format(self.kwargs['theory'].upper(), self.reactant.energy)) self.logger.info('\nNumber of gradient evaluations during reactant optimization: {}\n'.format(ngrad)) reac_cmat_new = self.reactant.toConnectivityMat() if not np.array_equal(reac_cmat, reac_cmat_new): success = False self.logger.warning('Optimized geometry has wrong connectivity and will not be used\n') self.reactant = reac_node if success: writeNode(self.reactant, 'reac.' + self.name, self.output_dir) self.ngrad += ngrad return success @util.logStartAndFinish @util.timeFn def optimizeProduct(self): """ Optimize product geometry and set product energy. The optimization is done separately for each molecule in the product structure. Return `True` if successful, `False` otherwise. """ success = True name = 'prod_opt.' + self.name prod_mol = self.product.toMolecule() prod_cmat = self.product.toConnectivityMat() prod_node = self.product.copy() try: ngrad = prod_mol.optimizeGeometry(self.Qclass, name=name, **self.kwargs) except QuantumError as e: success = False self.logger.warning('Optimization of product structure was unsuccessful') self.logger.info('Error message: {}'.format(e)) # Read number of gradients even if the optimization failed ngrad = 0 for logname in glob.glob('{}*.log'.format(name)): q = self.Qclass(logfile=os.path.join(self.output_dir, logname)) ngrad += q.getNumGrad() self.logger.info('\nNumber of gradient evaluations during failed product optimization: {}'.format(ngrad)) self.logger.info('Proceeding with force field or partially optimized geometry\n') self.product = prod_mol.toNode() else: self.product = prod_mol.toNode() self.logger.info('Optimized product structure:\n' + str(self.product)) self.logger.info('Energy ({}) = {}'.format(self.kwargs['theory'].upper(), self.product.energy)) self.logger.info('\nNumber of gradient evaluations during product optimization: {}\n'.format(ngrad)) prod_cmat_new = self.product.toConnectivityMat() if not np.array_equal(prod_cmat, prod_cmat_new): success = False self.logger.warning('Optimized geometry has wrong connectivity and will not be used\n') self.product = prod_node if success: writeNode(self.product, 'prod.' + self.name, self.output_dir) self.ngrad += ngrad return success @util.logStartAndFinish @util.timeFn def optimizeNode(self, name, node): """ Optimize copy of node and set energy. The optimization is done separately for each molecule in the structure. Return node copy and return `True` if successful, `False` otherwise. """ success = True mol = node.toMolecule() cmat_old = node.toConnectivityMat() try: ngrad = mol.optimizeGeometry(self.Qclass, name=name, **self.kwargs) except QuantumError as e: success = False self.logger.warning('Optimization of structure was unsuccessful') self.logger.info('Error message: {}'.format(e)) # Read number of gradients even if the optimization failed ngrad = 0 for logname in glob.glob('{}*.log'.format(name)): q = self.Qclass(logfile=os.path.join(self.output_dir, logname)) ngrad += q.getNumGrad() self.logger.info('\nNumber of gradient evaluations during failed optimization: {}'.format(ngrad)) node_new = mol.toNode() else: node_new = mol.toNode() self.logger.info('Optimized structure:\n' + str(node_new)) self.logger.info('Energy ({}) = {}'.format(self.kwargs['theory'].upper(), node_new.energy)) self.logger.info('\nNumber of gradient evaluations during optimization: {}\n'.format(ngrad)) cmat_new = node_new.toConnectivityMat() if not np.array_equal(cmat_old, cmat_new): success = False self.logger.warning('Optimized geometry has wrong connectivity\n') self.ngrad += ngrad return node_new, success def executeStringMethod(self): """ Run the string method with the options specified in `kwargs`. """ fsm = FSM(self.reactant, self.product, name=self.name, logger=self.logger, **self.kwargs) try: self.fsm = fsm.execute() except QuantumError as e: self.ngrad += fsm.ngrad self.logger.error('String method failed and terminated with the message: {}'.format(e)) self.logger.info('Number of gradient evaluations during failed string method: {}'.format(fsm.ngrad)) self.logger.info('Total number of gradient evaluations: {}'.format(self.ngrad)) raise TSError('TS search failed during string method') self.ngrad += fsm.ngrad filepath = os.path.join(self.output_dir, 'fsmpath.{}.png'.format(self.name)) drawPath(self.fsm, filepath) @util.logStartAndFinish @util.timeFn def executeExactTSSearch(self): """ Run the exact transition state search and update `self.ts`. """ name = 'tsopt.' + self.name self.logger.info('Initial TS structure:\n' + str(self.ts) + '\nEnergy = ' + str(self.ts.energy)) try: ngrad = self.ts.optimizeGeometry(self.Qclass, ts=True, name=name, **self.kwargs) except QuantumError as e: self.logger.error('Exact TS search did not succeed and terminated with the message: {}'.format(e)) # Read number of gradients even if the optimization failed q = self.Qclass(logfile=os.path.join(self.output_dir, name + '.log')) ngrad = q.getNumGrad() self.ngrad += ngrad self.logger.info('\nNumber of gradient evaluations during failed TS search: {}\n'.format(ngrad)) self.logger.info('Total number of gradient evaluations: {}'.format(self.ngrad)) raise TSError('TS search failed during exact TS search') writeNode(self.ts, 'ts.' + self.name, self.output_dir) self.logger.info('Optimized TS structure:\n{}\nEnergy ({}) = {}'.format(self.ts, self.kwargs['theory'].upper(), self.ts.energy)) self.logger.info('\nNumber of gradient evaluations during exact TS search: {}\n'.format(ngrad)) self.ngrad += ngrad @util.logStartAndFinish @util.timeFn def computeFrequencies(self, chkfile=None): """ Run a frequency calculation using the exact TS geometry. """ try: nimag, ngrad = self.ts.computeFrequencies( self.Qclass, name='freq.' + self.name, chkfile=chkfile, **self.kwargs ) except QuantumError as e: self.logger.error('Frequency calculation did not succeed and terminated with the message: {}'.format(e)) self.logger.info('Total number of gradient evaluations: {}'.format(self.ngrad)) raise TSError('TS search failed during frequency calculation') if nimag != 1: self.logger.error('Number of imaginary frequencies is different than 1. Geometry is not a TS!') self.logger.info('Total number of gradient evaluations: {}'.format(self.ngrad)) raise TSError('TS search failed due to wrong number of imaginary frequencies') self.logger.info('Number of gradient evaluations during frequency calculation: {}\n'.format(ngrad)) self.ngrad += ngrad @util.logStartAndFinish @util.timeFn def executeIRC(self, chkfile=None): """ Run an IRC calculation using the exact TS geometry and save the path to `self.irc`. Return two booleans indicating whether or not the correct reactant and product were found. """ if chkfile is not None and os.path.exists(chkfile): chkf_name, chkf_ext = os.path.splitext(chkfile) chkfile_copy = chkf_name + '_copy' + chkf_ext shutil.copyfile(chkfile, chkfile_copy) else: chkfile_copy = None forward_path, forward_ngrad = self._runOneDirectionalIRC('irc_forward.' + self.name, 'forward', chkfile) reverse_path, reverse_ngrad = self._runOneDirectionalIRC('irc_reverse.' + self.name, 'reverse', chkfile_copy) ngrad = forward_ngrad + reverse_ngrad # Check if endpoints correspond to reactant and product based on connectivity matrices # and try to orient IRC path so that it runs from reactant to product self.logger.info('Begin IRC endpoint check...') reac_cmat = self.reactant.toConnectivityMat() prod_cmat = self.product.toConnectivityMat() irc_end_1_cmat = forward_path[-1].toConnectivityMat() irc_end_2_cmat = reverse_path[-1].toConnectivityMat() correct_reac, correct_prod = False, False if np.array_equal(reac_cmat, irc_end_1_cmat): self.irc = forward_path[::-1] + [self.ts] + reverse_path correct_reac = True elif np.array_equal(reac_cmat, irc_end_2_cmat): self.irc = reverse_path[::-1] + [self.ts] + forward_path correct_reac = True else: self.irc = forward_path[::-1] + [self.ts] + reverse_path if np.array_equal(prod_cmat, irc_end_1_cmat): correct_prod = True if not correct_reac: self.irc = reverse_path[::-1] + [self.ts] + forward_path elif np.array_equal(prod_cmat, irc_end_2_cmat): correct_prod = True if correct_reac and correct_prod: self.logger.info('IRC check was successful. The IRC path endpoints correspond to the reactant and product.') elif correct_reac: self.logger.warning('IRC check was unsuccessful. Wrong product!') elif correct_prod: self.logger.warning('IRC check was unsuccessful. Wrong reactant!') else: self.logger.warning('IRC check was unsuccessful. Wrong reactant and product!') if np.array_equal(reac_cmat, prod_cmat): self.logger.warning('Reactant and product are the same! Conformational saddle point was found.') reactant_smi = self.reactant.toSMILES() product_smi = self.product.toSMILES() irc_end_1_smi = self.irc[0].toSMILES() irc_end_2_smi = self.irc[-1].toSMILES() self.logger.info('Coordinates converted to SMILES:') self.logger.info('Reactant: {}\nProduct: {}\nIRC endpoint 1: {}\nIRC endpoint 2: {}'. format(reactant_smi, product_smi, irc_end_1_smi, irc_end_2_smi)) with open(os.path.join(self.output_dir, 'irc.{}.out'.format(self.name)), 'w') as f: for node_num, node in enumerate(self.irc): f.write(str(len(node.atoms)) + '\n') f.write('Energy = ' + str(node.energy) + '\n') f.write(str(node) + '\n') self.logger.info('IRC path endpoints:\n' + str(self.irc[0]) + '\n****\n' + str(self.irc[-1]) + '\n') self.logger.info('\nNumber of gradient evaluations during IRC calculation: {}\n'.format(ngrad)) self.ngrad += ngrad filepath = os.path.join(self.output_dir, 'ircpath.{}.png'.format(self.name)) drawPath(self.irc, filepath) return correct_reac, correct_prod @util.timeFn def _runOneDirectionalIRC(self, name, direction, chkfile): """ Run an IRC calculation in the forward or reverse direction and return the path together with the number of gradient evaluations. The results are returned even if an error was raised during the calculation. """ try: ircpath, ngrad = self.ts.getIRCpath( self.Qclass, name=name, direction=direction, chkfile=chkfile, **self.kwargs ) except QuantumError as e: self.logger.warning( '{} IRC calculation did not run to completion and terminated with the message: {}'.format(direction, e) ) q = self.Qclass(logfile=os.path.join(self.output_dir, name + '.log')) try: path = q.getIRCpath() ngrad = q.getNumGrad() except QuantumError as e: self.logger.error('TS search failed reading IRC logfile: {}\n'.format(e)) self.barrier = (self.ts.energy - self.reactant.energy) * constants.hartree_to_kcal_per_mol self.logger.info('Barrier height (estimate) = {:.2f} kcal/mol\n'.format(self.barrier)) self.logger.info('Total number of gradient evaluations: {}'.format(self.ngrad)) raise TSError('TS search failed reading IRC logfile: {}'.format(e)) q.clearChkfile() ircpath = [] for element in path: node = Node(element[0], self.reactant.atoms, self.reactant.multiplicity) node.energy = element[1] ircpath.append(node) return ircpath, ngrad def logHeader(self): """ Output a log file header containing identifying information about the TS search. """ self.logger.info('#######################################################################') self.logger.info('############################## TS SEARCH ##############################') self.logger.info('#######################################################################') self.logger.info('Reactant SMILES: ' + str(self.reactant.toSMILES())) self.logger.info('Reactant structure:\n' + str(self.reactant)) self.logger.info('Product SMILES: ' + str(self.product.toSMILES())) self.logger.info('Product structure:\n' + str(self.product)) self.logger.info('#######################################################################\n') ############################################################################### def drawPath(nodepath, filepath): """ Make a plot of the path energies, where `nodepath` is a list of :class:`node.Node` objects. """ reac_energy = nodepath[0].energy energies = [(node.energy - reac_energy) * constants.hartree_to_kcal_per_mol for node in nodepath] n = range(1, len(energies) + 1) plt.figure() line = plt.plot(n, energies) plt.setp(line, c='b', ls='-', lw=2.0, marker='.', mec='k', mew=1.0, mfc='w', ms=17.0) plt.xlabel('Node') plt.ylabel('Energy (kcal/mol)') plt.grid(True) plt.savefig(filepath) def writeNode(node, name, out_dir): """ Write node geometry to file. """ with open(os.path.join(out_dir, name + '.out'), 'w') as f: f.write(str(len(node.atoms)) + '\n') f.write('Energy = {}\n'.format(node.energy)) f.write(str(node) + '\n') ############################################################################### if __name__ == '__main__': import argparse from ard.main import readInput # Set up parser for reading the input filename from the command line parser = argparse.ArgumentParser(description='A transition state search') parser.add_argument('-n', '--nproc', default=1, type=int, metavar='N', help='number of processors') parser.add_argument('-m', '--mem', default=2000, type=int, metavar='M', help='memory requirement') parser.add_argument('file', type=str, metavar='infile', help='an input file describing the job options') args = parser.parse_args() # Read input file input_file = os.path.abspath(args.file) options = readInput(input_file) # Set output directory output_dir = os.path.abspath(os.path.dirname(input_file)) options['output_dir'] = output_dir # Set number of processors and memory options['nproc'] = args.nproc options['mem'] = str(args.mem) + 'mb' # Execute job tssearch = TSSearch(**options) tssearch.execute()
[ "matplotlib.pyplot.grid", "matplotlib.pyplot.ylabel", "os.path.exists", "argparse.ArgumentParser", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.plot", "ard.sm.FSM", "ard.node.Node", "matplotlib.pyplot.savefig", "matplotlib.use", "os.path.splitext", "os.path.dirname", "shutil.copyfile", "...
[((229, 250), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (243, 250), False, 'import matplotlib\n'), ((23563, 23575), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (23573, 23575), True, 'import matplotlib.pyplot as plt\n'), ((23587, 23608), 'matplotlib.pyplot.plot', 'plt.plot', (['n', 'energies'], {}), '(n, energies)\n', (23595, 23608), True, 'import matplotlib.pyplot as plt\n'), ((23613, 23702), 'matplotlib.pyplot.setp', 'plt.setp', (['line'], {'c': '"""b"""', 'ls': '"""-"""', 'lw': '(2.0)', 'marker': '"""."""', 'mec': '"""k"""', 'mew': '(1.0)', 'mfc': '"""w"""', 'ms': '(17.0)'}), "(line, c='b', ls='-', lw=2.0, marker='.', mec='k', mew=1.0, mfc='w',\n ms=17.0)\n", (23621, 23702), True, 'import matplotlib.pyplot as plt\n'), ((23703, 23721), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Node"""'], {}), "('Node')\n", (23713, 23721), True, 'import matplotlib.pyplot as plt\n'), ((23726, 23757), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Energy (kcal/mol)"""'], {}), "('Energy (kcal/mol)')\n", (23736, 23757), True, 'import matplotlib.pyplot as plt\n'), ((23762, 23776), 'matplotlib.pyplot.grid', 'plt.grid', (['(True)'], {}), '(True)\n', (23770, 23776), True, 'import matplotlib.pyplot as plt\n'), ((23781, 23802), 'matplotlib.pyplot.savefig', 'plt.savefig', (['filepath'], {}), '(filepath)\n', (23792, 23802), True, 'import matplotlib.pyplot as plt\n'), ((24336, 24400), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""A transition state search"""'}), "(description='A transition state search')\n", (24359, 24400), False, 'import argparse\n'), ((24788, 24814), 'os.path.abspath', 'os.path.abspath', (['args.file'], {}), '(args.file)\n', (24803, 24814), False, 'import os\n'), ((24829, 24850), 'ard.main.readInput', 'readInput', (['input_file'], {}), '(input_file)\n', (24838, 24850), False, 'from ard.main import readInput\n'), ((2734, 2758), 'ard.util.assignQclass', 'util.assignQclass', (['qprog'], {}), '(qprog)\n', (2751, 2758), True, 'import ard.util as util\n'), ((3636, 3647), 'time.time', 'time.time', ([], {}), '()\n', (3645, 3647), False, 'import time\n'), ((13379, 13467), 'ard.sm.FSM', 'FSM', (['self.reactant', 'self.product'], {'name': 'self.name', 'logger': 'self.logger'}), '(self.reactant, self.product, name=self.name, logger=self.logger, **self\n .kwargs)\n', (13382, 13467), False, 'from ard.sm import FSM\n'), ((18170, 18211), 'numpy.array_equal', 'np.array_equal', (['reac_cmat', 'irc_end_1_cmat'], {}), '(reac_cmat, irc_end_1_cmat)\n', (18184, 18211), True, 'import numpy as np\n'), ((18566, 18607), 'numpy.array_equal', 'np.array_equal', (['prod_cmat', 'irc_end_1_cmat'], {}), '(prod_cmat, irc_end_1_cmat)\n', (18580, 18607), True, 'import numpy as np\n'), ((19327, 19363), 'numpy.array_equal', 'np.array_equal', (['reac_cmat', 'prod_cmat'], {}), '(reac_cmat, prod_cmat)\n', (19341, 19363), True, 'import numpy as np\n'), ((24912, 24939), 'os.path.dirname', 'os.path.dirname', (['input_file'], {}), '(input_file)\n', (24927, 24939), False, 'import os\n'), ((3099, 3138), 'os.path.join', 'os.path.join', (['self.output_dir', 'filename'], {}), '(self.output_dir, filename)\n', (3111, 3138), False, 'import os\n'), ((9001, 9041), 'numpy.array_equal', 'np.array_equal', (['reac_cmat', 'reac_cmat_new'], {}), '(reac_cmat, reac_cmat_new)\n', (9015, 9041), True, 'import numpy as np\n'), ((11137, 11177), 'numpy.array_equal', 'np.array_equal', (['prod_cmat', 'prod_cmat_new'], {}), '(prod_cmat, prod_cmat_new)\n', (11151, 11177), True, 'import numpy as np\n'), ((17129, 17152), 'os.path.exists', 'os.path.exists', (['chkfile'], {}), '(chkfile)\n', (17143, 17152), False, 'import os\n'), ((17188, 17213), 'os.path.splitext', 'os.path.splitext', (['chkfile'], {}), '(chkfile)\n', (17204, 17213), False, 'import os\n'), ((17284, 17322), 'shutil.copyfile', 'shutil.copyfile', (['chkfile', 'chkfile_copy'], {}), '(chkfile, chkfile_copy)\n', (17299, 17322), False, 'import shutil\n'), ((18327, 18368), 'numpy.array_equal', 'np.array_equal', (['reac_cmat', 'irc_end_2_cmat'], {}), '(reac_cmat, irc_end_2_cmat)\n', (18341, 18368), True, 'import numpy as np\n'), ((18760, 18801), 'numpy.array_equal', 'np.array_equal', (['prod_cmat', 'irc_end_2_cmat'], {}), '(prod_cmat, irc_end_2_cmat)\n', (18774, 18801), True, 'import numpy as np\n'), ((23903, 23939), 'os.path.join', 'os.path.join', (['out_dir', "(name + '.out')"], {}), "(out_dir, name + '.out')\n", (23915, 23939), False, 'import os\n'), ((7005, 7019), 'time.asctime', 'time.asctime', ([], {}), '()\n', (7017, 7019), False, 'import time\n'), ((13022, 13056), 'numpy.array_equal', 'np.array_equal', (['cmat_old', 'cmat_new'], {}), '(cmat_old, cmat_new)\n', (13036, 13056), True, 'import numpy as np\n'), ((3303, 3317), 'time.asctime', 'time.asctime', ([], {}), '()\n', (3315, 3317), False, 'import time\n'), ((7090, 7101), 'time.time', 'time.time', ([], {}), '()\n', (7099, 7101), False, 'import time\n'), ((22133, 22198), 'ard.node.Node', 'Node', (['element[0]', 'self.reactant.atoms', 'self.reactant.multiplicity'], {}), '(element[0], self.reactant.atoms, self.reactant.multiplicity)\n', (22137, 22198), False, 'from ard.node import Node\n'), ((14786, 14830), 'os.path.join', 'os.path.join', (['self.output_dir', "(name + '.log')"], {}), "(self.output_dir, name + '.log')\n", (14798, 14830), False, 'import os\n'), ((21364, 21408), 'os.path.join', 'os.path.join', (['self.output_dir', "(name + '.log')"], {}), "(self.output_dir, name + '.log')\n", (21376, 21408), False, 'import os\n'), ((8219, 8257), 'os.path.join', 'os.path.join', (['self.output_dir', 'logname'], {}), '(self.output_dir, logname)\n', (8231, 8257), False, 'import os\n'), ((10363, 10401), 'os.path.join', 'os.path.join', (['self.output_dir', 'logname'], {}), '(self.output_dir, logname)\n', (10375, 10401), False, 'import os\n'), ((12393, 12431), 'os.path.join', 'os.path.join', (['self.output_dir', 'logname'], {}), '(self.output_dir, logname)\n', (12405, 12431), False, 'import os\n')]
from setuptools import setup, find_packages, Extension from codecs import open from os import path """ Release instruction: Check that tests run correctly for 36 and 27 and doc compiles without warning (make clean first). change __version__ in setup.py to new version name. First upload to test pypi: mktmpenv (Python version should not matter) pip install numpy cython twine python setup.py sdist twine upload dist/blabla.tar.gz -r testpypi Check that install works on testpypi, then upload to pypi and check again. to install from testpypi: pip install --index-url https://test.pypi.org/simple/ --extra-index-url https://pypi.org/simple scikit-surprise # noqa push new release tag on github (commit last changes first if needed): git tag vX.Y.Z git push --tags Check that RTD has updated 'stable' to the new release (may take a while). In the mean time, upload to conda: - Compute SHA256 hash of the new .tar.gz archive (or check it up on PyPI) - update recipe/meta.yaml on feedstock fork consequently (only version and sha should be changed. Maybe add some import tests). - Push changes, Then open pull request on conda-forge feedstock and merge it when all checks are OK. Access the conda-forge feedstock it by the link on GitHub 'forked from blah blah'. - Check on https://anaconda.org/conda-forge/scikit-surprise that new version is available for all platforms. Then, maybe, celebrate. """ try: import numpy as np except ImportError: exit('Please install numpy>=1.11.2 first.') try: from Cython.Build import cythonize from Cython.Distutils import build_ext except ImportError: USE_CYTHON = False else: USE_CYTHON = True __version__ = '1.0.6' here = path.abspath(path.dirname(__file__)) # Get the long description from README.md with open(path.join(here, 'README.md'), encoding='utf-8') as f: long_description = f.read() # get the dependencies and installs with open(path.join(here, 'requirements.txt'), encoding='utf-8') as f: all_reqs = f.read().split('\n') install_requires = [x.strip() for x in all_reqs if 'git+' not in x] dependency_links = [x.strip().replace('git+', '') for x in all_reqs if x.startswith('git+')] cmdclass = {} ext = '.pyx' if USE_CYTHON else '.c' extensions = [ Extension( 'surprise.similarities', ['surprise/similarities' + ext], include_dirs=[np.get_include()] ), Extension( 'surprise.prediction_algorithms.matrix_factorization', ['surprise/prediction_algorithms/matrix_factorization' + ext], include_dirs=[np.get_include()]), Extension('surprise.prediction_algorithms.optimize_baselines', ['surprise/prediction_algorithms/optimize_baselines' + ext], include_dirs=[np.get_include()]), Extension('surprise.prediction_algorithms.slope_one', ['surprise/prediction_algorithms/slope_one' + ext], include_dirs=[np.get_include()]), Extension('surprise.prediction_algorithms.co_clustering', ['surprise/prediction_algorithms/co_clustering' + ext], include_dirs=[np.get_include()]), ] if USE_CYTHON: ext_modules = cythonize(extensions) cmdclass.update({'build_ext': build_ext}) else: ext_modules = extensions setup( name='scikit-surprise', author='<NAME>', author_email='<EMAIL>', description=('An easy-to-use library for recommender systems.'), long_description=long_description, long_description_content_type='text/markdown', version=__version__, url='http://surpriselib.com', license='GPLv3+', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Intended Audience :: Education', 'Intended Audience :: Science/Research', 'Topic :: Scientific/Engineering', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 2.7', ], keywords='recommender recommendation system', packages=find_packages(exclude=['tests*']), include_package_data=True, ext_modules=ext_modules, cmdclass=cmdclass, install_requires=install_requires, dependency_links=dependency_links, entry_points={'console_scripts': ['surprise = surprise.__main__:main']}, )
[ "Cython.Build.cythonize", "setuptools.find_packages", "os.path.join", "os.path.dirname", "numpy.get_include" ]
[((1771, 1793), 'os.path.dirname', 'path.dirname', (['__file__'], {}), '(__file__)\n', (1783, 1793), False, 'from os import path\n'), ((3234, 3255), 'Cython.Build.cythonize', 'cythonize', (['extensions'], {}), '(extensions)\n', (3243, 3255), False, 'from Cython.Build import cythonize\n'), ((1848, 1876), 'os.path.join', 'path.join', (['here', '"""README.md"""'], {}), "(here, 'README.md')\n", (1857, 1876), False, 'from os import path\n'), ((1981, 2016), 'os.path.join', 'path.join', (['here', '"""requirements.txt"""'], {}), "(here, 'requirements.txt')\n", (1990, 2016), False, 'from os import path\n'), ((4132, 4165), 'setuptools.find_packages', 'find_packages', ([], {'exclude': "['tests*']"}), "(exclude=['tests*'])\n", (4145, 4165), False, 'from setuptools import setup, find_packages, Extension\n'), ((2440, 2456), 'numpy.get_include', 'np.get_include', ([], {}), '()\n', (2454, 2456), True, 'import numpy as np\n'), ((2636, 2652), 'numpy.get_include', 'np.get_include', ([], {}), '()\n', (2650, 2652), True, 'import numpy as np\n'), ((2826, 2842), 'numpy.get_include', 'np.get_include', ([], {}), '()\n', (2840, 2842), True, 'import numpy as np\n'), ((2998, 3014), 'numpy.get_include', 'np.get_include', ([], {}), '()\n', (3012, 3014), True, 'import numpy as np\n'), ((3178, 3194), 'numpy.get_include', 'np.get_include', ([], {}), '()\n', (3192, 3194), True, 'import numpy as np\n')]
import numpy import soundfile from espnet.utils.io_utils import SoundHDF5File # TODO(kamo): Please implement, if anyone is interesting class SpeedPerturbation(object): # The marker used by "Transformation" accept_uttid = False def __init__(self, lower=0.8, upper=1.2, utt2scale=None): self.utt2scale = {} if utt2scale is not None: self.utt2scale_file = utt2scale self.lower = None self.upper = None self.accept_uttid = True with open(utt2scale, 'r') as f: for line in f: utt, scale = line.rstrip().split(None, 1) scale = float(scale) self.utt2scale[utt] = scale else: self.lower = lower self.upper = upper def __repr__(self): if len(self.utt2scale) == 0: return '{}({lower={}, upper={})'.format( self.__class__.__name__, self.lower, self.upper) else: return '{}({})'.format(self.__class__.__name__, self.utt2scale_file) def __call__(self, x, uttid=None): # if self.accept_uttid: # scale = self.utt2scale[uttid] # else: # scale = numpy.random.uniform(self.lower, self.upper) raise NotImplementedError class VolumePerturbation(object): # The marker used by "Transformation" accept_uttid = False def __init__(self, lower=0.8, upper=1.2, utt2scale=None): self.utt2scale = {} if utt2scale is not None: self.utt2scale_file = utt2scale self.lower = None self.upper = None self.accept_uttid = True with open(utt2scale, 'r') as f: for line in f: utt, scale = line.rstrip().split(None, 1) scale = float(scale) self.utt2scale[utt] = scale else: self.lower = lower self.upper = upper def __repr__(self): if len(self.utt2scale) == 0: return '{}({lower={}, upper={})'.format( self.__class__.__name__, self.lower, self.upper) else: return '{}({})'.format(self.__class__.__name__, self.utt2scale_file) def __call__(self, x, uttid=None): if self.accept_uttid: scale = self.utt2scale[uttid] else: scale = numpy.random.uniform(self.lower, self.upper) return x * scale class NoiseInjection(object): # The marker used by "Transformation" accept_uttid = True def __init__(self, utt2noise, utt2snr, filetype='list'): self.utt2noise_file = utt2noise self.utt2snr_file = utt2snr self.filetype = filetype self.utt2snr = {} with open(utt2noise, 'r') as f: for line in f: utt, snr = line.rstrip().split(None, 1) snr = float(snr) self.utt2snr[utt] = snr self.utt2noise = {} if filetype == 'list': with open(utt2noise, 'r') as f: for line in f: utt, filename = line.rstrip().split(None, 1) signal, rate = soundfile.read(filename, dtype='int16') self.utt2noise[utt] = (signal, rate) elif filetype == 'sound.hdf5': self.utt2noise = SoundHDF5File(utt2noise, 'r') else: raise ValueError(filetype) if set(self.utt2snr) != set(self.utt2noise): raise RuntimeError('The uttids mismatch between {} and {}' .format(utt2snr, utt2noise)) def __repr__(self): return '{}({})'.format(self.__class__.__name__, self.utt2noise_file) def __call__(self, x, uttid): # noise, rate self.utt2noise[uttid] # snr = self.utt2snr[uttid] raise NotImplementedError class RIRConvolve(object): # The marker used by "Transformation" accept_uttid = True def __init__(self, utt2rir, filetype='list'): self.utt2rir_file = utt2rir self.filetype = filetype self.utt2rir = {} if filetype == 'list': with open(utt2rir, 'r') as f: for line in f: utt, filename = line.rstrip().split(None, 1) signal, rate = soundfile.read(filename, dtype='int16') self.utt2rir[utt] = (signal, rate) elif filetype == 'sound.hdf5': self.utt2rir = SoundHDF5File(utt2rir, 'r') else: raise NotImplementedError(filetype) def __repr__(self): return '{}({})'.format(self.__class__.__name__, self.utt2rir_file) def __call__(self, x, uttid): # rir, rate = self.utt2rir[uttid] raise NotImplementedError
[ "soundfile.read", "espnet.utils.io_utils.SoundHDF5File", "numpy.random.uniform" ]
[((2481, 2525), 'numpy.random.uniform', 'numpy.random.uniform', (['self.lower', 'self.upper'], {}), '(self.lower, self.upper)\n', (2501, 2525), False, 'import numpy\n'), ((3444, 3473), 'espnet.utils.io_utils.SoundHDF5File', 'SoundHDF5File', (['utt2noise', '"""r"""'], {}), "(utt2noise, 'r')\n", (3457, 3473), False, 'from espnet.utils.io_utils import SoundHDF5File\n'), ((4602, 4629), 'espnet.utils.io_utils.SoundHDF5File', 'SoundHDF5File', (['utt2rir', '"""r"""'], {}), "(utt2rir, 'r')\n", (4615, 4629), False, 'from espnet.utils.io_utils import SoundHDF5File\n'), ((3278, 3317), 'soundfile.read', 'soundfile.read', (['filename'], {'dtype': '"""int16"""'}), "(filename, dtype='int16')\n", (3292, 3317), False, 'import soundfile\n'), ((4440, 4479), 'soundfile.read', 'soundfile.read', (['filename'], {'dtype': '"""int16"""'}), "(filename, dtype='int16')\n", (4454, 4479), False, 'import soundfile\n')]
# coding=utf-8 # Copyright 2019 The Google NoisyStudent Team 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. from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl import app from absl import flags import os import time import functools import json import tensorflow as tf import numpy as np import utils import preprocessing import data_input FLAGS = flags.FLAGS flags.DEFINE_string('predict_ckpt_path', '', 'The path to the checkpoint for prediction.') flags.DEFINE_string('output_dir', '', 'Directory to store prediction results.') flags.DEFINE_string('info_dir', '', 'Directory to store information for each shard.') flags.DEFINE_integer( 'num_shards', default=128, help='Total number of shards for the dataset.') flags.DEFINE_string( 'shard_id', default='0', help='Between 0 and num_shards - 1. The shard number to run prediction on.') flags.DEFINE_integer( 'total_replicas', default=1, help='Divide a shard into total_replicas copies of data.') flags.DEFINE_integer( 'worker_id', default=0, help='Between 0 and total_replicas - 1.') flags.DEFINE_bool( 'reassign_label', default=False, help='') flags.DEFINE_string( 'data_type', default='tfrecord', help='') flags.DEFINE_string('file_prefix', 'train', '') shard_id = 0 def set_shapes(batch_size, features): """Statically set the batch_size dimension.""" for key in features: if 'image' in key: images = features[key] images.set_shape(images.get_shape().merge_with( tf.TensorShape([batch_size, None, None, None]))) if 'label' in features: features['label'].set_shape(features['label'].get_shape().merge_with( tf.TensorShape([batch_size]))) return features def preprocess(parsed): """Preprocess image for inference.""" features = {} if FLAGS.data_type == 'tfrecord': image = tf.image.decode_jpeg(parsed['image/encoded'], channels=3) features['image'] = preprocessing.preprocess_image( image, is_training=False, image_size=FLAGS.input_image_size, use_bfloat16=FLAGS.use_bfloat16, is_image_bytes=False, ) return features def get_input_fn(params, raw_data=False): batch_size = params['batch_size'] global shard_id if FLAGS.reassign_label: assert FLAGS.data_type == 'tfrecord' filename = os.path.join( FLAGS.label_data_dir, '%s-%d-%05d-of-%05d' % ( FLAGS.file_prefix, FLAGS.worker_id, shard_id, FLAGS.num_shards)) tf.logging.info('processing {}'.format(filename)) # do not use replica here dst = utils.get_dst_from_filename(filename, FLAGS.data_type) else: filename = utils.get_filename(FLAGS.label_data_dir, FLAGS.file_prefix, shard_id, FLAGS.num_shards) tf.logging.info('processing files: {}'.format(str(filename))) dst = utils.get_dst_from_filename(filename, FLAGS.data_type, FLAGS.total_replicas, FLAGS.worker_id) if raw_data: return dst dst = dst.apply( tf.data.experimental.map_and_batch( functools.partial(preprocess), batch_size=batch_size, num_parallel_batches=16, drop_remainder=False)) dst = dst.map(functools.partial(set_shapes, batch_size)) dst = dst.prefetch(tf.data.experimental.AUTOTUNE) return dst def predict_on_dataset(estimator, worker_image_num): if not worker_image_num: return 0, [] global shard_id start_time = time.time() cnt = 0 predict_result_list = [] for i, result in enumerate(estimator.predict( get_input_fn, yield_single_examples=True, checkpoint_path=FLAGS.predict_ckpt_path)): classes = result['probabilities'].argmax() top_1_prob = result['probabilities'].max() new_result = { 'probabilities': result['probabilities'].tolist(), 'label': classes, 'prob': top_1_prob, } predict_result_list += [ new_result ] if i % 100 == 0: elp_time = (time.time() - start_time) / 3600 tf.logging.info( 'prediction finished sample {:d}, expected sample number {:d}'.format( i, worker_image_num)) tf.logging.info( 'elpased time: {:.2f} h, remaining time: {:.2f} h'.format( elp_time, elp_time / (i + 1) * (worker_image_num - i - 1))) cnt += 1 if cnt >= worker_image_num: break print(cnt, worker_image_num, len(predict_result_list), '\n' * 5) return cnt, predict_result_list def get_num_image(): info_file = os.path.join( FLAGS.info_dir, 'info-%.5d-of-%.5d-%.5d.txt' % ( shard_id, FLAGS.num_shards, FLAGS.worker_id)) print(info_file + '\n' * 10) if not FLAGS.reassign_label and tf.gfile.Exists(info_file): with tf.gfile.Open(info_file) as inf: info = json.load(inf) worker_image_num = info['image_num'] tf.logging.info('\n\n\nloaded worker image num') else: tf.logging.info( '\n\n\ngetting worker image num since %s does not exist', info_file) dst = get_input_fn({'batch_size': 1}, raw_data=True) worker_image_num = 0 tf.gfile.MakeDirs(FLAGS.info_dir) for _ in utils.iterate_through_dataset(dst): worker_image_num += 1 if worker_image_num % 100 == 0: tf.logging.info('image num %d', worker_image_num) if not FLAGS.reassign_label: with tf.gfile.Open(info_file, 'w') as ouf: info = { 'image_num': worker_image_num, } json.dump(info, ouf) tf.logging.info('worker image num: %d', worker_image_num) return worker_image_num def run_prediction(estimator): global shard_id shard_id_list = FLAGS.shard_id.split(',') for cur_shard_id in shard_id_list: shard_id = int(cur_shard_id) worker_image_num = get_num_image() cnt, predict_result_list = predict_on_dataset( estimator, worker_image_num) tf.logging.info('predicted on %d images', cnt) assert cnt == worker_image_num, (cnt, worker_image_num) tf.gfile.MakeDirs(FLAGS.output_dir) if FLAGS.reassign_label: sample_dir = os.path.join(FLAGS.output_dir, 'samples') uid_list = utils.get_uid_list() for uid in uid_list: tf.gfile.MakeDirs(os.path.join(sample_dir, uid)) image_bytes_placeholder = tf.placeholder(dtype=tf.string) decoded_image = utils.decode_raw_image(image_bytes_placeholder) raw_dst = get_input_fn({'batch_size': 1}, raw_data=True) raw_iter = raw_dst.make_initializable_iterator() raw_elem = raw_iter.get_next() filename = utils.get_reassign_filename( FLAGS.label_data_dir, FLAGS.file_prefix, shard_id, FLAGS.num_shards, FLAGS.worker_id) record_writer = tf.python_io.TFRecordWriter(os.path.join( FLAGS.output_dir, os.path.basename(filename))) sample_prob = 30000. / (worker_image_num * FLAGS.num_shards) with tf.Session() as sess: sess.run(raw_iter.initializer) for i in range(worker_image_num): features = sess.run(raw_elem) encoded_image = features['image/encoded'] features = {} label = predict_result_list[i]['label'] prob = predict_result_list[i]['prob'] features['image/encoded'] = utils.bytes_feature(encoded_image) features['prob'] = utils.float_feature(prob) features['label'] = utils.int64_feature(label) features['probabilities'] = utils.float_feature(predict_result_list[i]['probabilities']) example = tf.train.Example(features=tf.train.Features(feature=features)) record_writer.write(example.SerializeToString()) if np.random.random() < sample_prob: uid = uid_list[label] filename = os.path.join( sample_dir, uid, 'image_{:d}_{:d}_{:.2f}.jpeg'.format( shard_id, i, prob)) tf.logging.info('saving {:s}'.format(filename)) image = sess.run( decoded_image, feed_dict={image_bytes_placeholder: encoded_image} ) utils.save_pic(image, filename) record_writer.close() else: filename = 'train-info-%.5d-of-%.5d-%.5d' % ( shard_id, FLAGS.num_shards, FLAGS.worker_id) writer = tf.python_io.TFRecordWriter( os.path.join(FLAGS.output_dir, filename)) for result in predict_result_list: features = {} features['probabilities'] = utils.float_feature(result['probabilities']) features['classes'] = utils.int64_feature(result['label']) example = tf.train.Example(features=tf.train.Features(feature=features)) writer.write(example.SerializeToString()) writer.close()
[ "utils.get_uid_list", "utils.get_dst_from_filename", "tensorflow.gfile.MakeDirs", "tensorflow.gfile.Exists", "numpy.random.random", "tensorflow.placeholder", "json.dump", "tensorflow.Session", "utils.save_pic", "utils.decode_raw_image", "utils.iterate_through_dataset", "utils.bytes_feature", ...
[((940, 1034), 'absl.flags.DEFINE_string', 'flags.DEFINE_string', (['"""predict_ckpt_path"""', '""""""', '"""The path to the checkpoint for prediction."""'], {}), "('predict_ckpt_path', '',\n 'The path to the checkpoint for prediction.')\n", (959, 1034), False, 'from absl import flags\n'), ((1032, 1111), 'absl.flags.DEFINE_string', 'flags.DEFINE_string', (['"""output_dir"""', '""""""', '"""Directory to store prediction results."""'], {}), "('output_dir', '', 'Directory to store prediction results.')\n", (1051, 1111), False, 'from absl import flags\n'), ((1113, 1202), 'absl.flags.DEFINE_string', 'flags.DEFINE_string', (['"""info_dir"""', '""""""', '"""Directory to store information for each shard."""'], {}), "('info_dir', '',\n 'Directory to store information for each shard.')\n", (1132, 1202), False, 'from absl import flags\n'), ((1200, 1300), 'absl.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""num_shards"""'], {'default': '(128)', 'help': '"""Total number of shards for the dataset."""'}), "('num_shards', default=128, help=\n 'Total number of shards for the dataset.')\n", (1220, 1300), False, 'from absl import flags\n'), ((1302, 1428), 'absl.flags.DEFINE_string', 'flags.DEFINE_string', (['"""shard_id"""'], {'default': '"""0"""', 'help': '"""Between 0 and num_shards - 1. The shard number to run prediction on."""'}), "('shard_id', default='0', help=\n 'Between 0 and num_shards - 1. The shard number to run prediction on.')\n", (1321, 1428), False, 'from absl import flags\n'), ((1430, 1543), 'absl.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""total_replicas"""'], {'default': '(1)', 'help': '"""Divide a shard into total_replicas copies of data."""'}), "('total_replicas', default=1, help=\n 'Divide a shard into total_replicas copies of data.')\n", (1450, 1543), False, 'from absl import flags\n'), ((1545, 1636), 'absl.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""worker_id"""'], {'default': '(0)', 'help': '"""Between 0 and total_replicas - 1."""'}), "('worker_id', default=0, help=\n 'Between 0 and total_replicas - 1.')\n", (1565, 1636), False, 'from absl import flags\n'), ((1638, 1697), 'absl.flags.DEFINE_bool', 'flags.DEFINE_bool', (['"""reassign_label"""'], {'default': '(False)', 'help': '""""""'}), "('reassign_label', default=False, help='')\n", (1655, 1697), False, 'from absl import flags\n'), ((1704, 1765), 'absl.flags.DEFINE_string', 'flags.DEFINE_string', (['"""data_type"""'], {'default': '"""tfrecord"""', 'help': '""""""'}), "('data_type', default='tfrecord', help='')\n", (1723, 1765), False, 'from absl import flags\n'), ((1772, 1819), 'absl.flags.DEFINE_string', 'flags.DEFINE_string', (['"""file_prefix"""', '"""train"""', '""""""'], {}), "('file_prefix', 'train', '')\n", (1791, 1819), False, 'from absl import flags\n'), ((2479, 2630), 'preprocessing.preprocess_image', 'preprocessing.preprocess_image', (['image'], {'is_training': '(False)', 'image_size': 'FLAGS.input_image_size', 'use_bfloat16': 'FLAGS.use_bfloat16', 'is_image_bytes': '(False)'}), '(image, is_training=False, image_size=FLAGS.\n input_image_size, use_bfloat16=FLAGS.use_bfloat16, is_image_bytes=False)\n', (2509, 2630), False, 'import preprocessing\n'), ((3998, 4009), 'time.time', 'time.time', ([], {}), '()\n', (4007, 4009), False, 'import time\n'), ((5057, 5167), 'os.path.join', 'os.path.join', (['FLAGS.info_dir', "('info-%.5d-of-%.5d-%.5d.txt' % (shard_id, FLAGS.num_shards, FLAGS.worker_id))"], {}), "(FLAGS.info_dir, 'info-%.5d-of-%.5d-%.5d.txt' % (shard_id,\n FLAGS.num_shards, FLAGS.worker_id))\n", (5069, 5167), False, 'import os\n'), ((6027, 6084), 'tensorflow.logging.info', 'tf.logging.info', (['"""worker image num: %d"""', 'worker_image_num'], {}), "('worker image num: %d', worker_image_num)\n", (6042, 6084), True, 'import tensorflow as tf\n'), ((2398, 2455), 'tensorflow.image.decode_jpeg', 'tf.image.decode_jpeg', (["parsed['image/encoded']"], {'channels': '(3)'}), "(parsed['image/encoded'], channels=3)\n", (2418, 2455), True, 'import tensorflow as tf\n'), ((2860, 2988), 'os.path.join', 'os.path.join', (['FLAGS.label_data_dir', "('%s-%d-%05d-of-%05d' % (FLAGS.file_prefix, FLAGS.worker_id, shard_id,\n FLAGS.num_shards))"], {}), "(FLAGS.label_data_dir, '%s-%d-%05d-of-%05d' % (FLAGS.\n file_prefix, FLAGS.worker_id, shard_id, FLAGS.num_shards))\n", (2872, 2988), False, 'import os\n'), ((3120, 3174), 'utils.get_dst_from_filename', 'utils.get_dst_from_filename', (['filename', 'FLAGS.data_type'], {}), '(filename, FLAGS.data_type)\n', (3147, 3174), False, 'import utils\n'), ((3198, 3290), 'utils.get_filename', 'utils.get_filename', (['FLAGS.label_data_dir', 'FLAGS.file_prefix', 'shard_id', 'FLAGS.num_shards'], {}), '(FLAGS.label_data_dir, FLAGS.file_prefix, shard_id, FLAGS\n .num_shards)\n', (3216, 3290), False, 'import utils\n'), ((3396, 3493), 'utils.get_dst_from_filename', 'utils.get_dst_from_filename', (['filename', 'FLAGS.data_type', 'FLAGS.total_replicas', 'FLAGS.worker_id'], {}), '(filename, FLAGS.data_type, FLAGS.total_replicas,\n FLAGS.worker_id)\n', (3423, 3493), False, 'import utils\n'), ((3758, 3799), 'functools.partial', 'functools.partial', (['set_shapes', 'batch_size'], {}), '(set_shapes, batch_size)\n', (3775, 3799), False, 'import functools\n'), ((5253, 5279), 'tensorflow.gfile.Exists', 'tf.gfile.Exists', (['info_file'], {}), '(info_file)\n', (5268, 5279), True, 'import tensorflow as tf\n'), ((5396, 5445), 'tensorflow.logging.info', 'tf.logging.info', (['"""\n\n\nloaded worker image num"""'], {}), '("""\n\n\nloaded worker image num""")\n', (5411, 5445), True, 'import tensorflow as tf\n'), ((5457, 5546), 'tensorflow.logging.info', 'tf.logging.info', (['"""\n\n\ngetting worker image num since %s does not exist"""', 'info_file'], {}), '("""\n\n\ngetting worker image num since %s does not exist""",\n info_file)\n', (5472, 5546), True, 'import tensorflow as tf\n'), ((5637, 5670), 'tensorflow.gfile.MakeDirs', 'tf.gfile.MakeDirs', (['FLAGS.info_dir'], {}), '(FLAGS.info_dir)\n', (5654, 5670), True, 'import tensorflow as tf\n'), ((5684, 5718), 'utils.iterate_through_dataset', 'utils.iterate_through_dataset', (['dst'], {}), '(dst)\n', (5713, 5718), False, 'import utils\n'), ((6408, 6454), 'tensorflow.logging.info', 'tf.logging.info', (['"""predicted on %d images"""', 'cnt'], {}), "('predicted on %d images', cnt)\n", (6423, 6454), True, 'import tensorflow as tf\n'), ((6520, 6555), 'tensorflow.gfile.MakeDirs', 'tf.gfile.MakeDirs', (['FLAGS.output_dir'], {}), '(FLAGS.output_dir)\n', (6537, 6555), True, 'import tensorflow as tf\n'), ((3630, 3659), 'functools.partial', 'functools.partial', (['preprocess'], {}), '(preprocess)\n', (3647, 3659), False, 'import functools\n'), ((5290, 5314), 'tensorflow.gfile.Open', 'tf.gfile.Open', (['info_file'], {}), '(info_file)\n', (5303, 5314), True, 'import tensorflow as tf\n'), ((5336, 5350), 'json.load', 'json.load', (['inf'], {}), '(inf)\n', (5345, 5350), False, 'import json\n'), ((6604, 6645), 'os.path.join', 'os.path.join', (['FLAGS.output_dir', '"""samples"""'], {}), "(FLAGS.output_dir, 'samples')\n", (6616, 6645), False, 'import os\n'), ((6663, 6683), 'utils.get_uid_list', 'utils.get_uid_list', ([], {}), '()\n', (6681, 6683), False, 'import utils\n'), ((6801, 6832), 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': 'tf.string'}), '(dtype=tf.string)\n', (6815, 6832), True, 'import tensorflow as tf\n'), ((6855, 6902), 'utils.decode_raw_image', 'utils.decode_raw_image', (['image_bytes_placeholder'], {}), '(image_bytes_placeholder)\n', (6877, 6902), False, 'import utils\n'), ((7077, 7194), 'utils.get_reassign_filename', 'utils.get_reassign_filename', (['FLAGS.label_data_dir', 'FLAGS.file_prefix', 'shard_id', 'FLAGS.num_shards', 'FLAGS.worker_id'], {}), '(FLAGS.label_data_dir, FLAGS.file_prefix,\n shard_id, FLAGS.num_shards, FLAGS.worker_id)\n', (7104, 7194), False, 'import utils\n'), ((2219, 2247), 'tensorflow.TensorShape', 'tf.TensorShape', (['[batch_size]'], {}), '([batch_size])\n', (2233, 2247), True, 'import tensorflow as tf\n'), ((5794, 5843), 'tensorflow.logging.info', 'tf.logging.info', (['"""image num %d"""', 'worker_image_num'], {}), "('image num %d', worker_image_num)\n", (5809, 5843), True, 'import tensorflow as tf\n'), ((5888, 5917), 'tensorflow.gfile.Open', 'tf.gfile.Open', (['info_file', '"""w"""'], {}), "(info_file, 'w')\n", (5901, 5917), True, 'import tensorflow as tf\n'), ((6004, 6024), 'json.dump', 'json.dump', (['info', 'ouf'], {}), '(info, ouf)\n', (6013, 6024), False, 'import json\n'), ((7411, 7423), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (7421, 7423), True, 'import tensorflow as tf\n'), ((8829, 8869), 'os.path.join', 'os.path.join', (['FLAGS.output_dir', 'filename'], {}), '(FLAGS.output_dir, filename)\n', (8841, 8869), False, 'import os\n'), ((8970, 9014), 'utils.float_feature', 'utils.float_feature', (["result['probabilities']"], {}), "(result['probabilities'])\n", (8989, 9014), False, 'import utils\n'), ((9045, 9081), 'utils.int64_feature', 'utils.int64_feature', (["result['label']"], {}), "(result['label'])\n", (9064, 9081), False, 'import utils\n'), ((2062, 2108), 'tensorflow.TensorShape', 'tf.TensorShape', (['[batch_size, None, None, None]'], {}), '([batch_size, None, None, None])\n', (2076, 2108), True, 'import tensorflow as tf\n'), ((4524, 4535), 'time.time', 'time.time', ([], {}), '()\n', (4533, 4535), False, 'import time\n'), ((6737, 6766), 'os.path.join', 'os.path.join', (['sample_dir', 'uid'], {}), '(sample_dir, uid)\n', (6749, 6766), False, 'import os\n'), ((7304, 7330), 'os.path.basename', 'os.path.basename', (['filename'], {}), '(filename)\n', (7320, 7330), False, 'import os\n'), ((7766, 7800), 'utils.bytes_feature', 'utils.bytes_feature', (['encoded_image'], {}), '(encoded_image)\n', (7785, 7800), False, 'import utils\n'), ((7830, 7855), 'utils.float_feature', 'utils.float_feature', (['prob'], {}), '(prob)\n', (7849, 7855), False, 'import utils\n'), ((7886, 7912), 'utils.int64_feature', 'utils.int64_feature', (['label'], {}), '(label)\n', (7905, 7912), False, 'import utils\n'), ((7951, 8011), 'utils.float_feature', 'utils.float_feature', (["predict_result_list[i]['probabilities']"], {}), "(predict_result_list[i]['probabilities'])\n", (7970, 8011), False, 'import utils\n'), ((8167, 8185), 'numpy.random.random', 'np.random.random', ([], {}), '()\n', (8183, 8185), True, 'import numpy as np\n'), ((8597, 8628), 'utils.save_pic', 'utils.save_pic', (['image', 'filename'], {}), '(image, filename)\n', (8611, 8628), False, 'import utils\n'), ((9127, 9162), 'tensorflow.train.Features', 'tf.train.Features', ([], {'feature': 'features'}), '(feature=features)\n', (9144, 9162), True, 'import tensorflow as tf\n'), ((8058, 8093), 'tensorflow.train.Features', 'tf.train.Features', ([], {'feature': 'features'}), '(feature=features)\n', (8075, 8093), True, 'import tensorflow as tf\n')]
#!/usr/bin/env python # Copyright 2020 <NAME> # License: Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) """ Adopt from my another project: https://github.com/funcwj/setk See https://github.com/funcwj/setk/tree/master/doc/data_simu for command line usage """ import argparse import numpy as np from aps.loader.audio import read_audio, add_room_response from aps.opts import StrToBoolAction from aps.const import EPSILON def coeff_snr(sig_pow, ref_pow, snr): """ For mix = Sa + alpha*Sb Given SNR = 10*log10[Pa/(Pb * alpha^2)] we got alpha = Pa/[Pb*10^(SNR/10)]^0.5 """ return (ref_pow / (sig_pow * 10**(snr / 10) + EPSILON))**0.5 def add_speaker(mix_nsamps, src_spk, src_begin, sdr, src_rir=None, channel=-1, sr=16000): """ Mix source speakers """ spk_image, spk_power = [], [] for i, spk in enumerate(src_spk): if src_rir is None: src = spk[None, ...] if spk.ndim == 1 else spk spk_image.append(src) spk_power.append(np.mean(src[0]**2)) else: rir = src_rir[i] if rir.ndim == 1: rir = rir[None, ...] if channel >= 0: if rir.ndim == 2: rir = rir[channel:channel + 1] revb, p = add_room_response(spk, rir, sr=sr) spk_image.append(revb) spk_power.append(p) # make mix N, _ = spk_image[0].shape mix = [np.zeros([N, mix_nsamps], dtype=np.float32) for _ in src_spk] # start mixing ref_power = spk_power[0] for i, image in enumerate(spk_image): dur = image.shape[-1] beg = src_begin[i] coeff = 1 if i == 0 else coeff_snr(spk_power[i], ref_power, sdr[i]) mix[i][..., beg:beg + dur] += coeff * image return mix def add_point_noise(mix_nsamps, ref_power, noise, noise_begin, snr, noise_rir=None, channel=-1, repeat=False, sr=16000): """ Add pointsource noises """ image = [] image_power = [] for i, noise in enumerate(noise): beg = noise_begin[i] if not repeat: dur = min(noise.shape[-1], mix_nsamps - beg) else: dur = mix_nsamps - beg # if short, then padding if noise.shape[-1] < dur: noise = np.pad(noise, (0, dur - noise.shape[-1]), mode="wrap") if noise_rir is None: src = noise[None, ...] if noise.ndim == 1 else noise image.append(src) image_power.append(np.mean(src[0, :dur]**2) if dur > 0 else 0) else: rir = noise_rir[i] if rir.ndim == 1: rir = rir[None, ...] if channel >= 0: if rir.ndim == 2: rir = rir[channel:channel + 1] revb, revb_power = add_room_response(noise[:dur], rir, sr=sr) image.append(revb) image_power.append(revb_power) # make noise mix N, _ = image[0].shape mix = np.zeros([N, mix_nsamps], dtype=np.float32) # start mixing for i, img in enumerate(image): beg = noise_begin[i] coeff = coeff_snr(image_power[i], ref_power, snr[i]) mix[..., beg:beg + dur] += coeff * img[..., :dur] return mix def load_audio(src_args, beg=None, end=None, sr=16000): """ Load audio from args.xxx """ if src_args: src_path = src_args.split(",") beg_int = [None for _ in src_path] end_int = [None for _ in src_path] if beg: beg_int = [int(v) for v in beg.split(",")] if end: end_int = [int(v) for v in end.split(",")] return [ read_audio(s, sr=sr, beg=b, end=e) for s, b, e in zip(src_path, beg_int, end_int) ] else: return None def run_simu(args): def arg_float(src_args): return [float(s) for s in src_args.split(",")] if src_args else None src_spk = load_audio(args.src_spk, sr=args.sr) src_rir = load_audio(args.src_rir, sr=args.sr) if src_rir: if len(src_rir) != len(src_spk): raise RuntimeError( f"Number of --src-rir={args.src_rir} do not match with " + f"--src-spk={args.src_spk} option") sdr = arg_float(args.src_sdr) if len(src_spk) > 1 and not sdr: raise RuntimeError("--src-sdr need to be assigned for " + f"--src-spk={args.src_spk}") if sdr: if len(src_spk) - 1 != len(sdr): raise RuntimeError("Number of --src-snr - 1 do not match with " + "--src-snr option") sdr = [0] + sdr src_begin = arg_float(args.src_begin) if src_begin: src_begin = [int(v) for v in src_begin] else: src_begin = [0 for _ in src_spk] # number samples of the mixture mix_nsamps = max([b + s.size for b, s in zip(src_begin, src_spk)]) point_noise_rir = load_audio(args.point_noise_rir, sr=args.sr) point_noise_end = [ str(int(v) + mix_nsamps) for v in args.point_noise_offset.split() ] point_noise = load_audio(args.point_noise, beg=args.point_noise_offset, end=",".join(point_noise_end), sr=args.sr) if args.point_noise: if point_noise_rir: if len(point_noise) != len(point_noise_rir): raise RuntimeError( f"Number of --point-noise-rir={args.point_noise_rir} do not match with " + f"--point-noise={args.point_noise} option") point_snr = arg_float(args.point_noise_snr) if not point_snr: raise RuntimeError("--point-noise-snr need to be assigned for " + f"--point-noise={args.point_noise}") if len(point_noise) != len(point_snr): raise RuntimeError( f"Number of --point-noise-snr={args.point_noise_snr} do not match with " + f"--point-noise={args.point_noise} option") point_begin = arg_float(args.point_noise_begin) if point_begin: point_begin = [int(v) for v in point_begin] else: point_begin = [0 for _ in point_noise] isotropic_noise = load_audio(args.isotropic_noise, beg=str(args.isotropic_noise_offset), end=str(args.isotropic_noise_offset + mix_nsamps), sr=args.sr) if isotropic_noise: isotropic_noise = isotropic_noise[0] isotropic_snr = arg_float(args.isotropic_noise_snr) if not isotropic_snr: raise RuntimeError( "--isotropic-snr need to be assigned for " + f"--isotropic-noise={args.isotropic_noise} option") isotropic_snr = isotropic_snr[0] else: isotropic_snr = None # add speakers spk = add_speaker(mix_nsamps, src_spk, src_begin, sdr, src_rir=src_rir, channel=args.dump_channel, sr=args.sr) spk_utt = sum(spk) mix = spk_utt.copy() spk_power = np.mean(spk_utt[0]**2) if point_noise: noise = add_point_noise(mix_nsamps, spk_power, point_noise, point_begin, point_snr, noise_rir=point_noise_rir, channel=args.dump_channel, repeat=args.point_noise_repeat, sr=args.sr) num_channels = spk_utt.shape[0] if num_channels != noise.shape[0]: if num_channels == 1: noise = noise[0:1] else: raise RuntimeError("Channel mismatch between source speaker " + "configuration and pointsource noise's, " + f"{num_channels} vs {noise.shape[0]}") mix = spk_utt + noise else: noise = None ch = args.dump_channel if isotropic_noise is not None: N, _ = spk_utt.shape if N == 1: if isotropic_noise.ndim == 1: isotropic_noise = isotropic_noise[None, ...] else: if ch >= 0: isotropic_noise = isotropic_noise[ch:ch + 1] else: raise RuntimeError( "Single channel mixture vs multi-channel " "isotropic noise") else: if isotropic_noise.shape[0] != N: raise RuntimeError( "Channel number mismatch between mixture and isotropic noise, " + f"{N} vs {isotropic_noise.shape[0]}") dur = min(mix_nsamps, isotropic_noise.shape[-1]) isotropic_chunk = isotropic_noise[0, :dur] power = np.mean(isotropic_chunk**2) coeff = coeff_snr(power, spk_power, isotropic_snr) mix[..., :dur] += coeff * isotropic_chunk if noise is None: noise = coeff * isotropic_chunk else: noise[..., :dur] += coeff * isotropic_chunk factor = args.norm_factor / (np.max(np.abs(mix)) + EPSILON) mix = mix.squeeze() * factor spk = [s[0] * factor for s in spk] if noise is None: return mix, spk, None else: return mix, spk, noise[0] * factor def make_argparse(): parser = argparse.ArgumentParser( description="Command to do audio data simulation", formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument("--src-spk", type=str, required=True, help="Source speakers, e.g., spk1.wav,spk2.wav") parser.add_argument("--src-rir", type=str, default="", help="RIRs for each source speakers") parser.add_argument("--src-sdr", type=str, default="", help="SDR for each speakers (if needed)") parser.add_argument("--src-begin", type=str, default="", help="Begining samples on the mixture utterances") parser.add_argument("--point-noise", type=str, default="", help="Add pointsource noises") parser.add_argument("--point-noise-rir", type=str, default="", help="RIRs of the pointsource noises (if needed)") parser.add_argument("--point-noise-snr", type=str, default="", help="SNR of the pointsource noises") parser.add_argument("--point-noise-begin", type=str, default="", help="Begining samples of the " "pointsource noises on the mixture " "utterances (if needed)") parser.add_argument("--point-noise-offset", type=str, default="", help="Add from the offset position " "of the pointsource noise") parser.add_argument("--point-noise-repeat", action=StrToBoolAction, default="false", help="Repeat the pointsource noise or not") parser.add_argument("--isotropic-noise", type=str, default="", help="Add isotropic noises") parser.add_argument("--isotropic-noise-snr", type=str, default="", help="SNR of the isotropic noises") parser.add_argument("--isotropic-noise-offset", type=int, default=0, help="Add noise from the offset position " "of the isotropic noise") parser.add_argument("--dump-channel", type=int, default=-1, help="Index of the channel to dump out (-1 means all)") parser.add_argument('--norm-factor', type=float, default=0.9, help="Normalization factor of the final output") parser.add_argument("--sr", type=int, default=16000, help="Value of the sample rate") return parser
[ "numpy.mean", "aps.loader.audio.read_audio", "numpy.abs", "argparse.ArgumentParser", "numpy.zeros", "numpy.pad", "aps.loader.audio.add_room_response" ]
[((3261, 3304), 'numpy.zeros', 'np.zeros', (['[N, mix_nsamps]'], {'dtype': 'np.float32'}), '([N, mix_nsamps], dtype=np.float32)\n', (3269, 3304), True, 'import numpy as np\n'), ((7558, 7582), 'numpy.mean', 'np.mean', (['(spk_utt[0] ** 2)'], {}), '(spk_utt[0] ** 2)\n', (7565, 7582), True, 'import numpy as np\n'), ((9932, 10066), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Command to do audio data simulation"""', 'formatter_class': 'argparse.ArgumentDefaultsHelpFormatter'}), "(description='Command to do audio data simulation',\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n", (9955, 10066), False, 'import argparse\n'), ((1564, 1607), 'numpy.zeros', 'np.zeros', (['[N, mix_nsamps]'], {'dtype': 'np.float32'}), '([N, mix_nsamps], dtype=np.float32)\n', (1572, 1607), True, 'import numpy as np\n'), ((9374, 9403), 'numpy.mean', 'np.mean', (['(isotropic_chunk ** 2)'], {}), '(isotropic_chunk ** 2)\n', (9381, 9403), True, 'import numpy as np\n'), ((1406, 1440), 'aps.loader.audio.add_room_response', 'add_room_response', (['spk', 'rir'], {'sr': 'sr'}), '(spk, rir, sr=sr)\n', (1423, 1440), False, 'from aps.loader.audio import read_audio, add_room_response\n'), ((3087, 3129), 'aps.loader.audio.add_room_response', 'add_room_response', (['noise[:dur]', 'rir'], {'sr': 'sr'}), '(noise[:dur], rir, sr=sr)\n', (3104, 3129), False, 'from aps.loader.audio import read_audio, add_room_response\n'), ((3939, 3973), 'aps.loader.audio.read_audio', 'read_audio', (['s'], {'sr': 'sr', 'beg': 'b', 'end': 'e'}), '(s, sr=sr, beg=b, end=e)\n', (3949, 3973), False, 'from aps.loader.audio import read_audio, add_room_response\n'), ((1140, 1160), 'numpy.mean', 'np.mean', (['(src[0] ** 2)'], {}), '(src[0] ** 2)\n', (1147, 1160), True, 'import numpy as np\n'), ((2573, 2627), 'numpy.pad', 'np.pad', (['noise', '(0, dur - noise.shape[-1])'], {'mode': '"""wrap"""'}), "(noise, (0, dur - noise.shape[-1]), mode='wrap')\n", (2579, 2627), True, 'import numpy as np\n'), ((9693, 9704), 'numpy.abs', 'np.abs', (['mix'], {}), '(mix)\n', (9699, 9704), True, 'import numpy as np\n'), ((2786, 2812), 'numpy.mean', 'np.mean', (['(src[0, :dur] ** 2)'], {}), '(src[0, :dur] ** 2)\n', (2793, 2812), True, 'import numpy as np\n')]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Jan 31 15:50:31 2020 @author: Dr. <NAME> European Space Agency (ESA) European Space Research and Technology Centre (ESTEC) Keplerlaan 1, 2201 AZ Noordwijk, The Netherlands Email: <EMAIL> GitHub: mnguenther Twitter: m_n_guenther Web: www.mnguenther.com """ from __future__ import print_function, division, absolute_import #::: plotting settings import seaborn as sns sns.set(context='paper', style='ticks', palette='deep', font='sans-serif', font_scale=1.5, color_codes=True) sns.set_style({"xtick.direction": "in","ytick.direction": "in"}) sns.set_context(rc={'lines.markeredgewidth': 1}) #::: modules import numpy as np import matplotlib.pyplot as plt import os import warnings #::: specific modules try: from wotan import flatten except ImportError: pass #::: my modules import allesfitter from allesfitter.lightcurves import eclipse_width_smart from allesfitter.exoworlds_rdx.lightcurves.index_transits import get_tmid_observed_transits ############################################################################### #::: prepare TTV fit (if chosen) ############################################################################### def prepare_ttv_fit(datadir, ax=None): ''' this must be run *after* reduce_phot_data() ''' ax0 = ax alles = allesfitter.allesclass(datadir) window = alles.settings['fast_fit_width'] if not os.path.exists( os.path.join(datadir,'ttv_preparation') ): os.makedirs(os.path.join(datadir,'ttv_preparation')) with open(os.path.join(datadir,'ttv_preparation','ttv_initial_guess_params.csv'),'w') as f: f.write('') def plot_all_transits_color_coded(): for inst in alles.settings['inst_phot']: time = alles.data[inst]['time'] for companion in alles.settings['companions_phot']: ind = [] for i, t in enumerate(alles.data[companion+'_tmid_observed_transits']): ind += list( np.where((time >= (t - window/2.)) & (time <= (t + window/2.)))[0] ) ax.plot( alles.data[inst]['time'][ind], alles.data[inst]['flux'][ind], ls='none', marker='.', label=companion ) for companion in alles.settings['companions_phot']: with open(os.path.join(datadir,'ttv_preparation','ttv_initial_guess_params.csv'),'a') as f: f.write('#TTV companion '+companion+',,,,,\n') #---------------------------------------------------------------------- #::: get combined data from all instruments #---------------------------------------------------------------------- all_times = [] all_flux = [] for inst in alles.settings['inst_phot']: all_times += list(alles.data[inst]['time']) all_flux += list(alles.data[inst]['flux']) ind_sort = np.argsort(all_times) all_times = np.array(all_times)[ind_sort] all_flux = np.array(all_flux)[ind_sort] #---------------------------------------------------------------------- #::: get eclipse window #---------------------------------------------------------------------- alles.initial_guess_params_median[companion+'_epoch'] eclipse_width = eclipse_width_smart(alles.initial_guess_params_median[companion+'_period'], alles.initial_guess_params_median[companion+'_rr'], alles.initial_guess_params_median[companion+'_rsuma'], alles.initial_guess_params_median[companion+'_cosi'], alles.initial_guess_params_median[companion+'_f_s'], alles.initial_guess_params_median[companion+'_f_c'], )[0] #---------------------------------------------------------------------- #::: compute tmid, ttv_guess and make per-transit-plots #---------------------------------------------------------------------- tmids = [] alles.data[companion+'_tmid_observed_transits'] = get_tmid_observed_transits(all_times,alles.initial_guess_params_median[companion+'_epoch'],alles.initial_guess_params_median[companion+'_period'],alles.settings['fast_fit_width']) N = len(alles.data[companion+'_tmid_observed_transits']) fig, axes = plt.subplots(N, 1, figsize=(6,4*N), sharey=True, tight_layout=True) for i, t in enumerate(alles.data[companion+'_tmid_observed_transits']): ind_tr1 = np.where((all_times >= (t - window/2.)) & (all_times <= (t + window/2.)))[0] tr_times = all_times[ind_tr1] tr_flux = all_flux[ind_tr1] t_exp = np.median(np.diff(tr_times)) N_points_in_eclipse = int(eclipse_width/t_exp) try: trend = flatten(tr_times, tr_flux, window_length=eclipse_width/2., method='biweight', return_trend=True)[1] tmid = np.median( tr_times[ np.argsort(trend)[0:int(N_points_in_eclipse/2.)] ] ) except: warnings.warn('Install wotan for improved performance of prepare_ttv_fit().') trend = None tmid = np.median( tr_times[ np.argsort(tr_times)[0:int(N_points_in_eclipse/2.)] ] ) ttv_guess = tmid - t tmids.append(tmid) ax = axes[i] ax.plot(tr_times, tr_flux, 'b.', rasterized=True) if trend is not None: ax.plot(tr_times, trend, 'r-') ax.axvline(t,c='grey',ls='--',label='linear prediction') ax.axvline(tmid,c='r',ls='--',label='flux minimum') ax.set(xlabel='Time', ylabel='Flux', xlim=[t-window/2., t+window/2.]) ax.text(0.95,0.95,'Transit '+str(i+1), va='top', ha='right', transform=ax.transAxes) with open(os.path.join(datadir,'ttv_preparation','ttv_initial_guess_params.csv'),'a') as f: f.write(companion+'_ttv_transit_'+str(i+1)+','+np.format_float_positional(ttv_guess,4)+',1,uniform '+np.format_float_positional(ttv_guess-0.01,4)+' '+np.format_float_positional(ttv_guess+0.01,4)+',TTV$_\mathrm{'+companion+';'+str(i+1)+'}$,d\n') axes[0].legend() fig.savefig(os.path.join(datadir,'ttv_preparation','ttv_preparation_'+companion+'_per_transit.pdf'), bbox_inches='tight') plt.close(fig) tmids = np.array(tmids) #---------------------------------------------------------------------- #::: ttv guess 0-C plot #---------------------------------------------------------------------- nr = np.array([ int(np.round( (t-tmids[0]) / alles.initial_guess_params_median[companion+'_period'] )) for t in tmids ]) #get corresponding transit number nr -= int(nr[-1]/2.) #shift into the middle of the data set period_mean, epoch_mean = np.polyfit(nr, tmids, 1) fig, axes = plt.subplots(2,1,figsize=(6,8),tight_layout=True,sharex=True) axes[0].plot(nr, tmids, 'bo', label='Companion '+companion) axes[0].plot(nr, epoch_mean + nr * period_mean, 'b-') axes[0].set(xlabel='Nr.', ylabel='Transit mid-time') axes[0].legend() axes[1].plot(nr, tmids-(epoch_mean + nr * period_mean), 'bo') axes[1].axhline(0,c='grey',ls='--') fig.savefig(os.path.join(datadir,'ttv_preparation','ttv_preparation_'+companion+'_oc.pdf'), bbox_inches='tight') period_dev = np.abs( (period_mean-alles.initial_guess_params_median[companion+'_period'])/alles.initial_guess_params_median[companion+'_period'] ) epoch_dev = np.abs( (epoch_mean-alles.initial_guess_params_median[companion+'_epoch'])/alles.initial_guess_params_median[companion+'_epoch'] ) print('\nCompanion', companion) print('Initial guess for mean period and epoch:') print(np.format_float_positional(alles.initial_guess_params_median[companion+'_period']), np.format_float_positional(alles.initial_guess_params_median[companion+'_epoch'])) print('New estimate for mean period and epoch:') print(np.format_float_positional(period_mean,4), np.format_float_positional(epoch_mean,4)) # print('Deviation from another:') # print(np.format_float_positional(period_dev,4), # np.format_float_positional(epoch_dev,4)) if (period_dev > 0.01) or (epoch_dev > 0.01): print('\n! Consider updating your initial guess to these new estimated mean values.') print('\n! If you do, then you must rerun this code.') else: print('\n! Looks great! You are ready to fit.') #---------------------------------------------------------------------- #::: full lightcurve plot #---------------------------------------------------------------------- flux_min = np.nanmin(all_flux) flux_max = np.nanmax(all_flux) if ax0 is None: days = np.max(all_times) - np.min(all_times) figsizex = np.max( [5, 5*(days/10.)] ) fig, ax = plt.subplots(figsize=(figsizex, 4)) #figsize * 5 for every 20 days for inst in alles.settings['inst_phot']: ax.plot(alles.fulldata[inst]['time'], alles.fulldata[inst]['flux'],ls='none',marker='.',color='silver') # ax.plot(alles.data[inst]['time'], alles.data[inst]['flux'],ls='none',marker='.',label=inst) #color code by instrument plot_all_transits_color_coded() #color code by companion ax.plot( alles.data[companion+'_tmid_observed_transits'], np.ones_like(alles.data[companion+'_tmid_observed_transits'])*0.997*flux_min, 'k^', zorder=12 ) for i, tmid in enumerate(alles.data[companion+'_tmid_observed_transits']): ax.text( tmid, 0.992*flux_min, str(i+1), ha='center', zorder=12 ) ax.axvline( tmid, color='grey', zorder=11 ) ax.set(ylim=[0.99*flux_min, 1.002*flux_max], xlabel='Time (BJD)', ylabel='Realtive Flux', title='Companion '+companion) ax.legend(loc='best') fname = os.path.join(datadir,'ttv_preparation','ttv_preparation_'+companion+'.jpg') fig = plt.gcf() fig.savefig(fname, bbox_inches='tight' ) plt.close(fig)
[ "allesfitter.exoworlds_rdx.lightcurves.index_transits.get_tmid_observed_transits", "wotan.flatten", "numpy.polyfit", "seaborn.set_style", "numpy.argsort", "numpy.array", "numpy.nanmin", "seaborn.set", "numpy.where", "numpy.diff", "numpy.max", "matplotlib.pyplot.close", "numpy.nanmax", "num...
[((436, 548), 'seaborn.set', 'sns.set', ([], {'context': '"""paper"""', 'style': '"""ticks"""', 'palette': '"""deep"""', 'font': '"""sans-serif"""', 'font_scale': '(1.5)', 'color_codes': '(True)'}), "(context='paper', style='ticks', palette='deep', font='sans-serif',\n font_scale=1.5, color_codes=True)\n", (443, 548), True, 'import seaborn as sns\n'), ((545, 610), 'seaborn.set_style', 'sns.set_style', (["{'xtick.direction': 'in', 'ytick.direction': 'in'}"], {}), "({'xtick.direction': 'in', 'ytick.direction': 'in'})\n", (558, 610), True, 'import seaborn as sns\n'), ((610, 658), 'seaborn.set_context', 'sns.set_context', ([], {'rc': "{'lines.markeredgewidth': 1}"}), "(rc={'lines.markeredgewidth': 1})\n", (625, 658), True, 'import seaborn as sns\n'), ((1355, 1386), 'allesfitter.allesclass', 'allesfitter.allesclass', (['datadir'], {}), '(datadir)\n', (1377, 1386), False, 'import allesfitter\n'), ((2896, 2917), 'numpy.argsort', 'np.argsort', (['all_times'], {}), '(all_times)\n', (2906, 2917), True, 'import numpy as np\n'), ((4192, 4387), 'allesfitter.exoworlds_rdx.lightcurves.index_transits.get_tmid_observed_transits', 'get_tmid_observed_transits', (['all_times', "alles.initial_guess_params_median[companion + '_epoch']", "alles.initial_guess_params_median[companion + '_period']", "alles.settings['fast_fit_width']"], {}), "(all_times, alles.initial_guess_params_median[\n companion + '_epoch'], alles.initial_guess_params_median[companion +\n '_period'], alles.settings['fast_fit_width'])\n", (4218, 4387), False, 'from allesfitter.exoworlds_rdx.lightcurves.index_transits import get_tmid_observed_transits\n'), ((4457, 4527), 'matplotlib.pyplot.subplots', 'plt.subplots', (['N', '(1)'], {'figsize': '(6, 4 * N)', 'sharey': '(True)', 'tight_layout': '(True)'}), '(N, 1, figsize=(6, 4 * N), sharey=True, tight_layout=True)\n', (4469, 4527), True, 'import matplotlib.pyplot as plt\n'), ((6452, 6466), 'matplotlib.pyplot.close', 'plt.close', (['fig'], {}), '(fig)\n', (6461, 6466), True, 'import matplotlib.pyplot as plt\n'), ((6493, 6508), 'numpy.array', 'np.array', (['tmids'], {}), '(tmids)\n', (6501, 6508), True, 'import numpy as np\n'), ((6984, 7008), 'numpy.polyfit', 'np.polyfit', (['nr', 'tmids', '(1)'], {}), '(nr, tmids, 1)\n', (6994, 7008), True, 'import numpy as np\n'), ((7051, 7117), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(2)', '(1)'], {'figsize': '(6, 8)', 'tight_layout': '(True)', 'sharex': '(True)'}), '(2, 1, figsize=(6, 8), tight_layout=True, sharex=True)\n', (7063, 7117), True, 'import matplotlib.pyplot as plt\n'), ((7594, 7737), 'numpy.abs', 'np.abs', (["((period_mean - alles.initial_guess_params_median[companion + '_period']) /\n alles.initial_guess_params_median[companion + '_period'])"], {}), "((period_mean - alles.initial_guess_params_median[companion +\n '_period']) / alles.initial_guess_params_median[companion + '_period'])\n", (7600, 7737), True, 'import numpy as np\n'), ((7748, 7889), 'numpy.abs', 'np.abs', (["((epoch_mean - alles.initial_guess_params_median[companion + '_epoch']) /\n alles.initial_guess_params_median[companion + '_epoch'])"], {}), "((epoch_mean - alles.initial_guess_params_median[companion + '_epoch'\n ]) / alles.initial_guess_params_median[companion + '_epoch'])\n", (7754, 7889), True, 'import numpy as np\n'), ((9028, 9047), 'numpy.nanmin', 'np.nanmin', (['all_flux'], {}), '(all_flux)\n', (9037, 9047), True, 'import numpy as np\n'), ((9067, 9086), 'numpy.nanmax', 'np.nanmax', (['all_flux'], {}), '(all_flux)\n', (9076, 9086), True, 'import numpy as np\n'), ((10248, 10333), 'os.path.join', 'os.path.join', (['datadir', '"""ttv_preparation"""', "('ttv_preparation_' + companion + '.jpg')"], {}), "(datadir, 'ttv_preparation', 'ttv_preparation_' + companion +\n '.jpg')\n", (10260, 10333), False, 'import os\n'), ((10338, 10347), 'matplotlib.pyplot.gcf', 'plt.gcf', ([], {}), '()\n', (10345, 10347), True, 'import matplotlib.pyplot as plt\n'), ((10407, 10421), 'matplotlib.pyplot.close', 'plt.close', (['fig'], {}), '(fig)\n', (10416, 10421), True, 'import matplotlib.pyplot as plt\n'), ((1468, 1508), 'os.path.join', 'os.path.join', (['datadir', '"""ttv_preparation"""'], {}), "(datadir, 'ttv_preparation')\n", (1480, 1508), False, 'import os\n'), ((1523, 1563), 'os.path.join', 'os.path.join', (['datadir', '"""ttv_preparation"""'], {}), "(datadir, 'ttv_preparation')\n", (1535, 1563), False, 'import os\n'), ((1578, 1650), 'os.path.join', 'os.path.join', (['datadir', '"""ttv_preparation"""', '"""ttv_initial_guess_params.csv"""'], {}), "(datadir, 'ttv_preparation', 'ttv_initial_guess_params.csv')\n", (1590, 1650), False, 'import os\n'), ((2938, 2957), 'numpy.array', 'np.array', (['all_times'], {}), '(all_times)\n', (2946, 2957), True, 'import numpy as np\n'), ((2987, 3005), 'numpy.array', 'np.array', (['all_flux'], {}), '(all_flux)\n', (2995, 3005), True, 'import numpy as np\n'), ((3303, 3682), 'allesfitter.lightcurves.eclipse_width_smart', 'eclipse_width_smart', (["alles.initial_guess_params_median[companion + '_period']", "alles.initial_guess_params_median[companion + '_rr']", "alles.initial_guess_params_median[companion + '_rsuma']", "alles.initial_guess_params_median[companion + '_cosi']", "alles.initial_guess_params_median[companion + '_f_s']", "alles.initial_guess_params_median[companion + '_f_c']"], {}), "(alles.initial_guess_params_median[companion + '_period'\n ], alles.initial_guess_params_median[companion + '_rr'], alles.\n initial_guess_params_median[companion + '_rsuma'], alles.\n initial_guess_params_median[companion + '_cosi'], alles.\n initial_guess_params_median[companion + '_f_s'], alles.\n initial_guess_params_median[companion + '_f_c'])\n", (3322, 3682), False, 'from allesfitter.lightcurves import eclipse_width_smart\n'), ((6334, 6431), 'os.path.join', 'os.path.join', (['datadir', '"""ttv_preparation"""', "('ttv_preparation_' + companion + '_per_transit.pdf')"], {}), "(datadir, 'ttv_preparation', 'ttv_preparation_' + companion +\n '_per_transit.pdf')\n", (6346, 6431), False, 'import os\n'), ((7463, 7551), 'os.path.join', 'os.path.join', (['datadir', '"""ttv_preparation"""', "('ttv_preparation_' + companion + '_oc.pdf')"], {}), "(datadir, 'ttv_preparation', 'ttv_preparation_' + companion +\n '_oc.pdf')\n", (7475, 7551), False, 'import os\n'), ((8000, 8088), 'numpy.format_float_positional', 'np.format_float_positional', (["alles.initial_guess_params_median[companion + '_period']"], {}), "(alles.initial_guess_params_median[companion +\n '_period'])\n", (8026, 8088), True, 'import numpy as np\n'), ((8099, 8186), 'numpy.format_float_positional', 'np.format_float_positional', (["alles.initial_guess_params_median[companion + '_epoch']"], {}), "(alles.initial_guess_params_median[companion +\n '_epoch'])\n", (8125, 8186), True, 'import numpy as np\n'), ((8253, 8295), 'numpy.format_float_positional', 'np.format_float_positional', (['period_mean', '(4)'], {}), '(period_mean, 4)\n', (8279, 8295), True, 'import numpy as np\n'), ((8311, 8352), 'numpy.format_float_positional', 'np.format_float_positional', (['epoch_mean', '(4)'], {}), '(epoch_mean, 4)\n', (8337, 8352), True, 'import numpy as np\n'), ((9191, 9221), 'numpy.max', 'np.max', (['[5, 5 * (days / 10.0)]'], {}), '([5, 5 * (days / 10.0)])\n', (9197, 9221), True, 'import numpy as np\n'), ((9241, 9276), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(figsizex, 4)'}), '(figsize=(figsizex, 4))\n', (9253, 9276), True, 'import matplotlib.pyplot as plt\n'), ((2310, 2382), 'os.path.join', 'os.path.join', (['datadir', '"""ttv_preparation"""', '"""ttv_initial_guess_params.csv"""'], {}), "(datadir, 'ttv_preparation', 'ttv_initial_guess_params.csv')\n", (2322, 2382), False, 'import os\n'), ((4636, 4711), 'numpy.where', 'np.where', (['((all_times >= t - window / 2.0) & (all_times <= t + window / 2.0))'], {}), '((all_times >= t - window / 2.0) & (all_times <= t + window / 2.0))\n', (4644, 4711), True, 'import numpy as np\n'), ((4825, 4842), 'numpy.diff', 'np.diff', (['tr_times'], {}), '(tr_times)\n', (4832, 4842), True, 'import numpy as np\n'), ((9130, 9147), 'numpy.max', 'np.max', (['all_times'], {}), '(all_times)\n', (9136, 9147), True, 'import numpy as np\n'), ((9150, 9167), 'numpy.min', 'np.min', (['all_times'], {}), '(all_times)\n', (9156, 9167), True, 'import numpy as np\n'), ((4944, 5048), 'wotan.flatten', 'flatten', (['tr_times', 'tr_flux'], {'window_length': '(eclipse_width / 2.0)', 'method': '"""biweight"""', 'return_trend': '(True)'}), "(tr_times, tr_flux, window_length=eclipse_width / 2.0, method=\n 'biweight', return_trend=True)\n", (4951, 5048), False, 'from wotan import flatten\n'), ((5177, 5254), 'warnings.warn', 'warnings.warn', (['"""Install wotan for improved performance of prepare_ttv_fit()."""'], {}), "('Install wotan for improved performance of prepare_ttv_fit().')\n", (5190, 5254), False, 'import warnings\n'), ((5947, 6019), 'os.path.join', 'os.path.join', (['datadir', '"""ttv_preparation"""', '"""ttv_initial_guess_params.csv"""'], {}), "(datadir, 'ttv_preparation', 'ttv_initial_guess_params.csv')\n", (5959, 6019), False, 'import os\n'), ((6747, 6834), 'numpy.round', 'np.round', (["((t - tmids[0]) / alles.initial_guess_params_median[companion + '_period'])"], {}), "((t - tmids[0]) / alles.initial_guess_params_median[companion +\n '_period'])\n", (6755, 6834), True, 'import numpy as np\n'), ((9753, 9816), 'numpy.ones_like', 'np.ones_like', (["alles.data[companion + '_tmid_observed_transits']"], {}), "(alles.data[companion + '_tmid_observed_transits'])\n", (9765, 9816), True, 'import numpy as np\n'), ((2029, 2094), 'numpy.where', 'np.where', (['((time >= t - window / 2.0) & (time <= t + window / 2.0))'], {}), '((time >= t - window / 2.0) & (time <= t + window / 2.0))\n', (2037, 2094), True, 'import numpy as np\n'), ((5088, 5105), 'numpy.argsort', 'np.argsort', (['trend'], {}), '(trend)\n', (5098, 5105), True, 'import numpy as np\n'), ((5328, 5348), 'numpy.argsort', 'np.argsort', (['tr_times'], {}), '(tr_times)\n', (5338, 5348), True, 'import numpy as np\n'), ((6194, 6241), 'numpy.format_float_positional', 'np.format_float_positional', (['(ttv_guess + 0.01)', '(4)'], {}), '(ttv_guess + 0.01, 4)\n', (6220, 6241), True, 'import numpy as np\n'), ((6145, 6192), 'numpy.format_float_positional', 'np.format_float_positional', (['(ttv_guess - 0.01)', '(4)'], {}), '(ttv_guess - 0.01, 4)\n', (6171, 6192), True, 'import numpy as np\n'), ((6091, 6131), 'numpy.format_float_positional', 'np.format_float_positional', (['ttv_guess', '(4)'], {}), '(ttv_guess, 4)\n', (6117, 6131), True, 'import numpy as np\n')]
from operator import itemgetter import pandas as pd import numpy as np import matplotlib.pyplot as plt import matplotlib from openreview_matcher.evals import base_evaluator from openreview_matcher import utils matplotlib.style.use('ggplot') class Evaluator(base_evaluator.Evaluator): """ An Evaluator instance that evaluates precision_at_m = (number of papers reviewers bid positively on in top M) / (total number of papers retrieved) This evaluation method requires us to look at the bids, so we import them from somewhere in the __init__() method """ def __init__(self, params=None): datapath = params["data_path"] self.m_values = params["m_values"] self.data = utils.load_obj(datapath) self.bids_by_forum = self.data["bids_by_forum"] def evaluate(self, ranklists): """ Evaluate the model using a ranked list. Either you can evaluate using a single ranked list or evaluate against each individual query and average their precision scores Arguments @ranklists: a list of tuples. The 0th index of the tuple contains the forum ID of the rank of the list being evaluated The 1st index of the tuple contains a list of reviewer IDS, in order of expertise score Returns a generator object that yields an array of scores for each ranked list. If only one score is need, return the score in an array by itself """ return self.evaluate_using_single_rank(ranklists) def evaluate_using_individual_queries(self, ranklists): """ Evaluate using individual query ranks """ for forum, rank_list in ranklists: scores = [] for m in self.m_values: positive_labels = ["I want to review", "I can review"] positive_bids = [bid.signatures[0].encode('utf-8') for bid in self.bids_by_forum[forum] if bid.tag in positive_labels] relevant_reviewers = [1 if reviewer_id in positive_bids else 0 for reviewer_id in rank_list] precision = self.precision_at_m(relevant_reviewers, m) scores.append(precision) yield forum, scores def setup_ranked_list(self, rank_list): """ Setup the single ranked list for a model Combines all of the individual query ranks into one single rank """ new_rank_list = [] for forum, rank_list in rank_list: for reviewer_score in rank_list: reviewer = reviewer_score.split(";")[0] score = float(reviewer_score.split(";")[1]) has_bid = self.reviewer_has_bid(reviewer, forum) # filter for reviewers that gave a bid value if has_bid: new_rank_list.append((reviewer, score, forum)) ranked_reviewers = sorted(new_rank_list, key=itemgetter(1), reverse=True) return ranked_reviewers def reviewer_has_bid(self, reviewer, paper): """ Returns True if the reviewer bid on that 'paper' """ paper_bids = self.bids_by_forum[paper] has_bid = [True if bid.signatures[0] == reviewer.decode("utf-8") else False for bid in paper_bids][0] return has_bid def get_bid_for_reviewer_paper(self, reviewer, paper): """ Gets the bid for the reviewer and the paper Returns 0 if the bid is not relevant and 1 if the bid is relevant """ positive_labels = ['I want to review', 'I can review'] paper_bids = self.bids_by_forum[paper] bid_value = [1 if bid.tag in positive_labels else 0 for bid in paper_bids if bid.signatures[0] == reviewer.decode('utf-8')] if len(bid_value) > 0: return bid_value[0] else: return 0 def evaluate_using_single_rank(self, rank_list): """ Evaluate against a single ranked list computed by the model """ ranked_reviewers = self.setup_ranked_list(rank_list) scores = [] positive_bids = 0 for reviewer, score, forum in ranked_reviewers: bid = self.get_bid_for_reviewer_paper(reviewer, forum) if bid == 1: positive_bids +=1 for m in range(1, len(ranked_reviewers) + 1): topM = ranked_reviewers[0: m] topM = map(lambda reviewer: (reviewer[0], self.get_bid_for_reviewer_paper(reviewer[0], reviewer[2])), topM) pos_bids_from_topM = [bid for bid in topM if bid[1] == 1] precision = float(len(pos_bids_from_topM)) / float(m) # precision => relevant bids retrieved / # of retrieved scores.append((m, precision)) return scores def precision_at_m(self, ranked_list, m): """ Computes precision at M Arguments: ranked_list: ranked list of reviewers for a forum where each entry is either a 0 or 1 1 - reviewer that reviewer wanted to bid 0 - reviewer did not want to bid m: cuttoff value Returns: A float representing the precision """ topM = np.asarray(ranked_list)[:m] != 0 return np.mean(topM) def graph_precision_values(self, precision_values): """ Graph the recall values against M values """ fig, ax = plt.subplots() df_recall = pd.DataFrame({ '@M': range(1, len(precision_values)+1), 'Recall': precision_values }) ax = df_recall.plot.line(x="@M", y="Recall", ax=ax) ax.set_title("Recall Curve", y=1.08) ax.set_ylabel("Recall") fig.savefig("results/figures/{0}".format("recall_curve_bow_avg"), dpi=200)
[ "numpy.mean", "openreview_matcher.utils.load_obj", "numpy.asarray", "matplotlib.style.use", "operator.itemgetter", "matplotlib.pyplot.subplots" ]
[((213, 243), 'matplotlib.style.use', 'matplotlib.style.use', (['"""ggplot"""'], {}), "('ggplot')\n", (233, 243), False, 'import matplotlib\n'), ((740, 764), 'openreview_matcher.utils.load_obj', 'utils.load_obj', (['datapath'], {}), '(datapath)\n', (754, 764), False, 'from openreview_matcher import utils\n'), ((5292, 5305), 'numpy.mean', 'np.mean', (['topM'], {}), '(topM)\n', (5299, 5305), True, 'import numpy as np\n'), ((5438, 5452), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (5450, 5452), True, 'import matplotlib.pyplot as plt\n'), ((2936, 2949), 'operator.itemgetter', 'itemgetter', (['(1)'], {}), '(1)\n', (2946, 2949), False, 'from operator import itemgetter\n'), ((5244, 5267), 'numpy.asarray', 'np.asarray', (['ranked_list'], {}), '(ranked_list)\n', (5254, 5267), True, 'import numpy as np\n')]
import unittest import io from svgelements import * class TestElementShape(unittest.TestCase): def test_rect_dict(self): values = { 'tag': 'rect', 'rx': "4", 'ry': "2", 'x': "50", 'y': "51", 'width': "20", 'height': "10" } e = Rect(values) e2 = Rect(50, 51, 20, 10, 4, 2) self.assertEqual(e, e2) e2 *= "translate(2)" e3 = Rect() self.assertNotEqual(e, e3) def test_line_dict(self): values = { 'tag': 'rect', 'x1': "0", 'y1': "0", 'x2': "100", 'y2': "100" } e = SimpleLine(values) e2 = SimpleLine(0, '0px', '100px', '100px') e3 = SimpleLine(0, 0, 100, 100) self.assertEqual(e, e2) self.assertEqual(e, e3) e4 = SimpleLine() self.assertNotEqual(e, e4) def test_ellipse_dict(self): values = { 'tag': 'ellipse', 'rx': "4.0", 'ry': "8.0", 'cx': "22.4", 'cy': "33.33" } e = Ellipse(values) e2 = Ellipse(22.4, 33.33, 4, 8) self.assertEqual(e, e2) e3 = Ellipse() self.assertNotEqual(e, e3) def test_circle_dict(self): values = { 'tag': 'circle', 'r': "4.0", 'cx': "22.4", 'cy': "33.33" } e = Circle(values) e2 = Circle(22.4, 33.33, 4) self.assertEqual(e, e2) e3 = Circle() self.assertNotEqual(e, e3) circle_d = e.d() self.assertEqual(Path(circle_d), 'M26.4,33.33A4,4 0 0,1 22.4,37.33 A4,4 0 0,1 18.4,33.33 A4,4 0 0,1 22.4,29.33 A4,4 0 0,1 26.4,33.33Z') def test_polyline_dict(self): values = { 'tag': 'polyline', 'points': '0,100 50,25 50,75 100,0', } e = Polyline(values) e2 = Polyline(0, 100, 50, 25, 50, 75, 100, 0) self.assertEqual(e, e2) e3 = Polyline() self.assertNotEqual(e, e3) polyline_d = e.d() self.assertEqual(Path(polyline_d), "M 0,100 L 50,25 L 50,75 L 100,0") def test_polygon_dict(self): values = { 'tag': 'polyline', 'points': '0,100 50,25 50,75 100,0', } e = Polygon(values) e2 = Polygon(0, 100, 50, 25, 50, 75, 100, 0) self.assertEqual(e, e2) e3 = Polygon() self.assertNotEqual(e, e3) polygon_d = e.d() self.assertEqual(Path(polygon_d), 'M 0,100 L 50,25 L 50,75 L 100,0 Z') def test_circle_ellipse_equal(self): self.assertTrue(Ellipse(center=(0, 0), rx=10, ry=10) == Circle(center="0,0", r=10.0)) def test_transform_circle_to_ellipse(self): c = Circle(center="0,0", r=10.0) p = c * Matrix.skew_x(Angle.degrees(50)) p.reify() p = c * "translate(10,1)" p.reify() p = c * "scale(10,1)" p.reify() p = c * "rotate(10deg)" p.reify() p = c * "skewy(10)" p.reify() self.assertFalse(isinstance(Circle(), Ellipse)) self.assertFalse(isinstance(Ellipse(), Circle)) def test_circle_decomp(self): circle = Circle() c = Path(circle.d()) self.assertEqual(c, "M 1,0 A 1,1 0 0,1 0,1 A 1,1 0 0,1 -1,0 A 1,1 0 0,1 0,-1 A 1,1 0 0,1 1,0 Z") circle *= "scale(2,1)" c = Path(circle.d()) self.assertEqual(c, "M 2,0 A 2,1 0 0,1 0,1 A 2,1 0 0,1 -2,0 A 2,1 0 0,1 0,-1 A 2,1 0 0,1 2,0 Z") circle *= "scale(0.5,1)" c = Path(circle.d()) self.assertEqual(c, "M 1,0 A 1,1 0 0,1 0,1 A 1,1 0 0,1 -1,0 A 1,1 0 0,1 0,-1 A 1,1 0 0,1 1,0 Z") def test_circle_implicit(self): shape = Circle() shape *= "translate(40,40) rotate(15deg) scale(2,1.5)" self.assertAlmostEqual(shape.implicit_rx, 2.0) self.assertAlmostEqual(shape.implicit_ry, 1.5) self.assertAlmostEqual(shape.rotation, Angle.degrees(15)) self.assertEqual(shape.implicit_center, (40, 40)) def test_rect_implicit(self): shape = Rect() shape *= "translate(40,40) rotate(15deg) scale(2,1.5)" self.assertAlmostEqual(shape.implicit_x, 40) self.assertAlmostEqual(shape.implicit_y, 40) self.assertAlmostEqual(shape.implicit_width, 2) self.assertAlmostEqual(shape.implicit_height, 1.5) self.assertAlmostEqual(shape.implicit_rx, 0) self.assertAlmostEqual(shape.implicit_ry, 0) self.assertAlmostEqual(shape.rotation, Angle.degrees(15)) def test_line_implicit(self): shape = SimpleLine(0, 0, 1, 1) shape *= "translate(40,40) rotate(15deg) scale(2,1.5)" self.assertAlmostEqual(shape.implicit_x1, 40) self.assertAlmostEqual(shape.implicit_y1, 40) p = Point(1, 1) * "rotate(15deg) scale(2,1.5)" self.assertAlmostEqual(shape.implicit_x2, 40 + p[0]) self.assertAlmostEqual(shape.implicit_y2, 40 + p[1]) self.assertAlmostEqual(shape.rotation, Angle.degrees(15)) def test_circle_equals_transformed_circle(self): shape1 = Circle(r=2) shape2 = Circle().set('vector-effect', 'non-scaling-stroke') * "scale(2)" self.assertEqual(shape1, shape2) shape2.reify() self.assertEqual(shape1, shape2) def test_rect_equals_transformed_rect(self): shape1 = Rect(x=0, y=0, width=2, height=2) shape2 = Rect(0, 0, 1, 1).set('vector-effect', 'non-scaling-stroke') * "scale(2)" self.assertEqual(shape1, shape2) shape2.reify() self.assertEqual(shape1, shape2) def test_rrect_equals_transformed_rrect(self): shape1 = Rect(0, 0, 2, 2, 1, 1) shape2 = Rect(0, 0, 1, 1, 0.5, 0.5).set('vector-effect', 'non-scaling-stroke') * "scale(2)" self.assertEqual(shape1, shape2) shape2.reify() self.assertEqual(shape1, shape2) def test_line_equals_transformed_line(self): shape1 = SimpleLine(0, 0, 2, 2) shape2 = SimpleLine(0, 0, 1, 1).set('vector-effect', 'non-scaling-stroke') * "scale(2)" self.assertEqual(shape1, shape2) shape2.reify() self.assertEqual(shape1, shape2) def test_polyline_equals_transformed_polyline(self): shape1 = Polyline(0, 0, 2, 2) shape2 = Polyline(0, 0, 1, 1).set('vector-effect', 'non-scaling-stroke') * "scale(2)" self.assertEqual(shape1, shape2) shape2.reify() self.assertEqual(shape1, shape2) def test_polygon_equals_transformed_polygon(self): shape1 = Polyline(0, 0, 2, 2) shape2 = Polyline(0, 0, 1, 1).set('vector-effect', 'non-scaling-stroke') * "scale(2)" self.assertEqual(shape1, shape2) shape2.reify() self.assertEqual(shape1, shape2) def test_polyline_not_equal_transformed_polygon(self): shape1 = Polyline(0, 0, 2, 2) shape2 = Polygon(0, 0, 1, 1) * "scale(2)" self.assertNotEqual(shape1, shape2) def test_polyline_closed_equals_transformed_polygon(self): shape1 = Path(Polyline(0, 0, 2, 2)) + "z" shape2 = Polygon(0, 0, 1, 1).set('vector-effect', 'non-scaling-stroke') * "scale(2)" self.assertEqual(shape1, shape2) def test_path_plus_shape(self): path = Path("M 0,0 z") path += Rect(0, 0, 1, 1) self.assertEqual(path, "M0,0zM0,0h1v1h-1z") def test_circle_not_equal_red_circle(self): shape1 = Circle() shape2 = Circle(stroke="red") self.assertNotEqual(shape1, shape2) shape1 = Circle() shape2 = Circle(fill="red") self.assertNotEqual(shape1, shape2) def test_rect_initialize(self): shapes = ( Rect(), Rect(0), Rect(0, 0), Rect(0, 0, 1), Rect(0, 0, 1, 1), Rect(0, y=0), Rect(0, y=0, width=1), Rect(0, y=0, width=1, height=1), Rect(width=1, height=1, x=0, y=0), Rect(0, 0, 1, 1, 0, 0), Rect(0, 0, 1, 1, rx=0, ry=0) ) for s in shapes: self.assertEqual(shapes[0], s) def test_circle_initialize(self): shapes = ( Circle(), Circle(0, 0), Circle(center=(0, 0), r=1), Circle("0px", "0px", 1), Ellipse("0", "0", 1, 1), Ellipse("0", "0", rx=1, ry=1), Ellipse(0, 0, 1, ry=1), Circle(Circle()), Circle({"cx": 0, "cy": 0, "r": 1}), Ellipse({"cx": 0, "cy": 0, "rx": 1}), Ellipse({"cx": 0, "cy": 0, "ry": 1}), Ellipse({"cx": 0, "cy": 0, "rx": 1, "ry": 1.0}), Circle(Ellipse()), Ellipse(Circle()) ) for s in shapes: self.assertEqual(shapes[0], s) def test_polyline_initialize(self): shapes = ( Polyline(0, 0, 1, 1), Polyline((0, 0), (1, 1)), Polyline(points=((0, 0), (1, 1))), Polyline("0,0", "1,1"), Polyline("0,0", (1, 1)), Polyline("0,0", Point(1, 1)), Polyline({"points": "0,0,1,1"}), Polyline(Polyline(0, 0, 1, 1)), Path("M0,0L1,1"), SimpleLine(0, 0, 1, 1), ) for s in shapes: self.assertEqual(shapes[0], s) def test_polygon_initialize(self): shapes = ( Polygon(0, 0, 1, 1), Polygon((0, 0), (1, 1)), Polygon(points=((0, 0), (1, 1))), Polygon("0,0", "1,1"), Polygon("0,0", (1, 1)), Polygon("0,0", Point(1, 1)), Polygon({"points": "0,0,1,1"}), Polygon(Polyline(0, 0, 1, 1)), Polygon("0,0,1,1"), Path("M0,0L1,1z"), ) for s in shapes: self.assertEqual(shapes[0], s) def test_shapes_repr(self): s = Rect(fill='red') self.assertEqual(repr(s), "Rect(width=1, height=1, fill='#ff0000')") s = Ellipse(fill='red') self.assertEqual(repr(s), "Ellipse(cx=0, cy=0, r=1, fill='#ff0000')") s = Circle(fill='red') self.assertEqual(repr(s), "Circle(cx=0, cy=0, r=1, fill='#ff0000')") s = SimpleLine(fill='red') self.assertEqual(repr(s), "SimpleLine(x1=0.0, y1=0.0, x2=0.0, y2=0.0, fill='#ff0000')") s = Polygon(fill='red') self.assertEqual(repr(s), "Polygon(points='', fill='#ff0000')") s = Polyline(fill='red') self.assertEqual(repr(s), "Polyline(points='', fill='#ff0000')") s = Path(fill='red') self.assertEqual(repr(s), "Path(fill='#ff0000')") def test_shape_bbox(self): s = Rect() * 'scale(20)' self.assertEqual(s.bbox(False), (0, 0, 1, 1)) self.assertEqual(s.bbox(True), (0, 0, 20, 20)) self.assertNotEqual(s.bbox(False), (0, 0, 20, 20)) self.assertNotEqual(s.bbox(True), (0, 0, 1, 1)) s = Circle() * 'scale(20)' self.assertEqual(s.bbox(False), (-1, -1, 1, 1)) self.assertEqual(s.bbox(True), (-20, -20, 20, 20)) self.assertNotEqual(s.bbox(False), (-20, -20, 20, 20)) self.assertNotEqual(s.bbox(True), (-1, -1, 1, 1)) s = Ellipse() * 'scale(20)' self.assertEqual(s.bbox(False), (-1, -1, 1, 1)) self.assertEqual(s.bbox(True), (-20, -20, 20, 20)) self.assertNotEqual(s.bbox(False), (-20, -20, 20, 20)) self.assertNotEqual(s.bbox(True), (-1, -1, 1, 1)) s = Polygon() * 'scale(20)' self.assertEqual(s.bbox(False), None) self.assertEqual(s.bbox(True), None) self.assertNotEqual(s.bbox(False), (0, 0, 0, 0)) self.assertNotEqual(s.bbox(True), (0, 0, 0, 0)) s = Polyline() * 'scale(20)' self.assertEqual(s.bbox(False), None) self.assertEqual(s.bbox(True), None) self.assertNotEqual(s.bbox(False), (0, 0, 0, 0)) self.assertNotEqual(s.bbox(True), (0, 0, 0, 0)) s = Polygon("0,0 0,1 1,1 1,0 0,0") * 'scale(20)' self.assertEqual(s.bbox(False), (0, 0, 1, 1)) self.assertEqual(s.bbox(True), (0, 0, 20, 20)) self.assertNotEqual(s.bbox(False), (0, 0, 20, 20)) self.assertNotEqual(s.bbox(True), (0, 0, 1, 1)) s = Polyline("0,0 0,1 1,1 1,0 0,0") * 'scale(20)' self.assertEqual(s.bbox(False), (0, 0, 1, 1)) self.assertEqual(s.bbox(True), (0, 0, 20, 20)) self.assertNotEqual(s.bbox(False), (0, 0, 20, 20)) self.assertNotEqual(s.bbox(True), (0, 0, 1, 1)) s = SimpleLine(0, 0, 1, 1) * 'scale(20)' self.assertEqual(s.bbox(False), (0, 0, 1, 1)) self.assertEqual(s.bbox(True), (0, 0, 20, 20)) self.assertNotEqual(s.bbox(False), (0, 0, 20, 20)) self.assertNotEqual(s.bbox(True), (0, 0, 1, 1)) def test_rect_rot_equal_rect_path_rotate(self): r = Rect(10, 10, 8, 4) a = r.d() b = Path(a).d() self.assertEqual(a, b) a = (Path(r.d()) * "rotate(0.5turns)").d() b = (r * "rotate(0.5turns)").d() self.assertEqual(a, b) def test_rect_reify(self): """Reifying a rotated rect.""" reification_checks(self, Rect()) reification_checks(self, Rect(2, 2, 4, 4)) shape = Rect() * "rotate(-90) translate(20,0)" t = Rect(0, -20, 1, 1) t *= "rotate(-90, 0, -20)" self.assertEqual(t, shape) def test_circle_reify(self): """Reifying a rotated circle.""" reification_checks(self, Circle()) reification_checks(self, Circle(2, 2, 4, 4)) def test_ellipse_reify(self): """Reifying a rotated ellipse.""" reification_checks(self, Ellipse(rx=1, ry=2)) reification_checks(self, Ellipse(2, 2, 5, 8)) def test_polyline_reify(self): """Reifying a rotated polyline.""" reification_checks(self, Polyline("0,0 1,1 2,2")) reification_checks(self, Polyline("0,0 1,1 2,0")) def test_polygon_reify(self): """Reifying a rotated polygon.""" reification_checks(self, Polygon("0,0 1,1 2,2")) reification_checks(self, Polygon("0,0 1,1 2,0")) def test_line_reify(self): """Reifying a rotated line.""" reification_checks(self, SimpleLine(0, 0, 1, 1)) reification_checks(self, SimpleLine(2, 2, 1, 0)) def test_path_reify(self): """Reifying a path.""" reification_checks(self, Path("M0,0L1,1L1,0z")) reification_checks(self, Path("M100,100L70,70L45,0z")) def test_shapes_degenerate(self): """Testing Degenerate Shapes""" self.assertEqual(Rect(0, 0, 0, 100).d(), '') self.assertEqual(Rect(0, 0, 100, 0).d(), '') self.assertEqual(Circle(0, 0, 0).d(), '') self.assertEqual(Ellipse(0,0,0,100).d(), '') self.assertEqual(Ellipse(0, 0, 100, 0).d(), '') self.assertEqual(Polygon(points='').d(), '') def test_issue_95(self): """Testing Issue 95 stroke-width""" q = io.StringIO(u'''<?xml version="1.0" encoding="utf-8" ?> <svg> <ellipse style="stroke:#fc0000;stroke-width:1;fill:none" cx="0" cy="0" rx="1" ry="1" transform="scale(100) rotate(-90,0,0)"/> <rect style="stroke:#fc0000;stroke-width:1;fill:none" x="0" y="0" width="10" height="10" transform="scale(100) rotate(-90,0,0)"/> </svg>''') m = SVG.parse(q) ellipse = m[0] for i in range(5): ellipse = ellipse.reify() self.assertEqual(ellipse.stroke_width, 1.0) rect = m[1] for i in range(5): rect = rect.reify() self.assertEqual(rect.stroke_width, 1.0) def test_issue_99(self): """Test Issue of inverted circle reified location""" q = io.StringIO(u'''<?xml version="1.0" encoding="utf-8" ?> <svg width="82.475mm" height="35.215mm" viewBox="24.766026 -242.607513 82.475082 35.214996" version="1.1" > <circle transform="scale(1,-1)" style="opacity:0.99;fill:none;stroke:#ff0000;stroke-width:0.0264584;stroke-miterlimit:4;stroke-dasharray:none" r="2" cx="100.41245" cy="211.59723" id="circle2" /></svg> ''') m = SVG.parse(q, reify=False) q = copy(m[0]) r = copy(m[0]) self.assertEqual(q, r) q.reify() r = Path(r) q = Path(q) self.assertEqual(q, r) r.reify() q.reify() self.assertEqual(q, r) def test_issue_99b(self): """Test Issue of double inverted circle reified location""" q = io.StringIO(u'''<?xml version="1.0" encoding="utf-8" ?> <svg width="82.475mm" height="35.215mm" viewBox="24.766026 -242.607513 82.475082 35.214996" version="1.1" > <circle transform="scale(-1,-1)" style="opacity:0.99;fill:none;stroke:#ff0000;stroke-width:0.0264584;stroke-miterlimit:4;stroke-dasharray:none" r="2" cx="100.41245" cy="211.59723" id="circle2" /></svg> ''') m = SVG.parse(q, reify=False) q = copy(m[0]) r = copy(m[0]) self.assertEqual(q, r) q.reify() r = Path(r) q = Path(q) self.assertEqual(q, r) r.reify() q.reify() self.assertEqual(q, r) def test_issue_99c(self): """Test Issue of inverted rect reified location""" q = io.StringIO(u'''<?xml version="1.0" encoding="utf-8" ?> <svg width="82.475mm" height="35.215mm" viewBox="24.766026 -242.607513 82.475082 35.214996" version="1.1" > <rect transform="scale(1,-1)" style="opacity:0.99;fill:none;stroke:#ff0000;stroke-width:0.0264584;stroke-miterlimit:4;stroke-dasharray:none" rx="2" x="100.41245" y="211.59723" width="100" height="100" id="circle2" /></svg> ''') m = SVG.parse(q, reify=False) q = copy(m[0]) r = copy(m[0]) self.assertEqual(q, r) q.reify() r = Path(r) q = Path(q) self.assertEqual(q, r) r.reify() q.reify() self.assertEqual(q, r) def test_issue_99d(self): """Test Issue of double inverted rect reified location""" q = io.StringIO(u'''<?xml version="1.0" encoding="utf-8" ?> <svg width="82.475mm" height="35.215mm" viewBox="24.766026 -242.607513 82.475082 35.214996" version="1.1" > <rect transform="scale(-1,-1)" style="opacity:0.99;fill:none;stroke:#ff0000;stroke-width:0.0264584;stroke-miterlimit:4;stroke-dasharray:none" rx="2" x="100.41245" y="211.59723" width="100" height="100" id="circle2" /></svg> ''') m = SVG.parse(q, reify=False) q = copy(m[0]) r = copy(m[0]) self.assertEqual(q, r) q.reify() r = Path(r) q = Path(q) self.assertEqual(q, r) r.reify() q.reify() self.assertEqual(q, r) def test_issue_104(self): """Testing Issue 104 degenerate parsing""" q = io.StringIO(u'''<?xml version="1.0" encoding="utf-8" ?> <svg> <polygon points=""/> <polygon/> <rect x="0" y="0" width="0" height="10"/> <circle cx="0" cy="0" r="0"/> </svg>''') m = SVG.parse(q) self.assertEqual(len(m), 0) def test_rect_strict(self): values = { 'tag': 'rect', 'rx': "-4", 'x': "50", 'y': "51", 'width': "20", 'height': "10" } e = Rect(values) e2 = Rect(50, 51, 20, 10) self.assertEqual(e, e2) e3 = Rect(values) e3._strict = False # unstrict rx-negative rectangles, have scooped corners. self.assertNotEqual(e3, e2) values['ry'] = 4 e4 = Rect(values) self.assertEqual(e, e4) def test_shape_npoints(self): import numpy as np shapes = [ Rect(10, 20, 300, 340), Circle(10, 10, 5), Ellipse(50, 50, 30, 20), Polygon(points=((10, 10), (20, 30), (50, 20))), Polyline(points=((10, 10), (20, 30), (50, 20), (100, 120))), ] for shape in shapes: pos = np.linspace(0, 1, 1000) # with disable_numpy(): pts1 = shape.npoint(pos) # Test rendered worthless. pts2 = shape.npoint(pos) for p, p1, p2 in zip(pos, pts1, pts2): self.assertEqual(shape.point(p), Point(p1)) self.assertEqual(Point(p1), Point(p2)) def reification_checks(test, shape): correct_reify(test, shape * "rotate(-90) translate(20,0)") correct_reify(test, shape * "rotate(12turn)") correct_reify(test, shape * "translate(20,0)") correct_reify(test, shape * "scale(2) translate(20,0)") correct_reify(test, shape * "rotate(90) scale(-1) translate(20,0)") correct_reify(test, shape * "rotate(90) translate(20,0)") correct_reify(test, shape * "skewX(10)") correct_reify(test, shape * "skewY(10)") def correct_reify(test, shape): path = abs(Path(shape)) reified = abs(copy(shape)) test.assertEqual(path, shape) test.assertEqual(reified, shape) test.assertEqual(reified, path)
[ "io.StringIO", "numpy.linspace" ]
[((15475, 15909), 'io.StringIO', 'io.StringIO', (['u"""<?xml version="1.0" encoding="utf-8" ?>\n <svg>\n <ellipse style="stroke:#fc0000;stroke-width:1;fill:none" cx="0" cy="0" rx="1" ry="1" transform="scale(100) rotate(-90,0,0)"/>\n <rect style="stroke:#fc0000;stroke-width:1;fill:none" x="0" y="0" width="10" height="10" transform="scale(100) rotate(-90,0,0)"/>\n </svg>"""'], {}), '(\n u"""<?xml version="1.0" encoding="utf-8" ?>\n <svg>\n <ellipse style="stroke:#fc0000;stroke-width:1;fill:none" cx="0" cy="0" rx="1" ry="1" transform="scale(100) rotate(-90,0,0)"/>\n <rect style="stroke:#fc0000;stroke-width:1;fill:none" x="0" y="0" width="10" height="10" transform="scale(100) rotate(-90,0,0)"/>\n </svg>"""\n )\n', (15486, 15909), False, 'import io\n'), ((16315, 17054), 'io.StringIO', 'io.StringIO', (['u"""<?xml version="1.0" encoding="utf-8" ?>\n <svg\n width="82.475mm"\n height="35.215mm"\n viewBox="24.766026 -242.607513 82.475082 35.214996"\n version="1.1"\n >\n <circle\n transform="scale(1,-1)"\n style="opacity:0.99;fill:none;stroke:#ff0000;stroke-width:0.0264584;stroke-miterlimit:4;stroke-dasharray:none"\n r="2"\n cx="100.41245"\n cy="211.59723"\n id="circle2" /></svg>\n """'], {}), '(\n u"""<?xml version="1.0" encoding="utf-8" ?>\n <svg\n width="82.475mm"\n height="35.215mm"\n viewBox="24.766026 -242.607513 82.475082 35.214996"\n version="1.1"\n >\n <circle\n transform="scale(1,-1)"\n style="opacity:0.99;fill:none;stroke:#ff0000;stroke-width:0.0264584;stroke-miterlimit:4;stroke-dasharray:none"\n r="2"\n cx="100.41245"\n cy="211.59723"\n id="circle2" /></svg>\n """\n )\n', (16326, 17054), False, 'import io\n'), ((17456, 18196), 'io.StringIO', 'io.StringIO', (['u"""<?xml version="1.0" encoding="utf-8" ?>\n <svg\n width="82.475mm"\n height="35.215mm"\n viewBox="24.766026 -242.607513 82.475082 35.214996"\n version="1.1"\n >\n <circle\n transform="scale(-1,-1)"\n style="opacity:0.99;fill:none;stroke:#ff0000;stroke-width:0.0264584;stroke-miterlimit:4;stroke-dasharray:none"\n r="2"\n cx="100.41245"\n cy="211.59723"\n id="circle2" /></svg>\n """'], {}), '(\n u"""<?xml version="1.0" encoding="utf-8" ?>\n <svg\n width="82.475mm"\n height="35.215mm"\n viewBox="24.766026 -242.607513 82.475082 35.214996"\n version="1.1"\n >\n <circle\n transform="scale(-1,-1)"\n style="opacity:0.99;fill:none;stroke:#ff0000;stroke-width:0.0264584;stroke-miterlimit:4;stroke-dasharray:none"\n r="2"\n cx="100.41245"\n cy="211.59723"\n id="circle2" /></svg>\n """\n )\n', (17467, 18196), False, 'import io\n'), ((18589, 19406), 'io.StringIO', 'io.StringIO', (['u"""<?xml version="1.0" encoding="utf-8" ?>\n <svg\n width="82.475mm"\n height="35.215mm"\n viewBox="24.766026 -242.607513 82.475082 35.214996"\n version="1.1"\n >\n <rect\n transform="scale(1,-1)"\n style="opacity:0.99;fill:none;stroke:#ff0000;stroke-width:0.0264584;stroke-miterlimit:4;stroke-dasharray:none"\n rx="2"\n x="100.41245"\n y="211.59723"\n width="100"\n height="100"\n id="circle2" /></svg>\n """'], {}), '(\n u"""<?xml version="1.0" encoding="utf-8" ?>\n <svg\n width="82.475mm"\n height="35.215mm"\n viewBox="24.766026 -242.607513 82.475082 35.214996"\n version="1.1"\n >\n <rect\n transform="scale(1,-1)"\n style="opacity:0.99;fill:none;stroke:#ff0000;stroke-width:0.0264584;stroke-miterlimit:4;stroke-dasharray:none"\n rx="2"\n x="100.41245"\n y="211.59723"\n width="100"\n height="100"\n id="circle2" /></svg>\n """\n )\n', (18600, 19406), False, 'import io\n'), ((19808, 20626), 'io.StringIO', 'io.StringIO', (['u"""<?xml version="1.0" encoding="utf-8" ?>\n <svg\n width="82.475mm"\n height="35.215mm"\n viewBox="24.766026 -242.607513 82.475082 35.214996"\n version="1.1"\n >\n <rect\n transform="scale(-1,-1)"\n style="opacity:0.99;fill:none;stroke:#ff0000;stroke-width:0.0264584;stroke-miterlimit:4;stroke-dasharray:none"\n rx="2"\n x="100.41245"\n y="211.59723"\n width="100"\n height="100"\n id="circle2" /></svg>\n """'], {}), '(\n u"""<?xml version="1.0" encoding="utf-8" ?>\n <svg\n width="82.475mm"\n height="35.215mm"\n viewBox="24.766026 -242.607513 82.475082 35.214996"\n version="1.1"\n >\n <rect\n transform="scale(-1,-1)"\n style="opacity:0.99;fill:none;stroke:#ff0000;stroke-width:0.0264584;stroke-miterlimit:4;stroke-dasharray:none"\n rx="2"\n x="100.41245"\n y="211.59723"\n width="100"\n height="100"\n id="circle2" /></svg>\n """\n )\n', (19819, 20626), False, 'import io\n'), ((21013, 21343), 'io.StringIO', 'io.StringIO', (['u"""<?xml version="1.0" encoding="utf-8" ?>\n <svg>\n <polygon points=""/>\n <polygon/>\n <rect x="0" y="0" width="0" height="10"/>\n <circle cx="0" cy="0" r="0"/>\n </svg>"""'], {}), '(\n u"""<?xml version="1.0" encoding="utf-8" ?>\n <svg>\n <polygon points=""/>\n <polygon/>\n <rect x="0" y="0" width="0" height="10"/>\n <circle cx="0" cy="0" r="0"/>\n </svg>"""\n )\n', (21024, 21343), False, 'import io\n'), ((22349, 22372), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', '(1000)'], {}), '(0, 1, 1000)\n', (22360, 22372), True, 'import numpy as np\n')]
import numpy as np import math def snr_plot(model, snrs, lbl, test_idx, X_test, Y_test, classes): # Plot confusion matrix acc = {} for snr in snrs: # extract classes @ SNR test_SNRs = list(map(lambda x: lbl[x][1], test_idx)) test_X_i = X_test[np.where(np.array(test_SNRs) == snr)] test_Y_i = Y_test[np.where(np.array(test_SNRs) == snr)] # estimate classes test_Y_i_hat = model.predict(test_X_i) conf = np.zeros([len(classes), len(classes)]) confnorm = np.zeros([len(classes), len(classes)]) for i in range(0, test_X_i.shape[0]): j = list(test_Y_i[i, :]).index(1) k = int(np.argmax(test_Y_i_hat[i, :])) conf[j, k] = conf[j, k] + 1 for i in range(0, len(classes)): confnorm[i, :] = conf[i, :] / np.sum(conf[i, :]) cor = np.sum(np.diag(conf)) ncor = np.sum(conf) - cor print(snr, "dB, Overall Accuracy: ", cor / (cor + ncor)) acc[snr] = 1.0 * cor / (cor + ncor) return acc def SNR_singlech(S, SN): S = S-np.mean(S)# 消除直流分量 S = S/np.max(np.abs(S))#幅值归一化 mean_S = (np.sum(S))/(len(S))#纯信号的平均值 PS = np.sum((S-mean_S)*(S-mean_S)) PN = np.sum((S-SN)*(S-SN)) snr=10*math.log((PS/PN), 10) return(snr)
[ "numpy.mean", "numpy.abs", "numpy.argmax", "numpy.diag", "math.log", "numpy.sum", "numpy.array" ]
[((1188, 1223), 'numpy.sum', 'np.sum', (['((S - mean_S) * (S - mean_S))'], {}), '((S - mean_S) * (S - mean_S))\n', (1194, 1223), True, 'import numpy as np\n'), ((1227, 1254), 'numpy.sum', 'np.sum', (['((S - SN) * (S - SN))'], {}), '((S - SN) * (S - SN))\n', (1233, 1254), True, 'import numpy as np\n'), ((1084, 1094), 'numpy.mean', 'np.mean', (['S'], {}), '(S)\n', (1091, 1094), True, 'import numpy as np\n'), ((1151, 1160), 'numpy.sum', 'np.sum', (['S'], {}), '(S)\n', (1157, 1160), True, 'import numpy as np\n'), ((1260, 1281), 'math.log', 'math.log', (['(PS / PN)', '(10)'], {}), '(PS / PN, 10)\n', (1268, 1281), False, 'import math\n'), ((876, 889), 'numpy.diag', 'np.diag', (['conf'], {}), '(conf)\n', (883, 889), True, 'import numpy as np\n'), ((906, 918), 'numpy.sum', 'np.sum', (['conf'], {}), '(conf)\n', (912, 918), True, 'import numpy as np\n'), ((1120, 1129), 'numpy.abs', 'np.abs', (['S'], {}), '(S)\n', (1126, 1129), True, 'import numpy as np\n'), ((681, 710), 'numpy.argmax', 'np.argmax', (['test_Y_i_hat[i, :]'], {}), '(test_Y_i_hat[i, :])\n', (690, 710), True, 'import numpy as np\n'), ((835, 853), 'numpy.sum', 'np.sum', (['conf[i, :]'], {}), '(conf[i, :])\n', (841, 853), True, 'import numpy as np\n'), ((289, 308), 'numpy.array', 'np.array', (['test_SNRs'], {}), '(test_SNRs)\n', (297, 308), True, 'import numpy as np\n'), ((353, 372), 'numpy.array', 'np.array', (['test_SNRs'], {}), '(test_SNRs)\n', (361, 372), True, 'import numpy as np\n')]
import os import argparse import pickle as pk import numpy as np import matplotlib.pyplot as plt import torch import torch.nn as nn from stgcn import STGCN from GaussianCopula import CopulaLoss from utils import generate_dataset, load_metr_la_data, get_normalized_adj use_gpu = True num_timesteps_input = 12 num_timesteps_output = 3 seed = 7 epochs = 1000 patience = 30 batch_size = 50 parser = argparse.ArgumentParser(description='STGCN') parser.add_argument('--enable-cuda', action='store_true', help='Enable CUDA') args = parser.parse_args() args.device = None if args.enable_cuda and torch.cuda.is_available(): args.device = torch.device('cuda') else: args.device = torch.device('cpu') print(args.enable_cuda) print(torch.cuda.is_available()) print(args.device) def train_epoch(training_input, training_target, batch_size): """ Trains one epoch with the given data. :param training_input: Training inputs of shape (num_samples, num_nodes, num_timesteps_train, num_features). :param training_target: Training targets of shape (num_samples, num_nodes, num_timesteps_predict). :param batch_size: Batch size to use during training. :return: Average loss for this epoch. """ permutation = torch.randperm(training_input.shape[0]) epoch_training_losses = [] for i in range(0, training_input.shape[0], batch_size): net.train() optimizer.zero_grad() indices = permutation[i:i + batch_size] X_batch, y_batch = training_input[indices], training_target[indices] X_batch = X_batch.to(device=args.device) y_batch = y_batch.to(device=args.device) out = net(A_wave, X_batch) loss = loss_criterion(out, y_batch) loss.backward() optimizer.step() epoch_training_losses.append(loss.detach().cpu().numpy()) return sum(epoch_training_losses)/len(epoch_training_losses) if __name__ == '__main__': torch.manual_seed(seed) A, X, means, stds = load_metr_la_data() split_line1 = int(X.shape[2] * 0.6) split_line2 = int(X.shape[2] * 0.8) train_original_data = X[:, :, :split_line1] val_original_data = X[:, :, split_line1:split_line2] test_original_data = X[:, :, split_line2:] training_input, training_target = generate_dataset(train_original_data, num_timesteps_input=num_timesteps_input, num_timesteps_output=num_timesteps_output) val_input, val_target = generate_dataset(val_original_data, num_timesteps_input=num_timesteps_input, num_timesteps_output=num_timesteps_output) test_input, test_target = generate_dataset(test_original_data, num_timesteps_input=num_timesteps_input, num_timesteps_output=num_timesteps_output) A_wave = get_normalized_adj(A) A_wave = torch.from_numpy(A_wave) A_wave = A_wave.to(device=args.device) net = STGCN(A_wave.shape[0], training_input.shape[3], num_timesteps_input, num_timesteps_output).to(device=args.device) optimizer = torch.optim.Adam(net.parameters(), lr=1e-3) loss_criterion = CopulaLoss() training_losses = [] validation_losses = [] validation_maes = [] plt.ion() fig, axes = plt.subplots(1, figsize=(10, 5)) plt.suptitle('STGCN Training') axes.set_xlabel('Epoch') axes.set_ylabel('Loss') rem = patience idx = 0 best_loss = float('inf') for epoch in range(epochs): # Early stop if patience < 0: break loss = train_epoch(training_input, training_target, batch_size=batch_size) training_losses.append(loss) # Run validation with torch.no_grad(): net.eval() val_input = val_input.to(device=args.device) val_target = val_target.to(device=args.device) permutation = torch.randperm(training_input.shape[0]) val_loss_batch = [] mae_batch = [] for i in range(0, training_input.shape[0], batch_size): indices = permutation[i:i + batch_size] X_batch, y_batch = training_input[indices], training_target[indices] X_batch = X_batch.to(device=args.device) y_batch = y_batch.to(device=args.device) out = net(A_wave, X_batch) val_loss = loss_criterion(out, y_batch).to(device="cpu") val_loss_batch.append(val_loss.detach().numpy().item()) out_unnormalized = out.detach().cpu().numpy()*stds[0]+means[0] target_unnormalized = y_batch.detach().cpu().numpy()*stds[0]+means[0] mae = np.mean(np.absolute(out_unnormalized - target_unnormalized)) mae_batch.append(mae) validation_losses.append(np.mean(val_loss_batch)) validation_maes.append(np.mean(mae_batch)) out = None val_input = val_input.to(device="cpu") val_target = val_target.to(device="cpu") print("\nEpoch: {}".format(epoch)) print("Training loss: {}".format(training_losses[-1])) print("Validation loss: {}".format(validation_losses[-1])) print("Validation MAE: {}".format(validation_maes[-1])) checkpoint_path = "checkpoints/" if not os.path.exists(checkpoint_path): os.makedirs(checkpoint_path) with open("checkpoints/losses.pk", "wb") as fd: pk.dump((training_losses, validation_losses, validation_maes), fd) valid_loss = validation_losses[-1] if valid_loss < best_loss: rem = patience best_loss = valid_loss idx = epoch rem -= 1 print("\nThe MSE loss on test dataset is:", validation_losses[idx]) print("The MAE on test dataset is:", validation_maes[idx]) print("This is obtained in epoch", idx) plt.plot(training_losses, label="training loss") plt.plot(validation_losses, label="validation loss") plt.plot(validation_maes, label="validation MAE") plt.legend() fig.savefig("STGCN_training_{}".format(seed), dpi=200) plt.show()
[ "torch.randperm", "torch.from_numpy", "torch.cuda.is_available", "utils.get_normalized_adj", "utils.generate_dataset", "os.path.exists", "numpy.mean", "argparse.ArgumentParser", "GaussianCopula.CopulaLoss", "matplotlib.pyplot.plot", "utils.load_metr_la_data", "stgcn.STGCN", "matplotlib.pyplo...
[((400, 444), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""STGCN"""'}), "(description='STGCN')\n", (423, 444), False, 'import argparse\n'), ((613, 638), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (636, 638), False, 'import torch\n'), ((658, 678), 'torch.device', 'torch.device', (['"""cuda"""'], {}), "('cuda')\n", (670, 678), False, 'import torch\n'), ((703, 722), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (715, 722), False, 'import torch\n'), ((753, 778), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (776, 778), False, 'import torch\n'), ((1263, 1302), 'torch.randperm', 'torch.randperm', (['training_input.shape[0]'], {}), '(training_input.shape[0])\n', (1277, 1302), False, 'import torch\n'), ((1962, 1985), 'torch.manual_seed', 'torch.manual_seed', (['seed'], {}), '(seed)\n', (1979, 1985), False, 'import torch\n'), ((2011, 2030), 'utils.load_metr_la_data', 'load_metr_la_data', ([], {}), '()\n', (2028, 2030), False, 'from utils import generate_dataset, load_metr_la_data, get_normalized_adj\n'), ((2304, 2430), 'utils.generate_dataset', 'generate_dataset', (['train_original_data'], {'num_timesteps_input': 'num_timesteps_input', 'num_timesteps_output': 'num_timesteps_output'}), '(train_original_data, num_timesteps_input=\n num_timesteps_input, num_timesteps_output=num_timesteps_output)\n', (2320, 2430), False, 'from utils import generate_dataset, load_metr_la_data, get_normalized_adj\n'), ((2564, 2687), 'utils.generate_dataset', 'generate_dataset', (['val_original_data'], {'num_timesteps_input': 'num_timesteps_input', 'num_timesteps_output': 'num_timesteps_output'}), '(val_original_data, num_timesteps_input=num_timesteps_input,\n num_timesteps_output=num_timesteps_output)\n', (2580, 2687), False, 'from utils import generate_dataset, load_metr_la_data, get_normalized_adj\n'), ((2804, 2929), 'utils.generate_dataset', 'generate_dataset', (['test_original_data'], {'num_timesteps_input': 'num_timesteps_input', 'num_timesteps_output': 'num_timesteps_output'}), '(test_original_data, num_timesteps_input=\n num_timesteps_input, num_timesteps_output=num_timesteps_output)\n', (2820, 2929), False, 'from utils import generate_dataset, load_metr_la_data, get_normalized_adj\n'), ((3033, 3054), 'utils.get_normalized_adj', 'get_normalized_adj', (['A'], {}), '(A)\n', (3051, 3054), False, 'from utils import generate_dataset, load_metr_la_data, get_normalized_adj\n'), ((3068, 3092), 'torch.from_numpy', 'torch.from_numpy', (['A_wave'], {}), '(A_wave)\n', (3084, 3092), False, 'import torch\n'), ((3392, 3404), 'GaussianCopula.CopulaLoss', 'CopulaLoss', ([], {}), '()\n', (3402, 3404), False, 'from GaussianCopula import CopulaLoss\n'), ((3488, 3497), 'matplotlib.pyplot.ion', 'plt.ion', ([], {}), '()\n', (3495, 3497), True, 'import matplotlib.pyplot as plt\n'), ((3514, 3546), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)'], {'figsize': '(10, 5)'}), '(1, figsize=(10, 5))\n', (3526, 3546), True, 'import matplotlib.pyplot as plt\n'), ((3551, 3581), 'matplotlib.pyplot.suptitle', 'plt.suptitle', (['"""STGCN Training"""'], {}), "('STGCN Training')\n", (3563, 3581), True, 'import matplotlib.pyplot as plt\n'), ((6183, 6231), 'matplotlib.pyplot.plot', 'plt.plot', (['training_losses'], {'label': '"""training loss"""'}), "(training_losses, label='training loss')\n", (6191, 6231), True, 'import matplotlib.pyplot as plt\n'), ((6236, 6288), 'matplotlib.pyplot.plot', 'plt.plot', (['validation_losses'], {'label': '"""validation loss"""'}), "(validation_losses, label='validation loss')\n", (6244, 6288), True, 'import matplotlib.pyplot as plt\n'), ((6293, 6342), 'matplotlib.pyplot.plot', 'plt.plot', (['validation_maes'], {'label': '"""validation MAE"""'}), "(validation_maes, label='validation MAE')\n", (6301, 6342), True, 'import matplotlib.pyplot as plt\n'), ((6347, 6359), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (6357, 6359), True, 'import matplotlib.pyplot as plt\n'), ((6423, 6433), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (6431, 6433), True, 'import matplotlib.pyplot as plt\n'), ((3148, 3242), 'stgcn.STGCN', 'STGCN', (['A_wave.shape[0]', 'training_input.shape[3]', 'num_timesteps_input', 'num_timesteps_output'], {}), '(A_wave.shape[0], training_input.shape[3], num_timesteps_input,\n num_timesteps_output)\n', (3153, 3242), False, 'from stgcn import STGCN\n'), ((3984, 3999), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (3997, 3999), False, 'import torch\n'), ((4166, 4205), 'torch.randperm', 'torch.randperm', (['training_input.shape[0]'], {}), '(training_input.shape[0])\n', (4180, 4205), False, 'import torch\n'), ((5606, 5637), 'os.path.exists', 'os.path.exists', (['checkpoint_path'], {}), '(checkpoint_path)\n', (5620, 5637), False, 'import os\n'), ((5651, 5679), 'os.makedirs', 'os.makedirs', (['checkpoint_path'], {}), '(checkpoint_path)\n', (5662, 5679), False, 'import os\n'), ((5748, 5814), 'pickle.dump', 'pk.dump', (['(training_losses, validation_losses, validation_maes)', 'fd'], {}), '((training_losses, validation_losses, validation_maes), fd)\n', (5755, 5814), True, 'import pickle as pk\n'), ((5103, 5126), 'numpy.mean', 'np.mean', (['val_loss_batch'], {}), '(val_loss_batch)\n', (5110, 5126), True, 'import numpy as np\n'), ((5163, 5181), 'numpy.mean', 'np.mean', (['mae_batch'], {}), '(mae_batch)\n', (5170, 5181), True, 'import numpy as np\n'), ((4974, 5025), 'numpy.absolute', 'np.absolute', (['(out_unnormalized - target_unnormalized)'], {}), '(out_unnormalized - target_unnormalized)\n', (4985, 5025), True, 'import numpy as np\n')]
# Author: <NAME> import numpy as np from collections import defaultdict from agent import * ############################################### mdp = createMDP() # Escolhe próximo estado dado uma ação def performAction(pi, P): def nextState(s): ps = P[(s, pi[s])] probs = list(map(lambda x: x[0], ps)) states = list(map(lambda x: x[1], ps)) idx = np.random.choice(len(states), p=probs) return states[idx] return nextState # Estimação direta def directEst(model, s, goals, R, gamma, nextState, maxLen=20): trial = [(s, R[s])] while s not in goals: s = nextState(s) trial.append( (s, R[s]) ) if len(trial) > maxLen: break #return None for i, (s, r) in enumerate(trial): u = sum(r*(gamma**j) for j, (si, r) in enumerate(trial[i:])) model[s] = (model[s][0] + u, model[s][1] + 1) return model def runDirectEst(mdp, pi, nTrials): S, A, R, P, gamma = mdp model = defaultdict(lambda: (0.0, 0)) s0 = (1,1) goals = [(4,3), (4,2)] for trials in range(nTrials): model = directEst(model, s0, goals, R, gamma, performAction(pi, P)) if model is None: break return model def evaluate(mdp, pi, nTrials): model = runDirectEst(mdp, pi, nTrials) if model is None: U = { s:-np.inf for s in mdp[0] } else: U = {} for s, (v, n) in model.items(): U[s] = v/n return U def avalia(pi): U = evaluate(mdp, pi, 10) return U[(1,1)] class Individuo: def __init__(self, cromossomo = None): self.cromossomo = cromossomo if cromossomo is None: self.cromossomo = np.random.choice(["UP", "DOWN", "LEFT", "RIGHT"], 12) self.pi = {(i,j):self.cromossomo[3*i + j - 4] for i in range(1,5) for j in range(1,4)} self.fitness = avalia(self.pi) def tournament(P): idx1, idx2 = np.random.choice(len(P), 2) if P[idx1].fitness > P[idx2].fitness: return P[idx1] return P[idx2] def seleciona(P, n): return [tournament(P) for _ in range(n)] def muta(p): cromossomo = p.cromossomo idx = np.random.choice(len(cromossomo)) cromossomo[idx] = np.random.choice(["UP", "DOWN", "LEFT", "RIGHT"]) return Individuo(cromossomo) def cruza(p1, p2): cromossomo1 = p1.cromossomo cromossomo2 = p2.cromossomo idx = np.random.choice(len(cromossomo1)) return Individuo(np.append(cromossomo1[:idx], cromossomo2[idx:])) def cruzamento(P): return [cruza(seleciona(P, 1)[0], seleciona(P, 1)[0]) for _ in range(len(P))] def mutacao(P): return [muta(p) for p in P] def melhor(P): fitness = [(-p.fitness, i) for i, p in enumerate(P)] idx = sorted(fitness)[0][1] return P[idx] def GA(): P = [Individuo() for _ in range(100)] for it in range(100): filhos = cruzamento(P) filhos = mutacao(filhos) P = seleciona(P + filhos, len(P)) print(it, melhor(P).fitness) return melhor(P) p = GA() print(p.pi, p.fitness)
[ "numpy.random.choice", "collections.defaultdict", "numpy.append" ]
[((1035, 1065), 'collections.defaultdict', 'defaultdict', (['(lambda : (0.0, 0))'], {}), '(lambda : (0.0, 0))\n', (1046, 1065), False, 'from collections import defaultdict\n'), ((2328, 2377), 'numpy.random.choice', 'np.random.choice', (["['UP', 'DOWN', 'LEFT', 'RIGHT']"], {}), "(['UP', 'DOWN', 'LEFT', 'RIGHT'])\n", (2344, 2377), True, 'import numpy as np\n'), ((2569, 2616), 'numpy.append', 'np.append', (['cromossomo1[:idx]', 'cromossomo2[idx:]'], {}), '(cromossomo1[:idx], cromossomo2[idx:])\n', (2578, 2616), True, 'import numpy as np\n'), ((1778, 1831), 'numpy.random.choice', 'np.random.choice', (["['UP', 'DOWN', 'LEFT', 'RIGHT']", '(12)'], {}), "(['UP', 'DOWN', 'LEFT', 'RIGHT'], 12)\n", (1794, 1831), True, 'import numpy as np\n')]
import grpc import time from concurrent import futures import drivers.xarm.wrapper.xarm_api as arm import robot_con.xarm_shuidi.shuidi.shuidi_robot as agv import robot_con.xarm_shuidi.xarm_shuidi_pb2 as aa_msg # aa = arm_agv import robot_con.xarm_shuidi.xarm_shuidi_pb2_grpc as aa_rpc import numpy as np class XArmShuidiServer(aa_rpc.XArmShuidiServicer): def __init__(self, arm_ip, agv_ip="192.168.10.10"): """ :param _arm_x: an instancde of arm.XArmAPI :return: """ super().__init__() self._arm_x = arm.XArmAPI(port=arm_ip) if self._arm_x.has_err_warn: if self._arm_x.get_err_warn_code()[1][0] == 1: print("The Emergency Button is pushed in to stop!") input("Release the emergency button and press any key to continue. Press Enter to continue...") self._arm_x.clean_error() self._arm_x.clean_error() self._arm_x.motion_enable() self._arm_x.set_mode(1) # servo motion mode self._arm_x.set_state(state=0) self._arm_x.reset(wait=True) self._arm_x.clean_gripper_error() self._arm_x.set_gripper_enable(1) self._arm_x.set_gripper_mode(0) self.__speed = 5000 self._arm_x.set_gripper_speed(self.__speed) # 1000-5000 self._arm_x.set_gripper_position(850) # 1000-5000 self._agv_x = agv.ShuidiRobot(ip=agv_ip) def arm_get_jnt_values(self, request, context): code, jnt_values = self._arm_x.get_servo_angle(is_radian=True) if code != 0: raise Exception(f"The returned code of get_servo_angle is wrong! Code: {code}") return aa_msg.JntValues(data=np.array(jnt_values).tobytes()) def arm_move_jspace_path(self, request, context): nrow = request.length ncol = request.njnts flat_path_data = np.frombuffer(request.data, dtype=np.float64) path = flat_path_data.reshape((nrow, ncol)) for jnt_values in path.tolist(): self._arm_x.set_servo_angle_j(jnt_values, is_radian=True) time.sleep(.01) return aa_msg.Status(value=aa_msg.Status.DONE) def arm_jaw_to(self, request, context): self.__speed = request.speed self._arm_x.set_gripper_speed(self.__speed) self._arm_x.set_gripper_position(request.position, wait=True) return aa_msg.Status(value=aa_msg.Status.DONE) def arm_get_gripper_status(self, request, context): speed = self.__speed code, position = self._arm_x.get_gripper_position() if code != 0: raise Exception(f"The returned code of get_gripper_position is wrong! Code: {code}") return aa_msg.GripperStatus(speed=speed, position=position) def agv_mov(self, request, context): linear_speed = request.agv_linear_speed angular_speed = request.agv_angular_speed self._agv_x.joy_control(linear_velocity=linear_speed, angular_velocity=angular_speed) return aa_msg.Status(value=aa_msg.Status.DONE) def serve(arm_ip = "192.168.50.99", agv_ip="192.168.10.10", host = "localhost:18300"): _ONE_DAY_IN_SECONDS = 60 * 60 * 24 options = [('grpc.max_message_length', 100 * 1024 * 1024)] server = grpc.server(futures.ThreadPoolExecutor(max_workers=10), options = options) aa_server = XArmShuidiServer(arm_ip=arm_ip, agv_ip=agv_ip) aa_rpc.add_XArmShuidiServicer_to_server(aa_server, server) server.add_insecure_port(host) server.start() print("The XArm server is started!") try: while True: time.sleep(_ONE_DAY_IN_SECONDS) except KeyboardInterrupt: server.stop(0) if __name__ == "__main__": serve(arm_ip = "192.168.1.185", host = "192.168.50.99:18300")
[ "robot_con.xarm_shuidi.xarm_shuidi_pb2.Status", "robot_con.xarm_shuidi.xarm_shuidi_pb2_grpc.add_XArmShuidiServicer_to_server", "robot_con.xarm_shuidi.shuidi.shuidi_robot.ShuidiRobot", "robot_con.xarm_shuidi.xarm_shuidi_pb2.GripperStatus", "concurrent.futures.ThreadPoolExecutor", "time.sleep", "numpy.arr...
[((3446, 3504), 'robot_con.xarm_shuidi.xarm_shuidi_pb2_grpc.add_XArmShuidiServicer_to_server', 'aa_rpc.add_XArmShuidiServicer_to_server', (['aa_server', 'server'], {}), '(aa_server, server)\n', (3485, 3504), True, 'import robot_con.xarm_shuidi.xarm_shuidi_pb2_grpc as aa_rpc\n'), ((555, 579), 'drivers.xarm.wrapper.xarm_api.XArmAPI', 'arm.XArmAPI', ([], {'port': 'arm_ip'}), '(port=arm_ip)\n', (566, 579), True, 'import drivers.xarm.wrapper.xarm_api as arm\n'), ((1385, 1411), 'robot_con.xarm_shuidi.shuidi.shuidi_robot.ShuidiRobot', 'agv.ShuidiRobot', ([], {'ip': 'agv_ip'}), '(ip=agv_ip)\n', (1400, 1411), True, 'import robot_con.xarm_shuidi.shuidi.shuidi_robot as agv\n'), ((1858, 1903), 'numpy.frombuffer', 'np.frombuffer', (['request.data'], {'dtype': 'np.float64'}), '(request.data, dtype=np.float64)\n', (1871, 1903), True, 'import numpy as np\n'), ((2110, 2149), 'robot_con.xarm_shuidi.xarm_shuidi_pb2.Status', 'aa_msg.Status', ([], {'value': 'aa_msg.Status.DONE'}), '(value=aa_msg.Status.DONE)\n', (2123, 2149), True, 'import robot_con.xarm_shuidi.xarm_shuidi_pb2 as aa_msg\n'), ((2369, 2408), 'robot_con.xarm_shuidi.xarm_shuidi_pb2.Status', 'aa_msg.Status', ([], {'value': 'aa_msg.Status.DONE'}), '(value=aa_msg.Status.DONE)\n', (2382, 2408), True, 'import robot_con.xarm_shuidi.xarm_shuidi_pb2 as aa_msg\n'), ((2689, 2741), 'robot_con.xarm_shuidi.xarm_shuidi_pb2.GripperStatus', 'aa_msg.GripperStatus', ([], {'speed': 'speed', 'position': 'position'}), '(speed=speed, position=position)\n', (2709, 2741), True, 'import robot_con.xarm_shuidi.xarm_shuidi_pb2 as aa_msg\n'), ((3061, 3100), 'robot_con.xarm_shuidi.xarm_shuidi_pb2.Status', 'aa_msg.Status', ([], {'value': 'aa_msg.Status.DONE'}), '(value=aa_msg.Status.DONE)\n', (3074, 3100), True, 'import robot_con.xarm_shuidi.xarm_shuidi_pb2 as aa_msg\n'), ((3316, 3358), 'concurrent.futures.ThreadPoolExecutor', 'futures.ThreadPoolExecutor', ([], {'max_workers': '(10)'}), '(max_workers=10)\n', (3342, 3358), False, 'from concurrent import futures\n'), ((2079, 2095), 'time.sleep', 'time.sleep', (['(0.01)'], {}), '(0.01)\n', (2089, 2095), False, 'import time\n'), ((3641, 3672), 'time.sleep', 'time.sleep', (['_ONE_DAY_IN_SECONDS'], {}), '(_ONE_DAY_IN_SECONDS)\n', (3651, 3672), False, 'import time\n'), ((1687, 1707), 'numpy.array', 'np.array', (['jnt_values'], {}), '(jnt_values)\n', (1695, 1707), True, 'import numpy as np\n')]
# Copyright 2019 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 numpy as np import pytest import mindspore.common.dtype as mstype import mindspore.dataset as ds from mindspore import log as logger # Generate 1d int numpy array from 0 - 63 def generator_1d(): for i in range(64): yield (np.array([i]),) def test_case_0(): """ Test 1D Generator """ logger.info("Test 1D Generator : 0 - 63") # apply dataset operations data1 = ds.GeneratorDataset(generator_1d, ["data"]) i = 0 for item in data1.create_dict_iterator(): # each data is a dictionary golden = np.array([i]) assert np.array_equal(item["data"], golden) i = i + 1 # Generate md int numpy array from [[0, 1], [2, 3]] to [[63, 64], [65, 66]] def generator_md(): for i in range(64): yield (np.array([[i, i + 1], [i + 2, i + 3]]),) def test_case_1(): """ Test MD Generator """ logger.info("Test MD Generator : 0 - 63, with shape [2, 2]") # apply dataset operations data1 = ds.GeneratorDataset(generator_md, ["data"]) i = 0 for item in data1.create_dict_iterator(): # each data is a dictionary golden = np.array([[i, i + 1], [i + 2, i + 3]]) assert np.array_equal(item["data"], golden) i = i + 1 # Generate two columns, the first column is from Generator1D, the second column is from GeneratorMD def generator_mc(maxid=64): for i in range(maxid): yield (np.array([i]), np.array([[i, i + 1], [i + 2, i + 3]])) def test_case_2(): """ Test multi column generator """ logger.info("Test multi column generator") # apply dataset operations data1 = ds.GeneratorDataset(generator_mc, ["col0", "col1"]) i = 0 for item in data1.create_dict_iterator(): # each data is a dictionary golden = np.array([i]) assert np.array_equal(item["col0"], golden) golden = np.array([[i, i + 1], [i + 2, i + 3]]) assert np.array_equal(item["col1"], golden) i = i + 1 def test_case_3(): """ Test 1D Generator + repeat(4) """ logger.info("Test 1D Generator : 0 - 63 + Repeat(4)") # apply dataset operations data1 = ds.GeneratorDataset(generator_1d, ["data"]) data1 = data1.repeat(4) i = 0 for item in data1.create_dict_iterator(): # each data is a dictionary golden = np.array([i]) assert np.array_equal(item["data"], golden) i = i + 1 if i == 64: i = 0 def test_case_4(): """ Test fixed size 1D Generator + batch """ logger.info("Test 1D Generator : 0 - 63 + batch(4)") # apply dataset operations data1 = ds.GeneratorDataset(generator_1d, ["data"]) data1 = data1.batch(4) i = 0 for item in data1.create_dict_iterator(): # each data is a dictionary golden = np.array([[i], [i + 1], [i + 2], [i + 3]]) assert np.array_equal(item["data"], golden) i = i + 4 def generator_with_type(t): for i in range(64): yield (np.array([i], dtype=t),) def type_tester(t): logger.info("Test with Type {}".format(t.__name__)) # apply dataset operations data1 = ds.GeneratorDataset((lambda: generator_with_type(t)), ["data"]) data1 = data1.batch(4) i = 0 for item in data1.create_dict_iterator(): # each data is a dictionary golden = np.array([[i], [i + 1], [i + 2], [i + 3]], dtype=t) assert np.array_equal(item["data"], golden) i = i + 4 def test_case_5(): """ Test 1D Generator on different data type """ logger.info("Test 1D Generator on all data types") types = [np.int8, np.int16, np.int32, np.int64, np.uint8, np.uint16, np.uint32, np.uint64, np.float32, np.float64] for t in types: type_tester(t) def type_tester_with_type_check(t, c): logger.info("Test with Type {}".format(t.__name__)) # apply dataset operations data1 = ds.GeneratorDataset((lambda: generator_with_type(t)), ["data"], column_types=[c]) data1 = data1.batch(4) i = 0 for item in data1.create_dict_iterator(): # each data is a dictionary golden = np.array([[i], [i + 1], [i + 2], [i + 3]], dtype=t) assert np.array_equal(item["data"], golden) i = i + 4 def test_case_6(): """ Test 1D Generator on different data type with type check """ logger.info("Test 1D Generator on all data types with type check") np_types = [np.int8, np.int16, np.int32, np.int64, np.uint8, np.uint16, np.uint32, np.uint64, np.float32, np.float64] de_types = [mstype.int8, mstype.int16, mstype.int32, mstype.int64, mstype.uint8, mstype.uint16, mstype.uint32, mstype.uint64, mstype.float32, mstype.float64] for i in range(len(np_types)): type_tester_with_type_check(np_types[i], de_types[i]) def generator_with_type_2c(t): for i in range(64): yield (np.array([i], dtype=t), np.array([i], dtype=t)) def type_tester_with_type_check_2c(t, c): logger.info("Test with Type {}".format(t.__name__)) # apply dataset operations data1 = ds.GeneratorDataset((lambda: generator_with_type_2c(t)), ["data0", "data1"], column_types=c) data1 = data1.batch(4) i = 0 for item in data1.create_dict_iterator(): # each data is a dictionary golden = np.array([[i], [i + 1], [i + 2], [i + 3]], dtype=t) assert np.array_equal(item["data0"], golden) i = i + 4 def test_case_7(): """ Test 2 column Generator on different data type with type check """ logger.info("Test 2 column Generator on all data types with type check") np_types = [np.int8, np.int16, np.int32, np.int64, np.uint8, np.uint16, np.uint32, np.uint64, np.float32, np.float64] de_types = [mstype.int8, mstype.int16, mstype.int32, mstype.int64, mstype.uint8, mstype.uint16, mstype.uint32, mstype.uint64, mstype.float32, mstype.float64] for i in range(len(np_types)): type_tester_with_type_check_2c(np_types[i], [None, de_types[i]]) def test_case_8(): """ Test multi column generator with few mapops """ logger.info("Test multi column generator with mapops to check the order too") # apply dataset operations data1 = ds.GeneratorDataset(generator_mc(2048), ["col0", "col1"]) data1 = data1.map(input_columns="col0", output_columns="out0", operations=(lambda x: x * 3), num_parallel_workers=2) data1 = data1.map(input_columns="col1", output_columns=["out1", "out2"], operations=(lambda x: (x * 7, x)), num_parallel_workers=2, columns_order=["out0", "out1", "out2"]) data1 = data1.map(input_columns="out2", output_columns="out2", operations=(lambda x: x + 1), num_parallel_workers=2) i = 0 for item in data1.create_dict_iterator(): # each data is a dictionary golden = np.array([i * 3]) assert np.array_equal(item["out0"], golden) golden = np.array([[i * 7, (i + 1) * 7], [(i + 2) * 7, (i + 3) * 7]]) assert np.array_equal(item["out1"], golden) golden = np.array([[i + 1, i + 2], [i + 3, i + 4]]) assert np.array_equal(item["out2"], golden) i = i + 1 def test_case_9(): """ Test map column order when len(input_columns) == len(output_columns). """ logger.info("Test map column order when len(input_columns) == len(output_columns).") # apply dataset operations data1 = ds.GeneratorDataset(generator_mc(2048), ["image", "label"]) data2 = ds.GeneratorDataset(generator_mc(2048), ["label", "image"]) data1 = data1.map(input_columns="label", operations=(lambda x: x * 3), num_parallel_workers=4) data2 = data2.map(input_columns="label", operations=(lambda x: x * 3), num_parallel_workers=4) # Expected column order is not changed. # data1 = data[0] is "image" and data[1] is "label" # data2 = data[0] is "label" and data[1] is "image" i = 0 for data1, data2 in zip(data1, data2): # each data is a dictionary golden = np.array([i]) assert np.array_equal(data1[0], golden) golden = np.array([[i * 3, (i + 1) * 3], [(i + 2) * 3, (i + 3) * 3]]) assert np.array_equal(data1[1], golden) golden = np.array([i * 3]) assert np.array_equal(data2[0], golden) golden = np.array([[i, i + 1], [i + 2, i + 3]]) assert np.array_equal(data2[1], golden) i = i + 1 def test_case_10(): """ Test map column order when len(input_columns) != len(output_columns). """ logger.info("Test map column order when len(input_columns) != len(output_columns).") # apply dataset operations data1 = ds.GeneratorDataset(generator_mc(2048), ["col0", "col1"]) data1 = data1.map(input_columns="col1", output_columns=["out1", "out2"], operations=(lambda x: (x, x * 5)), columns_order=['col0', 'out1', 'out2'], num_parallel_workers=2) # Expected column order is |col0|out1|out2| i = 0 for item in data1.create_tuple_iterator(): golden = np.array([i]) assert np.array_equal(item[0], golden) golden = np.array([[i, i + 1], [i + 2, i + 3]]) assert np.array_equal(item[1], golden) golden = np.array([[i * 5, (i + 1) * 5], [(i + 2) * 5, (i + 3) * 5]]) assert np.array_equal(item[2], golden) i = i + 1 def test_case_11(): """ Test map column order when len(input_columns) != len(output_columns). """ logger.info("Test map column order when len(input_columns) != len(output_columns), " "and columns_order drops some columns.") # apply dataset operations data1 = ds.GeneratorDataset(generator_mc(2048), ["col0", "col1"]) data1 = data1.map(input_columns="col1", output_columns=["out1", "out2"], operations=(lambda x: (x, x * 5)), columns_order=['out1', 'out2'], num_parallel_workers=2) # Expected column order is |out1|out2| i = 0 for item in data1.create_tuple_iterator(): # len should be 2 because col0 is dropped (not included in columns_order) assert len(item) == 2 golden = np.array([[i, i + 1], [i + 2, i + 3]]) assert np.array_equal(item[0], golden) golden = np.array([[i * 5, (i + 1) * 5], [(i + 2) * 5, (i + 3) * 5]]) assert np.array_equal(item[1], golden) i = i + 1 def test_case_12(): """ Test map column order when input_columns and output_columns are None. """ logger.info("Test map column order when input_columns and output_columns are None.") # apply dataset operations data1 = ds.GeneratorDataset(generator_mc(2048), ["col0", "col1"]) data1 = data1.map(operations=(lambda x: (x * 5)), num_parallel_workers=2) # Expected column order is |col0|col1| i = 0 for item in data1.create_tuple_iterator(): assert len(item) == 2 golden = np.array([i * 5]) assert np.array_equal(item[0], golden) golden = np.array([[i, i + 1], [i + 2, i + 3]]) assert np.array_equal(item[1], golden) i = i + 1 data1 = ds.GeneratorDataset(generator_mc(2048), ["col0", "col1"]) data1 = data1.map(operations=(lambda x: (x * 5)), columns_order=["col1", "col0"], num_parallel_workers=2) # Expected column order is |col0|col1| i = 0 for item in data1.create_tuple_iterator(): assert len(item) == 2 golden = np.array([i * 5]) assert np.array_equal(item[1], golden) golden = np.array([[i, i + 1], [i + 2, i + 3]]) assert np.array_equal(item[0], golden) i = i + 1 def test_case_13(): """ Test map column order when input_columns is None. """ logger.info("Test map column order when input_columns is None.") # apply dataset operations data1 = ds.GeneratorDataset(generator_mc(2048), ["col0", "col1"]) data1 = data1.map(operations=(lambda x: (x * 5)), output_columns=["out0"], num_parallel_workers=2) # Expected column order is |out0|col1| i = 0 for item in data1.create_tuple_iterator(): assert len(item) == 2 golden = np.array([i * 5]) assert np.array_equal(item[0], golden) golden = np.array([[i, i + 1], [i + 2, i + 3]]) assert np.array_equal(item[1], golden) i = i + 1 for item in data1.create_dict_iterator(): # each data is a dictionary # len should be 2 because col0 is dropped (not included in columns_order) assert len(item) == 2 golden = np.array([i * 5]) assert np.array_equal(item["out0"], golden) golden = np.array([[i, i + 1], [i + 2, i + 3]]) assert np.array_equal(item["col1"], golden) i = i + 1 def test_case_error_1(): def generator_np(): for i in range(64): yield (np.array([{i}]),) with pytest.raises(RuntimeError) as info: data1 = ds.GeneratorDataset(generator_np, ["data"]) for _ in data1: pass assert "Invalid data type" in str(info.value) def test_case_error_2(): def generator_np(): for i in range(64): yield ({i},) with pytest.raises(RuntimeError) as info: data1 = ds.GeneratorDataset(generator_np, ["data"]) for _ in data1: pass assert "Generator should return a tuple of numpy arrays" in str(info.value) def test_case_error_3(): with pytest.raises(ValueError) as info: # apply dataset operations data1 = ds.GeneratorDataset(generator_mc(2048), ["label", "image"]) data1 = data1.map(input_columns=["label"], output_columns=["out1", "out2"], operations=(lambda x: (x, x * 5)), num_parallel_workers=2) for _ in data1: pass assert "When (len(input_columns) != len(output_columns)), columns_order must be specified." in str(info.value) def test_case_error_4(): with pytest.raises(RuntimeError) as info: # apply dataset operations data1 = ds.GeneratorDataset(generator_mc(2048), ["label", "image"]) data1 = data1.map(input_columns=["label"], operations=(lambda x: (x, x * 5)), num_parallel_workers=2) for _ in data1: pass assert "Unexpected error. Result of a tensorOp doesn't match output column names" in str(info.value) if __name__ == "__main__": test_case_0() test_case_1() test_case_2() test_case_3() test_case_4() test_case_5() test_case_6() test_case_7() test_case_8() test_case_9() test_case_10() test_case_11() test_case_12() test_case_13() test_case_error_1() test_case_error_2() test_case_error_3() test_case_error_4()
[ "mindspore.log.info", "mindspore.dataset.GeneratorDataset", "numpy.array", "numpy.array_equal", "pytest.raises" ]
[((992, 1033), 'mindspore.log.info', 'logger.info', (['"""Test 1D Generator : 0 - 63"""'], {}), "('Test 1D Generator : 0 - 63')\n", (1003, 1033), True, 'from mindspore import log as logger\n'), ((1078, 1121), 'mindspore.dataset.GeneratorDataset', 'ds.GeneratorDataset', (['generator_1d', "['data']"], {}), "(generator_1d, ['data'])\n", (1097, 1121), True, 'import mindspore.dataset as ds\n'), ((1550, 1610), 'mindspore.log.info', 'logger.info', (['"""Test MD Generator : 0 - 63, with shape [2, 2]"""'], {}), "('Test MD Generator : 0 - 63, with shape [2, 2]')\n", (1561, 1610), True, 'from mindspore import log as logger\n'), ((1655, 1698), 'mindspore.dataset.GeneratorDataset', 'ds.GeneratorDataset', (['generator_md', "['data']"], {}), "(generator_md, ['data'])\n", (1674, 1698), True, 'import mindspore.dataset as ds\n'), ((2211, 2253), 'mindspore.log.info', 'logger.info', (['"""Test multi column generator"""'], {}), "('Test multi column generator')\n", (2222, 2253), True, 'from mindspore import log as logger\n'), ((2298, 2349), 'mindspore.dataset.GeneratorDataset', 'ds.GeneratorDataset', (['generator_mc', "['col0', 'col1']"], {}), "(generator_mc, ['col0', 'col1'])\n", (2317, 2349), True, 'import mindspore.dataset as ds\n'), ((2720, 2773), 'mindspore.log.info', 'logger.info', (['"""Test 1D Generator : 0 - 63 + Repeat(4)"""'], {}), "('Test 1D Generator : 0 - 63 + Repeat(4)')\n", (2731, 2773), True, 'from mindspore import log as logger\n'), ((2818, 2861), 'mindspore.dataset.GeneratorDataset', 'ds.GeneratorDataset', (['generator_1d', "['data']"], {}), "(generator_1d, ['data'])\n", (2837, 2861), True, 'import mindspore.dataset as ds\n'), ((3198, 3250), 'mindspore.log.info', 'logger.info', (['"""Test 1D Generator : 0 - 63 + batch(4)"""'], {}), "('Test 1D Generator : 0 - 63 + batch(4)')\n", (3209, 3250), True, 'from mindspore import log as logger\n'), ((3295, 3338), 'mindspore.dataset.GeneratorDataset', 'ds.GeneratorDataset', (['generator_1d', "['data']"], {}), "(generator_1d, ['data'])\n", (3314, 3338), True, 'import mindspore.dataset as ds\n'), ((4202, 4252), 'mindspore.log.info', 'logger.info', (['"""Test 1D Generator on all data types"""'], {}), "('Test 1D Generator on all data types')\n", (4213, 4252), True, 'from mindspore import log as logger\n'), ((4995, 5061), 'mindspore.log.info', 'logger.info', (['"""Test 1D Generator on all data types with type check"""'], {}), "('Test 1D Generator on all data types with type check')\n", (5006, 5061), True, 'from mindspore import log as logger\n'), ((6196, 6268), 'mindspore.log.info', 'logger.info', (['"""Test 2 column Generator on all data types with type check"""'], {}), "('Test 2 column Generator on all data types with type check')\n", (6207, 6268), True, 'from mindspore import log as logger\n'), ((6784, 6861), 'mindspore.log.info', 'logger.info', (['"""Test multi column generator with mapops to check the order too"""'], {}), "('Test multi column generator with mapops to check the order too')\n", (6795, 6861), True, 'from mindspore import log as logger\n'), ((7996, 8085), 'mindspore.log.info', 'logger.info', (['"""Test map column order when len(input_columns) == len(output_columns)."""'], {}), "(\n 'Test map column order when len(input_columns) == len(output_columns).')\n", (8007, 8085), True, 'from mindspore import log as logger\n'), ((9265, 9354), 'mindspore.log.info', 'logger.info', (['"""Test map column order when len(input_columns) != len(output_columns)."""'], {}), "(\n 'Test map column order when len(input_columns) != len(output_columns).')\n", (9276, 9354), True, 'from mindspore import log as logger\n'), ((10196, 10328), 'mindspore.log.info', 'logger.info', (['"""Test map column order when len(input_columns) != len(output_columns), and columns_order drops some columns."""'], {}), "(\n 'Test map column order when len(input_columns) != len(output_columns), and columns_order drops some columns.'\n )\n", (10207, 10328), True, 'from mindspore import log as logger\n'), ((11205, 11294), 'mindspore.log.info', 'logger.info', (['"""Test map column order when input_columns and output_columns are None."""'], {}), "(\n 'Test map column order when input_columns and output_columns are None.')\n", (11216, 11294), True, 'from mindspore import log as logger\n'), ((12415, 12479), 'mindspore.log.info', 'logger.info', (['"""Test map column order when input_columns is None."""'], {}), "('Test map column order when input_columns is None.')\n", (12426, 12479), True, 'from mindspore import log as logger\n'), ((1225, 1238), 'numpy.array', 'np.array', (['[i]'], {}), '([i])\n', (1233, 1238), True, 'import numpy as np\n'), ((1254, 1290), 'numpy.array_equal', 'np.array_equal', (["item['data']", 'golden'], {}), "(item['data'], golden)\n", (1268, 1290), True, 'import numpy as np\n'), ((1802, 1840), 'numpy.array', 'np.array', (['[[i, i + 1], [i + 2, i + 3]]'], {}), '([[i, i + 1], [i + 2, i + 3]])\n', (1810, 1840), True, 'import numpy as np\n'), ((1856, 1892), 'numpy.array_equal', 'np.array_equal', (["item['data']", 'golden'], {}), "(item['data'], golden)\n", (1870, 1892), True, 'import numpy as np\n'), ((2453, 2466), 'numpy.array', 'np.array', (['[i]'], {}), '([i])\n', (2461, 2466), True, 'import numpy as np\n'), ((2482, 2518), 'numpy.array_equal', 'np.array_equal', (["item['col0']", 'golden'], {}), "(item['col0'], golden)\n", (2496, 2518), True, 'import numpy as np\n'), ((2536, 2574), 'numpy.array', 'np.array', (['[[i, i + 1], [i + 2, i + 3]]'], {}), '([[i, i + 1], [i + 2, i + 3]])\n', (2544, 2574), True, 'import numpy as np\n'), ((2590, 2626), 'numpy.array_equal', 'np.array_equal', (["item['col1']", 'golden'], {}), "(item['col1'], golden)\n", (2604, 2626), True, 'import numpy as np\n'), ((2994, 3007), 'numpy.array', 'np.array', (['[i]'], {}), '([i])\n', (3002, 3007), True, 'import numpy as np\n'), ((3023, 3059), 'numpy.array_equal', 'np.array_equal', (["item['data']", 'golden'], {}), "(item['data'], golden)\n", (3037, 3059), True, 'import numpy as np\n'), ((3470, 3512), 'numpy.array', 'np.array', (['[[i], [i + 1], [i + 2], [i + 3]]'], {}), '([[i], [i + 1], [i + 2], [i + 3]])\n', (3478, 3512), True, 'import numpy as np\n'), ((3528, 3564), 'numpy.array_equal', 'np.array_equal', (["item['data']", 'golden'], {}), "(item['data'], golden)\n", (3542, 3564), True, 'import numpy as np\n'), ((3994, 4045), 'numpy.array', 'np.array', (['[[i], [i + 1], [i + 2], [i + 3]]'], {'dtype': 't'}), '([[i], [i + 1], [i + 2], [i + 3]], dtype=t)\n', (4002, 4045), True, 'import numpy as np\n'), ((4061, 4097), 'numpy.array_equal', 'np.array_equal', (["item['data']", 'golden'], {}), "(item['data'], golden)\n", (4075, 4097), True, 'import numpy as np\n'), ((4771, 4822), 'numpy.array', 'np.array', (['[[i], [i + 1], [i + 2], [i + 3]]'], {'dtype': 't'}), '([[i], [i + 1], [i + 2], [i + 3]], dtype=t)\n', (4779, 4822), True, 'import numpy as np\n'), ((4838, 4874), 'numpy.array_equal', 'np.array_equal', (["item['data']", 'golden'], {}), "(item['data'], golden)\n", (4852, 4874), True, 'import numpy as np\n'), ((5965, 6016), 'numpy.array', 'np.array', (['[[i], [i + 1], [i + 2], [i + 3]]'], {'dtype': 't'}), '([[i], [i + 1], [i + 2], [i + 3]], dtype=t)\n', (5973, 6016), True, 'import numpy as np\n'), ((6032, 6069), 'numpy.array_equal', 'np.array_equal', (["item['data0']", 'golden'], {}), "(item['data0'], golden)\n", (6046, 6069), True, 'import numpy as np\n'), ((7551, 7568), 'numpy.array', 'np.array', (['[i * 3]'], {}), '([i * 3])\n', (7559, 7568), True, 'import numpy as np\n'), ((7584, 7620), 'numpy.array_equal', 'np.array_equal', (["item['out0']", 'golden'], {}), "(item['out0'], golden)\n", (7598, 7620), True, 'import numpy as np\n'), ((7638, 7698), 'numpy.array', 'np.array', (['[[i * 7, (i + 1) * 7], [(i + 2) * 7, (i + 3) * 7]]'], {}), '([[i * 7, (i + 1) * 7], [(i + 2) * 7, (i + 3) * 7]])\n', (7646, 7698), True, 'import numpy as np\n'), ((7714, 7750), 'numpy.array_equal', 'np.array_equal', (["item['out1']", 'golden'], {}), "(item['out1'], golden)\n", (7728, 7750), True, 'import numpy as np\n'), ((7768, 7810), 'numpy.array', 'np.array', (['[[i + 1, i + 2], [i + 3, i + 4]]'], {}), '([[i + 1, i + 2], [i + 3, i + 4]])\n', (7776, 7810), True, 'import numpy as np\n'), ((7826, 7862), 'numpy.array_equal', 'np.array_equal', (["item['out2']", 'golden'], {}), "(item['out2'], golden)\n", (7840, 7862), True, 'import numpy as np\n'), ((8755, 8768), 'numpy.array', 'np.array', (['[i]'], {}), '([i])\n', (8763, 8768), True, 'import numpy as np\n'), ((8784, 8816), 'numpy.array_equal', 'np.array_equal', (['data1[0]', 'golden'], {}), '(data1[0], golden)\n', (8798, 8816), True, 'import numpy as np\n'), ((8834, 8894), 'numpy.array', 'np.array', (['[[i * 3, (i + 1) * 3], [(i + 2) * 3, (i + 3) * 3]]'], {}), '([[i * 3, (i + 1) * 3], [(i + 2) * 3, (i + 3) * 3]])\n', (8842, 8894), True, 'import numpy as np\n'), ((8910, 8942), 'numpy.array_equal', 'np.array_equal', (['data1[1]', 'golden'], {}), '(data1[1], golden)\n', (8924, 8942), True, 'import numpy as np\n'), ((8961, 8978), 'numpy.array', 'np.array', (['[i * 3]'], {}), '([i * 3])\n', (8969, 8978), True, 'import numpy as np\n'), ((8994, 9026), 'numpy.array_equal', 'np.array_equal', (['data2[0]', 'golden'], {}), '(data2[0], golden)\n', (9008, 9026), True, 'import numpy as np\n'), ((9044, 9082), 'numpy.array', 'np.array', (['[[i, i + 1], [i + 2, i + 3]]'], {}), '([[i, i + 1], [i + 2, i + 3]])\n', (9052, 9082), True, 'import numpy as np\n'), ((9098, 9130), 'numpy.array_equal', 'np.array_equal', (['data2[1]', 'golden'], {}), '(data2[1], golden)\n', (9112, 9130), True, 'import numpy as np\n'), ((9773, 9786), 'numpy.array', 'np.array', (['[i]'], {}), '([i])\n', (9781, 9786), True, 'import numpy as np\n'), ((9802, 9833), 'numpy.array_equal', 'np.array_equal', (['item[0]', 'golden'], {}), '(item[0], golden)\n', (9816, 9833), True, 'import numpy as np\n'), ((9851, 9889), 'numpy.array', 'np.array', (['[[i, i + 1], [i + 2, i + 3]]'], {}), '([[i, i + 1], [i + 2, i + 3]])\n', (9859, 9889), True, 'import numpy as np\n'), ((9905, 9936), 'numpy.array_equal', 'np.array_equal', (['item[1]', 'golden'], {}), '(item[1], golden)\n', (9919, 9936), True, 'import numpy as np\n'), ((9954, 10014), 'numpy.array', 'np.array', (['[[i * 5, (i + 1) * 5], [(i + 2) * 5, (i + 3) * 5]]'], {}), '([[i * 5, (i + 1) * 5], [(i + 2) * 5, (i + 3) * 5]])\n', (9962, 10014), True, 'import numpy as np\n'), ((10030, 10061), 'numpy.array_equal', 'np.array_equal', (['item[2]', 'golden'], {}), '(item[2], golden)\n', (10044, 10061), True, 'import numpy as np\n'), ((10860, 10898), 'numpy.array', 'np.array', (['[[i, i + 1], [i + 2, i + 3]]'], {}), '([[i, i + 1], [i + 2, i + 3]])\n', (10868, 10898), True, 'import numpy as np\n'), ((10914, 10945), 'numpy.array_equal', 'np.array_equal', (['item[0]', 'golden'], {}), '(item[0], golden)\n', (10928, 10945), True, 'import numpy as np\n'), ((10963, 11023), 'numpy.array', 'np.array', (['[[i * 5, (i + 1) * 5], [(i + 2) * 5, (i + 3) * 5]]'], {}), '([[i * 5, (i + 1) * 5], [(i + 2) * 5, (i + 3) * 5]])\n', (10971, 11023), True, 'import numpy as np\n'), ((11039, 11070), 'numpy.array_equal', 'np.array_equal', (['item[1]', 'golden'], {}), '(item[1], golden)\n', (11053, 11070), True, 'import numpy as np\n'), ((11618, 11635), 'numpy.array', 'np.array', (['[i * 5]'], {}), '([i * 5])\n', (11626, 11635), True, 'import numpy as np\n'), ((11651, 11682), 'numpy.array_equal', 'np.array_equal', (['item[0]', 'golden'], {}), '(item[0], golden)\n', (11665, 11682), True, 'import numpy as np\n'), ((11700, 11738), 'numpy.array', 'np.array', (['[[i, i + 1], [i + 2, i + 3]]'], {}), '([[i, i + 1], [i + 2, i + 3]])\n', (11708, 11738), True, 'import numpy as np\n'), ((11754, 11785), 'numpy.array_equal', 'np.array_equal', (['item[1]', 'golden'], {}), '(item[1], golden)\n', (11768, 11785), True, 'import numpy as np\n'), ((12133, 12150), 'numpy.array', 'np.array', (['[i * 5]'], {}), '([i * 5])\n', (12141, 12150), True, 'import numpy as np\n'), ((12166, 12197), 'numpy.array_equal', 'np.array_equal', (['item[1]', 'golden'], {}), '(item[1], golden)\n', (12180, 12197), True, 'import numpy as np\n'), ((12215, 12253), 'numpy.array', 'np.array', (['[[i, i + 1], [i + 2, i + 3]]'], {}), '([[i, i + 1], [i + 2, i + 3]])\n', (12223, 12253), True, 'import numpy as np\n'), ((12269, 12300), 'numpy.array_equal', 'np.array_equal', (['item[0]', 'golden'], {}), '(item[0], golden)\n', (12283, 12300), True, 'import numpy as np\n'), ((12833, 12850), 'numpy.array', 'np.array', (['[i * 5]'], {}), '([i * 5])\n', (12841, 12850), True, 'import numpy as np\n'), ((12866, 12897), 'numpy.array_equal', 'np.array_equal', (['item[0]', 'golden'], {}), '(item[0], golden)\n', (12880, 12897), True, 'import numpy as np\n'), ((12915, 12953), 'numpy.array', 'np.array', (['[[i, i + 1], [i + 2, i + 3]]'], {}), '([[i, i + 1], [i + 2, i + 3]])\n', (12923, 12953), True, 'import numpy as np\n'), ((12969, 13000), 'numpy.array_equal', 'np.array_equal', (['item[1]', 'golden'], {}), '(item[1], golden)\n', (12983, 13000), True, 'import numpy as np\n'), ((13224, 13241), 'numpy.array', 'np.array', (['[i * 5]'], {}), '([i * 5])\n', (13232, 13241), True, 'import numpy as np\n'), ((13257, 13293), 'numpy.array_equal', 'np.array_equal', (["item['out0']", 'golden'], {}), "(item['out0'], golden)\n", (13271, 13293), True, 'import numpy as np\n'), ((13311, 13349), 'numpy.array', 'np.array', (['[[i, i + 1], [i + 2, i + 3]]'], {}), '([[i, i + 1], [i + 2, i + 3]])\n', (13319, 13349), True, 'import numpy as np\n'), ((13365, 13401), 'numpy.array_equal', 'np.array_equal', (["item['col1']", 'golden'], {}), "(item['col1'], golden)\n", (13379, 13401), True, 'import numpy as np\n'), ((13546, 13573), 'pytest.raises', 'pytest.raises', (['RuntimeError'], {}), '(RuntimeError)\n', (13559, 13573), False, 'import pytest\n'), ((13599, 13642), 'mindspore.dataset.GeneratorDataset', 'ds.GeneratorDataset', (['generator_np', "['data']"], {}), "(generator_np, ['data'])\n", (13618, 13642), True, 'import mindspore.dataset as ds\n'), ((13848, 13875), 'pytest.raises', 'pytest.raises', (['RuntimeError'], {}), '(RuntimeError)\n', (13861, 13875), False, 'import pytest\n'), ((13901, 13944), 'mindspore.dataset.GeneratorDataset', 'ds.GeneratorDataset', (['generator_np', "['data']"], {}), "(generator_np, ['data'])\n", (13920, 13944), True, 'import mindspore.dataset as ds\n'), ((14102, 14127), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (14115, 14127), False, 'import pytest\n'), ((14610, 14637), 'pytest.raises', 'pytest.raises', (['RuntimeError'], {}), '(RuntimeError)\n', (14623, 14637), False, 'import pytest\n'), ((913, 926), 'numpy.array', 'np.array', (['[i]'], {}), '([i])\n', (921, 926), True, 'import numpy as np\n'), ((1446, 1484), 'numpy.array', 'np.array', (['[[i, i + 1], [i + 2, i + 3]]'], {}), '([[i, i + 1], [i + 2, i + 3]])\n', (1454, 1484), True, 'import numpy as np\n'), ((2083, 2096), 'numpy.array', 'np.array', (['[i]'], {}), '([i])\n', (2091, 2096), True, 'import numpy as np\n'), ((2098, 2136), 'numpy.array', 'np.array', (['[[i, i + 1], [i + 2, i + 3]]'], {}), '([[i, i + 1], [i + 2, i + 3]])\n', (2106, 2136), True, 'import numpy as np\n'), ((3652, 3674), 'numpy.array', 'np.array', (['[i]'], {'dtype': 't'}), '([i], dtype=t)\n', (3660, 3674), True, 'import numpy as np\n'), ((5549, 5571), 'numpy.array', 'np.array', (['[i]'], {'dtype': 't'}), '([i], dtype=t)\n', (5557, 5571), True, 'import numpy as np\n'), ((5573, 5595), 'numpy.array', 'np.array', (['[i]'], {'dtype': 't'}), '([i], dtype=t)\n', (5581, 5595), True, 'import numpy as np\n'), ((13518, 13533), 'numpy.array', 'np.array', (['[{i}]'], {}), '([{i}])\n', (13526, 13533), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- """ __author__ = '{<NAME>}' __email__ = '{<EMAIL>}' """ from module.model import DaNN from module.datafunc import make_dataloaders import torch from tqdm import tqdm import numpy as np import os from convex_adversarial import robust_loss, robust_loss_parallel torch.manual_seed(7) torch.cuda.manual_seed_all(100) torch.backends.cudnn.deterministic = True class Trainer(): def __init__(self, args): self.model = DaNN() self.optimizer = torch.optim.Adam(self.model.parameters()) self.criterion = torch.nn.CrossEntropyLoss() self.criterion_domain = torch.nn.CrossEntropyLoss() dataloaders = make_dataloaders(args.source, args.target, args.batch_size) self.sourceloader = dataloaders[0] self.sourcetestloader = dataloaders[1] self.targetloader = dataloaders[2] self.targettestloader = dataloaders[3] self.device = 'cuda' if torch.cuda.is_available() else 'cpu' for to_cuda_obj in [self.model, self.criterion, self.criterion_domain]: to_cuda_obj.to(self.device) self.cert = args.cert self.args = args stot = (self.args.source[:1], self.args.target[:1]) self.modelpath = os.path.join('ckpt', self.args.taskname, 'model_%s_%s.pth'%stot) self.certpath = os.path.join('ckpt', self.args.taskname, 'cert_%s_%s.pth'%stot) def train(self): print('%s --> %s'%(self.args.source, self.args.target)) print('half') best_acc = 0 # bbar = range(self.args.epochs) if self.args.resume is None: bbar = tqdm(range(self.args.epochs), ncols=100) for epoch in bbar: self.model.train() self.train_one_epoch(epoch) self.model.eval() sacc, acc = self.test() if acc > best_acc: best_acc = acc if self.cert: torch.save(self.model.state_dict(), self.certpath) else: torch.save(self.model.state_dict(), self.modelpath) # print(sacc, acc, best_acc) bbar.set_postfix(acc=acc, sacc=sacc, best_acc=best_acc) modelpath = self.certpath if self.cert else self.modelpath self.model.load_state_dict(torch.load(modelpath)) result = self.attack() print('source fgsm pgd') print(result[0][0]) print(result[0][1]) print('target fgsm pgd') print(result[1][0]) print(result[1][1]) def train_one_epoch(self, epoch): num_iteration = min(len(self.sourceloader), len(self.targetloader)) pbar = tqdm(range(num_iteration), ncols=100, desc=str(epoch)) for i in pbar: p = float(i + epoch * num_iteration) / self.args.epochs / num_iteration alpha = 2. / (1. + np.exp(-10 * p)) - 1 simg, slabel = next(iter(self.sourceloader)) simg, slabel = simg.to(self.device), slabel.to(self.device) timg, __ = next(iter(self.targetloader)) timg = timg.to(self.device) ## simply split the model into two??? #train with source data batch_size = len(slabel) domain_label = torch.zeros(batch_size).long().to(self.device) self.model._set_alpha = alpha if self.cert: features = self.model.main_features(simg) features = features.view(-1, 50*4*4) loss_label, err = robust_loss(self.model.classifier, 0.05, features, slabel) else: output = self.model(simg) loss_label = self.criterion(output, slabel) domain_output = self.model(simg, mode='domain') loss_domain = self.criterion_domain(domain_output, domain_label) # train with target data batch_size = len(timg) domain_label = torch.ones(batch_size).long().to(self.device) domain_output = self.model(timg, mode='domain') tloss_domain = self.criterion_domain(domain_output, domain_label) loss = loss_label + loss_domain + tloss_domain self.optimizer.zero_grad() loss.backward() self.optimizer.step() pbar.set_postfix(loss=loss_label.item(), d_s_loss=loss_domain.item(), d_t_loss=tloss_domain.item()) def test(self): #source and test alpha = 0 result = [] for loader in [self.sourcetestloader, self.targettestloader]: correct = 0 length = 0 for images, labels in loader: images, labels = images.to(self.device), labels.to(self.device) batch_size = len(images) output = self.model(images) pred = output.argmax(dim=1) correct += pred.eq(labels).sum().item() length += batch_size accuracy = correct *100//length result.append(accuracy) return result def attack(self): RES = [] for loader in [self.sourcetestloader, self.targettestloader]: results = [] for desc, attack_f in zip(['FGSM', 'PGD'], [self.FGSM, self.PGD]): result = [] for eps in tqdm([i*0.01 for i in range(10)], ncols=100, desc=desc): accuracy = 0 length = 0 for images, target in loader: images, target = images.cuda(), target.cuda() pert_image = attack_f(eps, images, target) output = self.model(pert_image) pred = output.argmax(dim=1) accuracy += pred.eq(target).data.sum() length += len(pred) result.append(accuracy.item()*100//length) results.append(result) print(result) RES.append(results) return RES def FGSM(self, eps, images, target): ## this is X = images.clone() X.requires_grad = True output = self.model(X) loss = self.criterion(output, target) loss.backward() grad_sign = X.grad.data.sign() return (X + eps*grad_sign).clamp(0, 1) def PGD(self, eps, images, target): X_orig = images.clone() X_var = images.clone() for __ in range(40): X = X_var.clone() X.requires_grad = True output = self.model(X) loss = self.criterion(output, target) loss.backward() grad_sign = X.grad.data.sign() X_var = X_var + 0.05*grad_sign # X_var.clamp(X_orig-eps, X_orig+eps) X_var = torch.where(X_var < X_orig-eps, X_orig-eps, X_var) X_var = torch.where(X_var > X_orig+eps, X_orig+eps, X_var) X_var.clamp(0, 1) return X_var
[ "torch.cuda.manual_seed_all", "torch.manual_seed", "module.model.DaNN", "torch.ones", "torch.nn.CrossEntropyLoss", "module.datafunc.make_dataloaders", "torch.load", "os.path.join", "convex_adversarial.robust_loss", "numpy.exp", "torch.cuda.is_available", "torch.zeros", "torch.where" ]
[((291, 311), 'torch.manual_seed', 'torch.manual_seed', (['(7)'], {}), '(7)\n', (308, 311), False, 'import torch\n'), ((312, 343), 'torch.cuda.manual_seed_all', 'torch.cuda.manual_seed_all', (['(100)'], {}), '(100)\n', (338, 343), False, 'import torch\n'), ((456, 462), 'module.model.DaNN', 'DaNN', ([], {}), '()\n', (460, 462), False, 'from module.model import DaNN\n'), ((555, 582), 'torch.nn.CrossEntropyLoss', 'torch.nn.CrossEntropyLoss', ([], {}), '()\n', (580, 582), False, 'import torch\n'), ((615, 642), 'torch.nn.CrossEntropyLoss', 'torch.nn.CrossEntropyLoss', ([], {}), '()\n', (640, 642), False, 'import torch\n'), ((665, 724), 'module.datafunc.make_dataloaders', 'make_dataloaders', (['args.source', 'args.target', 'args.batch_size'], {}), '(args.source, args.target, args.batch_size)\n', (681, 724), False, 'from module.datafunc import make_dataloaders\n'), ((1245, 1311), 'os.path.join', 'os.path.join', (['"""ckpt"""', 'self.args.taskname', "('model_%s_%s.pth' % stot)"], {}), "('ckpt', self.args.taskname, 'model_%s_%s.pth' % stot)\n", (1257, 1311), False, 'import os\n'), ((1334, 1399), 'os.path.join', 'os.path.join', (['"""ckpt"""', 'self.args.taskname', "('cert_%s_%s.pth' % stot)"], {}), "('ckpt', self.args.taskname, 'cert_%s_%s.pth' % stot)\n", (1346, 1399), False, 'import os\n'), ((938, 963), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (961, 963), False, 'import torch\n'), ((2350, 2371), 'torch.load', 'torch.load', (['modelpath'], {}), '(modelpath)\n', (2360, 2371), False, 'import torch\n'), ((6845, 6899), 'torch.where', 'torch.where', (['(X_var < X_orig - eps)', '(X_orig - eps)', 'X_var'], {}), '(X_var < X_orig - eps, X_orig - eps, X_var)\n', (6856, 6899), False, 'import torch\n'), ((6916, 6970), 'torch.where', 'torch.where', (['(X_var > X_orig + eps)', '(X_orig + eps)', 'X_var'], {}), '(X_var > X_orig + eps, X_orig + eps, X_var)\n', (6927, 6970), False, 'import torch\n'), ((3578, 3636), 'convex_adversarial.robust_loss', 'robust_loss', (['self.model.classifier', '(0.05)', 'features', 'slabel'], {}), '(self.model.classifier, 0.05, features, slabel)\n', (3589, 3636), False, 'from convex_adversarial import robust_loss, robust_loss_parallel\n'), ((2906, 2921), 'numpy.exp', 'np.exp', (['(-10 * p)'], {}), '(-10 * p)\n', (2912, 2921), True, 'import numpy as np\n'), ((3318, 3341), 'torch.zeros', 'torch.zeros', (['batch_size'], {}), '(batch_size)\n', (3329, 3341), False, 'import torch\n'), ((3996, 4018), 'torch.ones', 'torch.ones', (['batch_size'], {}), '(batch_size)\n', (4006, 4018), False, 'import torch\n')]
""" Python re-implementation of "Visual Object Tracking using Adaptive Correlation Filters" @inproceedings{Bolme2010Visual, title={Visual object tracking using adaptive correlation filters}, author={Bolme, <NAME>. and Beveridge, <NAME> and Draper, <NAME>. and Lui, <NAME>}, booktitle={Computer Vision & Pattern Recognition}, year={2010}, } """ import numpy as np import cv2 from pysot.pycftrackers.lib.utils import gaussian2d_labels,cos_window from pysot.pycftrackers.cftracker.base import BaseCF class SFMOSSE(BaseCF): def __init__(self,interp_factor=0.125,sigma=2.): super(SFMOSSE).__init__() self.interp_factor=interp_factor self.sigma=sigma def init(self,first_frame,bbox): if len(first_frame.shape)!=2: assert first_frame.shape[2]==3 first_frame=cv2.cvtColor(first_frame,cv2.COLOR_BGR2GRAY) first_frame=first_frame.astype(np.float32)/255 x,y,w,h=tuple(bbox) self._center=(x+w/2,y+h/2) self.w,self.h=w,h w,h=int(round(w)),int(round(h)) self.cos_window=cos_window((w,h)) self._fi=cv2.getRectSubPix(first_frame,(w,h),self._center) self._G=np.fft.fft2(gaussian2d_labels((w,h),self.sigma)) self.crop_size=(w,h) self._Ai=np.zeros_like(self._G) self._Bi=np.zeros_like(self._G) for _ in range(8): fi=self._rand_warp(self._fi) Fi=np.fft.fft2(self._preprocessing(fi,self.cos_window)) self._Ai+=self._G*np.conj(Fi) self._Bi+=Fi*np.conj(Fi) def update(self,current_frame,vis=False): if len(current_frame.shape)!=2: assert current_frame.shape[2]==3 current_frame=cv2.cvtColor(current_frame,cv2.COLOR_BGR2GRAY) current_frame=current_frame.astype(np.float32)/255 Hi=self._Ai/self._Bi fi=cv2.getRectSubPix(current_frame,(int(round(self.w)),int(round(self.h))),self._center) fi=self._preprocessing(fi,self.cos_window) Gi=Hi*np.fft.fft2(fi) gi=np.real(np.fft.ifft2(Gi)) if vis is True: self.score=gi curr=np.unravel_index(np.argmax(gi, axis=None),gi.shape) dy,dx=curr[0]-(self.h/2),curr[1]-(self.w/2) x_c,y_c=self._center x_c+=dx y_c+=dy self._center=(x_c,y_c) fi=cv2.getRectSubPix(current_frame,(int(round(self.w)),int(round(self.h))),self._center) fi=self._preprocessing(fi,self.cos_window) Fi=np.fft.fft2(fi) self._Ai=self.interp_factor*(self._G*np.conj(Fi))+(1-self.interp_factor)*self._Ai self._Bi=self.interp_factor*(Fi*np.conj(Fi))+(1-self.interp_factor)*self._Bi return [self._center[0]-self.w/2,self._center[1]-self.h/2,self.w,self.h],-1.0 def _preprocessing(self,img,cos_window,eps=1e-5): img=np.log(img+1) img=(img-np.mean(img))/(np.std(img)+eps) return cos_window*img def _rand_warp(self,img): h, w = img.shape[:2] C = .1 ang = np.random.uniform(-C, C) c, s = np.cos(ang), np.sin(ang) W = np.array([[c + np.random.uniform(-C, C), -s + np.random.uniform(-C, C), 0], [s + np.random.uniform(-C, C), c + np.random.uniform(-C, C), 0]]) center_warp = np.array([[w / 2], [h / 2]]) tmp = np.sum(W[:, :2], axis=1).reshape((2, 1)) W[:, 2:] = center_warp - center_warp * tmp warped = cv2.warpAffine(img, W, (w, h), cv2.BORDER_REFLECT) return warped
[ "numpy.mean", "cv2.warpAffine", "numpy.fft.ifft2", "numpy.conj", "numpy.std", "numpy.log", "cv2.getRectSubPix", "pysot.pycftrackers.lib.utils.gaussian2d_labels", "numpy.fft.fft2", "pysot.pycftrackers.lib.utils.cos_window", "numpy.array", "numpy.argmax", "numpy.sum", "numpy.cos", "cv2.cvt...
[((1111, 1129), 'pysot.pycftrackers.lib.utils.cos_window', 'cos_window', (['(w, h)'], {}), '((w, h))\n', (1121, 1129), False, 'from pysot.pycftrackers.lib.utils import gaussian2d_labels, cos_window\n'), ((1147, 1199), 'cv2.getRectSubPix', 'cv2.getRectSubPix', (['first_frame', '(w, h)', 'self._center'], {}), '(first_frame, (w, h), self._center)\n', (1164, 1199), False, 'import cv2\n'), ((1311, 1333), 'numpy.zeros_like', 'np.zeros_like', (['self._G'], {}), '(self._G)\n', (1324, 1333), True, 'import numpy as np\n'), ((1352, 1374), 'numpy.zeros_like', 'np.zeros_like', (['self._G'], {}), '(self._G)\n', (1365, 1374), True, 'import numpy as np\n'), ((2549, 2564), 'numpy.fft.fft2', 'np.fft.fft2', (['fi'], {}), '(fi)\n', (2560, 2564), True, 'import numpy as np\n'), ((2901, 2916), 'numpy.log', 'np.log', (['(img + 1)'], {}), '(img + 1)\n', (2907, 2916), True, 'import numpy as np\n'), ((3090, 3114), 'numpy.random.uniform', 'np.random.uniform', (['(-C)', 'C'], {}), '(-C, C)\n', (3107, 3114), True, 'import numpy as np\n'), ((3357, 3385), 'numpy.array', 'np.array', (['[[w / 2], [h / 2]]'], {}), '([[w / 2], [h / 2]])\n', (3365, 3385), True, 'import numpy as np\n'), ((3512, 3562), 'cv2.warpAffine', 'cv2.warpAffine', (['img', 'W', '(w, h)', 'cv2.BORDER_REFLECT'], {}), '(img, W, (w, h), cv2.BORDER_REFLECT)\n', (3526, 3562), False, 'import cv2\n'), ((850, 895), 'cv2.cvtColor', 'cv2.cvtColor', (['first_frame', 'cv2.COLOR_BGR2GRAY'], {}), '(first_frame, cv2.COLOR_BGR2GRAY)\n', (862, 895), False, 'import cv2\n'), ((1226, 1263), 'pysot.pycftrackers.lib.utils.gaussian2d_labels', 'gaussian2d_labels', (['(w, h)', 'self.sigma'], {}), '((w, h), self.sigma)\n', (1243, 1263), False, 'from pysot.pycftrackers.lib.utils import gaussian2d_labels, cos_window\n'), ((1762, 1809), 'cv2.cvtColor', 'cv2.cvtColor', (['current_frame', 'cv2.COLOR_BGR2GRAY'], {}), '(current_frame, cv2.COLOR_BGR2GRAY)\n', (1774, 1809), False, 'import cv2\n'), ((2066, 2081), 'numpy.fft.fft2', 'np.fft.fft2', (['fi'], {}), '(fi)\n', (2077, 2081), True, 'import numpy as np\n'), ((2102, 2118), 'numpy.fft.ifft2', 'np.fft.ifft2', (['Gi'], {}), '(Gi)\n', (2114, 2118), True, 'import numpy as np\n'), ((2203, 2227), 'numpy.argmax', 'np.argmax', (['gi'], {'axis': 'None'}), '(gi, axis=None)\n', (2212, 2227), True, 'import numpy as np\n'), ((3131, 3142), 'numpy.cos', 'np.cos', (['ang'], {}), '(ang)\n', (3137, 3142), True, 'import numpy as np\n'), ((3144, 3155), 'numpy.sin', 'np.sin', (['ang'], {}), '(ang)\n', (3150, 3155), True, 'import numpy as np\n'), ((1545, 1556), 'numpy.conj', 'np.conj', (['Fi'], {}), '(Fi)\n', (1552, 1556), True, 'import numpy as np\n'), ((1583, 1594), 'numpy.conj', 'np.conj', (['Fi'], {}), '(Fi)\n', (1590, 1594), True, 'import numpy as np\n'), ((2933, 2945), 'numpy.mean', 'np.mean', (['img'], {}), '(img)\n', (2940, 2945), True, 'import numpy as np\n'), ((2948, 2959), 'numpy.std', 'np.std', (['img'], {}), '(img)\n', (2954, 2959), True, 'import numpy as np\n'), ((3401, 3425), 'numpy.sum', 'np.sum', (['W[:, :2]'], {'axis': '(1)'}), '(W[:, :2], axis=1)\n', (3407, 3425), True, 'import numpy as np\n'), ((2611, 2622), 'numpy.conj', 'np.conj', (['Fi'], {}), '(Fi)\n', (2618, 2622), True, 'import numpy as np\n'), ((2697, 2708), 'numpy.conj', 'np.conj', (['Fi'], {}), '(Fi)\n', (2704, 2708), True, 'import numpy as np\n'), ((3184, 3208), 'numpy.random.uniform', 'np.random.uniform', (['(-C)', 'C'], {}), '(-C, C)\n', (3201, 3208), True, 'import numpy as np\n'), ((3215, 3239), 'numpy.random.uniform', 'np.random.uniform', (['(-C)', 'C'], {}), '(-C, C)\n', (3232, 3239), True, 'import numpy as np\n'), ((3273, 3297), 'numpy.random.uniform', 'np.random.uniform', (['(-C)', 'C'], {}), '(-C, C)\n', (3290, 3297), True, 'import numpy as np\n'), ((3303, 3327), 'numpy.random.uniform', 'np.random.uniform', (['(-C)', 'C'], {}), '(-C, C)\n', (3320, 3327), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- """ Created on Mon Jun 29 12:59:04 2020 @author: hartwgj """ # cth 1mm interferometer code import scipy.constants from scipy import fft,ifft from cthmds import CTHData import numpy as np # input the chord # return the density and time axis # other possible keywords: numfwin, phase,SAVEintfrm_1mm,eflag, verbose #def CTHintfrm_1mm(shotnum,chord,debug): def CTHintfrm_1mm(sawsig,intsig,chord,debug): # use when testing # --------------------- Define constants --------------------- pi=scipy.constants.pi c = scipy.constants.c # [m/s] speed of light, !const.c me = scipy.constants.m_e # [kg] electron mass, !const.me ep0 = scipy.constants.epsilon_0 # [C^2/Nm^2] permitivity of free space, !const.eps0 e = scipy.constants.e # [C] fundamental charge, !const.e # these are system dependent freq=[244.0E9, 244.0E9, 244.0E9, 280.0E9] # chord frequencies w0 = 2.0*pi * np.array(freq) # [Hz] nominal frequency of output lp = 2.0 * 0.25 #[m] closer to the flux surface width in ECRH plasmas dt=1.0/50E6 # 50MHz digitization rate sweepfreq=450000 # 450kHz sweep frequency hanning_width=70000 # window width of hanning window # define data board and channel pairs sawtooth_ch=[(5,1),(5,1),(5,1),(6,2)] data_ch = [(5,2),(5,3),(5,4),(6,3)] # ------------------------- Get data ------------------------- # if debug: print(' Getting interferometer data...') # intsig=CTHData('intgis') # sawsig=CTHData('intsaw') # sawsig.get_data(server='neil',shotnum=shotnum,board_channel=sawtooth_ch[chord-1]) # intsig.get_data(server='neil',shotnum=shotnum,board_channel=data_ch[chord-1]) if debug: print('') print(' data retrieved, starting phase calculation... ') length=len(intsig.data) print('data length ',length) signal_strength=max(intsig.data[0:5000]) - min(intsig.data[0:5000]) print('chord ',chord,' signal strength ' ,signal_strength) # ; Truncate for efficiency 2^23=8388608 which should speed up calculations # that would go from 1.55s to 1.68 which is not long enough # # ;intfrm1 = temporary(intfrm1[0:numt-1]) # ;intfrm2 = temporary(intfrm2[0:numt-1]) # ;intfrm3 = temporary(intfrm3[0:numt-1]) # ;sawtooth = temporary(sawtooth[0:numt-1]) # ;t_intfrm = temporary(t_intfrm[0:numt-1]) # ; experimental code, not in use. # if 0 then begin # tdisrupt = 1.66 # ntdisrupt = max(where(t_intfrm le tdisrupt)) # print,ntdisrupt # nt = 5500000 # numt = long(2)^22 # intfrm = intfrm[0:nt-1,*] # sawtooth = temporary(sawtooth[0:nt-1]) # t_intfrm = temporary(t_intfrm[0:nt-1]) # ;if ntdisrupt le numt then stop # ; intfrm = intfrm[ntdisrupt-numt+1:ntdisrupt,*] # ; sawtooth = temporary(sawtooth[ntdisrupt-numt+1:ntdisrupt]) # ; t_intfrm = temporary(t_intfrm[ntdisrupt-numt+1:ntdisrupt]) # endif # Compute fft of signals numt=len(sawsig.data) sawfft = np.fft.fft(sawsig.data) # faxis = [findgen(numt/2+1),-reverse(findgen(round(numt/2.0)-1)+1)] /(numt*dt) faxis=np.linspace(0.0,1.0/(2.0*dt),length//2) nfmax=int(sweepfreq/5.0) numfwin=int(hanning_width/5.0) abssawfft=np.abs(sawfft) maxsfft=np.max(abssawfft[1:length//2]) nfmax = np.where(abssawfft==maxsfft)[0][0] if debug: print('nfmax = ',nfmax,' at f= ',faxis[nfmax]) # nfmax=90000 # ; numfwin sets the frequency window width used # ; I'm not sure what the optimal value is, and it probably depends on the # ; interferometer chirp frequency (i.e. sawtooth frequency) numfwin=hanning_width//5 # ; Apply frequency window. Set usehanning = 1 to use a hanning window, # ; otherwise a top hat window will be used # usehanning=1 # if keyword_set(usehanning) then begin # hwin = hanning(2L*numfwin+1) # for ii=0,numchord-1 do begin # sigfft[nfmax-numfwin:nfmax+numfwin,ii] = hwin*sigfft[nfmax-numfwin:nfmax+numfwin,ii] # endfor # sigfft[0:nfmax-numfwin-1,*] = 0.0 # sigfft[nfmax+numfwin+1:*,*] = 0.0 # endif else begin # ; Zero out all but frequencies within numfwin of nfmax # sigfft[0:nfmax-numfwin,*] = 0.0 # sigfft[nfmax+numfwin:*,*] = 0.0 # endelse # ; Do inverse transform for all chords # sig = fft(sigfft,/inverse,dimension=1) # ; Create cleaner reference signal from fft of sawtooth # reffft = sawfft # if keyword_set(usehanning) then begin # hwin = hanning(2L*numfwin+1) # reffft[nfmax-numfwin:nfmax+numfwin] = hwin*reffft[nfmax-numfwin:nfmax+numfwin] # reffft[0:nfmax-numfwin-1,*] = 0.0 # reffft[nfmax+numfwin+1:*,*] = 0.0 # endif else begin # reffft[0:nfmax-numfwin] = 0.0 # reffft[nfmax+numfwin:*] = 0.0 # endelse # for ii=0,numchord-1 do begin # if ii eq 0 then ref = fft(reffft,/inverse) else $ # ref = [[ref],[ref]] # endfor # ; Calculate phase difference between signals and reference # phs = atan(sig*conj(ref),/phase) # ; --------------------- Correct phase ------------------------- # phs = cthfringecounter(phs) # ; Subtract offset and thin the data # noffset = where( (t_intfrm ge 1.56) and (t_intfrm le 1.58) ) # for ii=0,numchord-1 do begin # if ii eq 0 then phase = thinn(phs[*,ii] - mean(phs[noffset,ii]),9) else $ # phase = [[phase],[thinn(phs[*,ii] - mean(phs[noffset,ii]),9)]] # endfor # t_intfrm = thinn(t_intfrm,9) # if n_elements(t_intfrm) ne n_elements(phase[*,0]) then $ # message,'processed data and time axis not of same length!' # ; --------- Calculate density -------- # ;est_density = -(2.0 * !const.me * !const.eps0 * !const.c * w0 * phase) / (!const.e^2.0 * lp) # est_density = -(2.0 * me * ep0 * c * w0 * phase) / (e^2.0 * lp) # t0 = t_intfrm[0] # tf = max(t_intfrm) # ;dt = (tf - t0)/(numt - 1) # taxis = t_intfrm # dt = (tf - t0)/(n_elements(taxis)-1) # if max(SAVEintfrm_1mm) eq 1 then begin # print,' Saving data...' # for ii=0,numchord-1 do begin # if SAVEintfrm_1mm[ii] eq 1 then $ # mdsput,'processed:intfrm_1mm:phs_'+strtrim(chord[ii],2), $ # 'BUILD_SIGNAL( $,*,build_range($,$,$))',phase[*,ii],t0,tf,dt # endfor # mdsput,'processed:intfrm_1mm:t0','$',t0 # mdsput,'processed:intfrm_1mm:dt','$',dt # endif # if keyword_set(stp) then begin # print, 'cthintfrm_1mm.pro stopped for debugging at ', $ # systime(0) # stop # endif # ; end of cthintfrm_1mm
[ "numpy.abs", "numpy.where", "numpy.fft.fft", "numpy.max", "numpy.array", "numpy.linspace" ]
[((3043, 3066), 'numpy.fft.fft', 'np.fft.fft', (['sawsig.data'], {}), '(sawsig.data)\n', (3053, 3066), True, 'import numpy as np\n'), ((3162, 3209), 'numpy.linspace', 'np.linspace', (['(0.0)', '(1.0 / (2.0 * dt))', '(length // 2)'], {}), '(0.0, 1.0 / (2.0 * dt), length // 2)\n', (3173, 3209), True, 'import numpy as np\n'), ((3290, 3304), 'numpy.abs', 'np.abs', (['sawfft'], {}), '(sawfft)\n', (3296, 3304), True, 'import numpy as np\n'), ((3317, 3349), 'numpy.max', 'np.max', (['abssawfft[1:length // 2]'], {}), '(abssawfft[1:length // 2])\n', (3323, 3349), True, 'import numpy as np\n'), ((964, 978), 'numpy.array', 'np.array', (['freq'], {}), '(freq)\n', (972, 978), True, 'import numpy as np\n'), ((3365, 3395), 'numpy.where', 'np.where', (['(abssawfft == maxsfft)'], {}), '(abssawfft == maxsfft)\n', (3373, 3395), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- # Contains the "Note" class used in our program, that represent a note # and keeps various attributes assigned to it. It also contains static # methods to get a random note, or convert a whole list. import random import re from time import sleep import numpy as np import simpleaudio as sa # List of notes and figures NOTE_NAMES = ['DO', 'RE', 'MI', 'FA', 'SOL', 'LA', 'SI'] NOTE_FIGURES = ['r', 'b', 'n', 'c'] class Note: def __init__(self, raw_input): self.raw_input = raw_input self.parsed_data = self.parse() # Name of the note (one of NOTE_NAMES) self.name = self.parsed_data[0] # Figure of the note (one of NOTE_FIGURES) self.figure = self.parsed_data[1] # Wether the note has its duration extended with a point self.has_point = bool(self.parsed_data[2]) # The frequency of the note self.frequency = self.get_frequency() # The duration of the note in seconds self.duration = self.get_duration() # Wether the note is a pause self.is_pause = self.name == "Z" @staticmethod def create_random_note(): """ Create a random note. """ raw_note = random.choice(NOTE_NAMES) raw_note += random.choice(NOTE_FIGURES) return Note(raw_note) @staticmethod def to_raw(parsed_notes): """ Transform a list of Note instances into a list of raw notes, as in the partition files """ output = [] for note in parsed_notes: new_note = f'{note.name}{note.figure}' new_note += 'p' if note.has_point else '' output.append(new_note) return output def parse(self): """ Parse notes in the partitions, and returns a tuple containing the name, the duration and whether it contains a point. """ groups = re.findall("([A-Z]*)(r|b|n|c)(p)?", self.raw_input) return groups[0] def get_frequency(self): """ Assign a frequency for each available notes """ if self.name == "DO": return 264 elif self.name == "RE": return 297 elif self.name == "MI": return 330 elif self.name == "FA": return 352 elif self.name == "SOL": return 396 elif self.name == "LA": return 440 elif self.name == "SI": return 495 return 0 def get_duration(self): """ Get the duration depending on the figure, and if there is a point """ duration = 0 if self.figure == 'r': # "Ronde" duration = 1000 elif self.figure == 'b': # "Blanche" duration = 500 elif self.figure == 'n': # "Noire" duration = 250 elif self.figure == 'c': # "Croche" duration = 125 # If there is a point, set it to half the duration, otherwise 0 point_duration = duration / 2 if self.has_point else 0 # Add the duration and the extended duration (point), and normalize it return (duration + point_duration) / 1000 def play(self): """ If there is a frequency, play the note, otherwise it is a pause """ if self.is_pause: # Sleep for the duration of the note when the note is "Z" sleep(self.duration) else: # Get timesteps for each sample, "duration" is note duration in seconds sample_rate = 44100 t = np.linspace(0, self.duration, int(self.duration * sample_rate), False) # Generate sine wave tone tone = np.sin(self.frequency * t * 6 * np.pi) # Normalize to 24−bit range tone *= 8388607 / np.max(np.abs(tone)) # Convert to 32−bit data tone = tone.astype(np.int32) # Convert from 32−bit to 24−bit by building a new byte buffer, # skipping every fourth bit # Note: this also works for 2−channel audio i = 0 byte_array = [] for b in tone.tobytes(): if i % 4 != 3: byte_array.append(b) i += 1 audio = bytearray(byte_array) # Start playback play_obj = sa.play_buffer(audio, 1, 3, sample_rate) # Wait for playback to finish before exiting play_obj.wait_done()
[ "numpy.abs", "random.choice", "simpleaudio.play_buffer", "time.sleep", "numpy.sin", "re.findall" ]
[((1218, 1243), 'random.choice', 'random.choice', (['NOTE_NAMES'], {}), '(NOTE_NAMES)\n', (1231, 1243), False, 'import random\n'), ((1264, 1291), 'random.choice', 'random.choice', (['NOTE_FIGURES'], {}), '(NOTE_FIGURES)\n', (1277, 1291), False, 'import random\n'), ((1888, 1939), 're.findall', 're.findall', (['"""([A-Z]*)(r|b|n|c)(p)?"""', 'self.raw_input'], {}), "('([A-Z]*)(r|b|n|c)(p)?', self.raw_input)\n", (1898, 1939), False, 'import re\n'), ((3349, 3369), 'time.sleep', 'sleep', (['self.duration'], {}), '(self.duration)\n', (3354, 3369), False, 'from time import sleep\n'), ((3644, 3682), 'numpy.sin', 'np.sin', (['(self.frequency * t * 6 * np.pi)'], {}), '(self.frequency * t * 6 * np.pi)\n', (3650, 3682), True, 'import numpy as np\n'), ((4297, 4337), 'simpleaudio.play_buffer', 'sa.play_buffer', (['audio', '(1)', '(3)', 'sample_rate'], {}), '(audio, 1, 3, sample_rate)\n', (4311, 4337), True, 'import simpleaudio as sa\n'), ((3760, 3772), 'numpy.abs', 'np.abs', (['tone'], {}), '(tone)\n', (3766, 3772), True, 'import numpy as np\n')]
""" cclib (http://cclib.sf.net) is (c) 2006, the cclib development team and licensed under the LGPL (http://www.gnu.org/copyleft/lgpl.html). """ __revision__ = "$Revision: 668 $" import re import numpy import logfileparser import utils class ORCA(logfileparser.Logfile): """An ORCA log file.""" def __init__(self, *args, **kwargs): # Call the __init__ method of the superclass super(ORCA, self).__init__(logname="ORCA", *args, **kwargs) def __str__(self): """Return a string representation of the object.""" return "ORCA log file %s" % (self.filename) def __repr__(self): """Return a representation of the object.""" return 'ORCA("%s")' % (self.filename) def normalisesym(self, label): """Use standard symmetry labels instead of Gaussian labels. To normalise: (1) If label is one of [SG, PI, PHI, DLTA], replace by [sigma, pi, phi, delta] (2) replace any G or U by their lowercase equivalent >>> sym = Gaussian("dummyfile").normalisesym >>> labels = ['A1', 'AG', 'A1G', "SG", "PI", "PHI", "DLTA", 'DLTU', 'SGG'] >>> map(sym, labels) ['A1', 'Ag', 'A1g', 'sigma', 'pi', 'phi', 'delta', 'delta.u', 'sigma.g'] """ def before_parsing(self): # Used to index self.scftargets[]. SCFRMS, SCFMAX, SCFENERGY = range(3) # Flag that indicates whether it has reached the end of a geoopt. self.optfinished = False # Flag for identifying Coupled Cluster runs. self.coupledcluster = False def extract(self, inputfile, line): """Extract information from the file object inputfile.""" if line[0:15] == "Number of atoms": natom = int(line.split()[-1]) if hasattr(self, "natom"): # I wonder whether this code will ever be executed. assert self.natom == natom else: self.natom = natom if line[1:13] == "Total Charge": #get charge and multiplicity info self.charge = int(line.split()[-1]) line = inputfile.next() self.mult = int(line.split()[-1]) if line[25:50] == "Geometry Optimization Run": #get geotarget info line = inputfile.next() while line[0:23] != "Convergence Tolerances:": line = inputfile.next() self.geotargets = numpy.zeros((5,), "d") for i in range(5): line = inputfile.next() self.geotargets[i] = float(line.split()[-2]) # Read in scfvalues. if line [:14] == "SCF ITERATIONS": if not hasattr(self, "scfvalues"): self.scfvalues = [] dashes = inputfile.next() line = inputfile.next().split() assert line[1] == "Energy" assert line[2] == "Delta-E" assert line[3] == "Max-DP" self.scfvalues.append([]) while line != []: if line[0].isdigit(): energy = float(line[1]) deltaE = float(line[2]) maxDP = float(line[3]) rmsDP = float(line[4]) self.scfvalues[-1].append([deltaE, maxDP, rmsDP]) line = inputfile.next().split() # Read in values for last SCF iteration and scftargets. if line[:15] == "SCF CONVERGENCE": if not hasattr(self, "scfvalues"): self.scfvalues = [] if not hasattr(self, "scftargets"): self.scftargets = [] dashes = inputfile.next() blank = inputfile.next() line = inputfile.next() assert line[:29].strip() == "Last Energy change" deltaE_value = float(line[33:46]) deltaE_target = float(line[60:72]) line = inputfile.next() assert line[:29].strip() == "Last MAX-Density change" maxDP_value = float(line[33:46]) maxDP_target = float(line[60:72]) line = inputfile.next() assert line[:29].strip() == "Last RMS-Density change" rmsDP_value = float(line[33:46]) rmsDP_target = float(line[60:72]) line = inputfile.next() assert line[:29].strip() == "Last DIIS Error" self.scfvalues[-1].append([deltaE_value,maxDP_value,rmsDP_value]) self.scftargets.append([deltaE_target,maxDP_target,rmsDP_target]) # Read in SCF energy, at least in SP calculation. if line [:16] == "TOTAL SCF ENERGY": if not hasattr(self, "scfenergies"): self.scfenergies = [] dashes = inputfile.next() blank = inputfile.next() line = inputfile.next() if line[:12] == "Total Energy": energy = float(line[50:67]) self.scfenergies.append(energy) if line[33:53] == "Geometry convergence": #get geometry convergence criteria if not hasattr(self, "geovalues"): self.geovalues = [ ] newlist = [] headers = inputfile.next() dashes = inputfile.next() #check if energy change is present (steps > 1) line = inputfile.next() if line.find("Energy change") > 0: newlist.append(float(line.split()[2])) line = inputfile.next() else: newlist.append(0.0) #get rest of info for i in range(4): newlist.append(float(line.split()[2])) line = inputfile.next() self.geovalues.append(newlist) if line[0:21] == "CARTESIAN COORDINATES" and not hasattr(self, "atomcoords"): #if not an optimization, determine structure used dashes = inputfile.next() atomnos = [] atomcoords = [] line = inputfile.next() while len(line) > 1: broken = line.split() atomnos.append(self.table.number[broken[0]]) atomcoords.append(map(float, broken[1:4])) line = inputfile.next() self.atomcoords = [atomcoords] if not hasattr(self, "atomnos"): self.atomnos = atomnos self.natom = len(atomnos) if line[26:53] == "GEOMETRY OPTIMIZATION CYCLE": #parse geometry coords stars = inputfile.next() dashes = inputfile.next() text = inputfile.next() dashes = inputfile.next() if not hasattr(self,"atomcoords"): self.atomcoords = [] atomnos = [] atomcoords = [] for i in range(self.natom): line = inputfile.next() broken = line.split() atomnos.append(self.table.number[broken[0]]) atomcoords.append(map(float, broken[1:4])) self.atomcoords.append(atomcoords) if not hasattr(self, "atomnos"): self.atomnos = numpy.array(atomnos,'i') if line[21:68] == "FINAL ENERGY EVALUATION AT THE STATIONARY POINT": text = inputfile.next() broken = text.split() assert int(broken[2]) == len(self.atomcoords) stars = inputfile.next() dashes = inputfile.next() text = inputfile.next() dashes = inputfile.next() atomcoords = [] for i in range(self.natom): line = inputfile.next() broken = line.split() atomcoords.append(map(float, broken[1:4])) self.atomcoords.append(atomcoords) if line[0:16] == "ORBITAL ENERGIES": #parser orbial energy information dashes = inputfile.next() text = inputfile.next() text = inputfile.next() self.moenergies = [[]] self.homos = [[0]] line = inputfile.next() while len(line) > 20: #restricted calcs are terminated by ------ info = line.split() self.moenergies[0].append(float(info[3])) if float(info[1]) > 0.00: #might be 1 or 2, depending on restricted-ness self.homos[0] = int(info[0]) line = inputfile.next() line = inputfile.next() #handle beta orbitals if line[17:35] == "SPIN DOWN ORBITALS": text = inputfile.next() self.moenergies.append([]) self.homos.append(0) line = inputfile.next() while len(line) > 20: #actually terminated by ------ info = line.split() self.moenergies[1].append(float(info[3])) if float(info[1]) == 1.00: self.homos[1] = int(info[0]) line = inputfile.next() if line[1:32] == "# of contracted basis functions": self.nbasis = int(line.split()[-1]) if line[0:14] == "OVERLAP MATRIX": #parser the overlap matrix dashes = inputfile.next() self.aooverlaps = numpy.zeros( (self.nbasis, self.nbasis), "d") for i in range(0, self.nbasis, 6): header = inputfile.next() size = len(header.split()) for j in range(self.nbasis): line = inputfile.next() broken = line.split() self.aooverlaps[j, i:i+size] = map(float, broken[1:size+1]) # Molecular orbital coefficients. # This is also where atombasis is parsed. if line[0:18] == "MOLECULAR ORBITALS": dashses = inputfile.next() mocoeffs = [ numpy.zeros((self.nbasis, self.nbasis), "d") ] self.aonames = [] self.atombasis = [] for n in range(self.natom): self.atombasis.append([]) for spin in range(len(self.moenergies)): if spin == 1: blank = inputfile.next() mocoeffs.append(numpy.zeros((self.nbasis, self.nbasis), "d")) for i in range(0, self.nbasis, 6): numbers = inputfile.next() energies = inputfile.next() occs = inputfile.next() dashes = inputfile.next() broken = dashes.split() size = len(broken) for j in range(self.nbasis): line = inputfile.next() broken = line.split() #only need this on the first time through if spin == 0 and i == 0: atomname = line[3:5].split()[0] num = int(line[0:3]) orbital = broken[1].upper() self.aonames.append("%s%i_%s"%(atomname, num+1, orbital)) self.atombasis[num].append(j) temp = [] vals = line[16:-1] #-1 to remove the last blank space for k in range(0, len(vals), 10): temp.append(float(vals[k:k+10])) mocoeffs[spin][i:i+size, j] = temp self.mocoeffs = mocoeffs if line[0:18] == "TD-DFT/TDA EXCITED": sym = "Triplet" # Could be singlets or triplets if line.find("SINGLETS") >= 0: sym = "Singlet" self.etsecs = [] self.etenergies = [] self.etsyms = [] lookup = {'a':0, 'b':1} line = inputfile.next() while line.find("STATE") < 0: line = inputfile.next() # Contains STATE or is blank while line.find("STATE") >= 0: broken = line.split() self.etenergies.append(float(broken[-2])) self.etsyms.append(sym) line = inputfile.next() sec = [] # Contains SEC or is blank while line.strip(): start = line[0:8].strip() start = (int(start[:-1]), lookup[start[-1]]) end = line[10:17].strip() end = (int(end[:-1]), lookup[end[-1]]) contrib = float(line[35:47].strip()) sec.append([start, end, contrib]) line = inputfile.next() self.etsecs.append(sec) line = inputfile.next() if line[25:44] == "ABSORPTION SPECTRUM": minus = inputfile.next() header = inputfile.next() header = inputfile.next() minus = inputfile.next() self.etoscs = [] for x in self.etsyms: osc = inputfile.next().split()[3] if osc == "spin": # "spin forbidden" osc = 0 else: osc = float(osc) self.etoscs.append(osc) if line[0:23] == "VIBRATIONAL FREQUENCIES": #parse the vibrational frequencies dashes = inputfile.next() blank = inputfile.next() self.vibfreqs = numpy.zeros((3 * self.natom,),"d") for i in range(3 * self.natom): line = inputfile.next() self.vibfreqs[i] = float(line.split()[1]) if line[0:11] == "IR SPECTRUM": #parse ir intensities dashes = inputfile.next() blank = inputfile.next() header = inputfile.next() dashes = inputfile.next() self.vibirs = numpy.zeros((3 * self.natom,),"d") line = inputfile.next() while len(line) > 2: num = int(line[0:4]) self.vibirs[num] = float(line.split()[2]) line = inputfile.next() if line[0:14] == "<NAME>": #parser raman intensities dashes = inputfile.next() blank = inputfile.next() header = inputfile.next() dashes = inputfile.next() self.vibramans = numpy.zeros((3 * self.natom,),"d") line = inputfile.next() while len(line) > 2: num = int(line[0:4]) self.vibramans[num] = float(line.split()[2]) line = inputfile.next() if __name__ == "__main__": import doctest, orcaparser doctest.testmod(orcaparser, verbose=False)
[ "numpy.array", "numpy.zeros", "doctest.testmod" ]
[((15197, 15239), 'doctest.testmod', 'doctest.testmod', (['orcaparser'], {'verbose': '(False)'}), '(orcaparser, verbose=False)\n', (15212, 15239), False, 'import doctest, orcaparser\n'), ((2516, 2538), 'numpy.zeros', 'numpy.zeros', (['(5,)', '"""d"""'], {}), "((5,), 'd')\n", (2527, 2538), False, 'import numpy\n'), ((9619, 9663), 'numpy.zeros', 'numpy.zeros', (['(self.nbasis, self.nbasis)', '"""d"""'], {}), "((self.nbasis, self.nbasis), 'd')\n", (9630, 9663), False, 'import numpy\n'), ((13947, 13982), 'numpy.zeros', 'numpy.zeros', (['(3 * self.natom,)', '"""d"""'], {}), "((3 * self.natom,), 'd')\n", (13958, 13982), False, 'import numpy\n'), ((14379, 14414), 'numpy.zeros', 'numpy.zeros', (['(3 * self.natom,)', '"""d"""'], {}), "((3 * self.natom,), 'd')\n", (14390, 14414), False, 'import numpy\n'), ((14877, 14912), 'numpy.zeros', 'numpy.zeros', (['(3 * self.natom,)', '"""d"""'], {}), "((3 * self.natom,), 'd')\n", (14888, 14912), False, 'import numpy\n'), ((7432, 7457), 'numpy.array', 'numpy.array', (['atomnos', '"""i"""'], {}), "(atomnos, 'i')\n", (7443, 7457), False, 'import numpy\n'), ((10231, 10275), 'numpy.zeros', 'numpy.zeros', (['(self.nbasis, self.nbasis)', '"""d"""'], {}), "((self.nbasis, self.nbasis), 'd')\n", (10242, 10275), False, 'import numpy\n'), ((10598, 10642), 'numpy.zeros', 'numpy.zeros', (['(self.nbasis, self.nbasis)', '"""d"""'], {}), "((self.nbasis, self.nbasis), 'd')\n", (10609, 10642), False, 'import numpy\n')]
#!/usr/bin/env python3 import argparse import math import os import time import numpy as np import torch import torch.nn.functional as F import torch.optim as optim from Steed.optimizationfns import MultiClassLM from Steed.drllib import models, utils, common TEST_ITERS = 1000 RunName = "Test5" def test_net(net, env, count=10, device="cpu"): rewards = 0.0 steps = 0 for _ in range(count): obs = env.reset() while True: obs_v = utils.float32_preprocessor([obs]).to(device) mu_v = net(obs_v)[0] action = mu_v.squeeze(dim=0).data.cpu().numpy() action = np.clip(action, -1, 1) obs, reward, done, _ = env.step(action) rewards += reward steps += 1 if done: break return rewards / count, steps / count def calc_logprob(mu_v, var_v, actions_v): p1 = - ((mu_v - actions_v) ** 2) / (2*var_v.clamp(min=1e-3)) p2 = - torch.log(torch.sqrt(2 * math.pi * var_v)) return p1 + p2 def run_ac2(actiontype,env,test_env,device,OPT_FUNC,GAMMA,BATCH,LR,ENTROPY_BETA,STEP, REWARD_STEPS): save_path = os.path.join("saves", "ddpg-" + RunName) os.makedirs(save_path, exist_ok=True) if actiontype == "Discrete": if env.action_space.n == 2: net = models.ModelA2C(env.observation_space.shape[0], env.action_space.n - 1).to(device) else: net = models.ModelA2C(env.observation_space.shape[0], env.action_space.n).to(device) else: net = models.ModelA2C(env.observation_space.shape[0], env.action_space.shape[0]).to(device) print(net) agent = models.AgentA2C(net, device=device) exp_source = utils.ExperienceSourceFirstLast(env, agent, GAMMA, steps_count=REWARD_STEPS) batch = [] best_reward = None for step_idx, exp in enumerate(exp_source): rewards_steps = exp_source.pop_rewards_steps() if rewards_steps: rewards, steps = zip(*rewards_steps) if step_idx % TEST_ITERS == 0: ts = time.time() rewards, steps = test_net(net, test_env, device=device) print("Test done is %.2f sec, reward %.3f, steps %d" % ( time.time() - ts, rewards, steps)) if best_reward is None or best_reward < rewards: if best_reward is not None: print("Best reward updated: %.3f -> %.3f" % (best_reward, rewards)) name = "best_%+.3f_%d.dat" % (rewards, step_idx) fname = os.path.join(save_path, name) torch.save(net.state_dict(), fname) best_reward = rewards batch.append(exp) if len(batch) < BATCH: continue states_v, actions_v, vals_ref_v = \ common.unpack_batch_a2c(batch, net, last_val_gamma=GAMMA ** REWARD_STEPS, device=device) batch.clear() if OPT_FUNC is None or OPT_FUNC == "adam": optimizer = optim.Adam(net.parameters(), lr=LR) optimizer.zero_grad() mu_v, var_v, value_v = net(states_v) loss_value_v = F.mse_loss(value_v.squeeze(-1), vals_ref_v) adv_v = vals_ref_v.unsqueeze(dim=-1) - value_v.detach() log_prob_v = adv_v * calc_logprob(mu_v, var_v, actions_v) loss_policy_v = -log_prob_v.mean() entropy_loss_v = ENTROPY_BETA * (-(torch.log(2 * math.pi * var_v) + 1) / 2).mean() loss_v = loss_policy_v + entropy_loss_v + loss_value_v loss_v.backward() optimizer.step() else: # Our optimization functions LM = MultiClassLM.LM() return best_reward if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--actiontype", required=True, help='Discrete or Continuous') parser.add_argument("--env", required=True, help="Env") parser.add_argument("--testenv", required=True, help="Test Env") parser.add_argument("--cuda", required=True, default=False, help="Cuda") parser.add_argument("--gamma",required=False,default=0.99) parser.add_argument("--lr", required=False, default=5e-5) parser.add_argument("--entropy",required=False,default=1e-4) args = parser.parse_args() action_type = args["actiontype"] env = args["env"] test_env = args["testenv"] cuda = args["cuda"] GAMMA = args["gamma"] LEARNING_RATE = args["lr"] ENTROPY_BETA = args["entropy"] device = torch.device("cuda" if cuda else "cpu") run_ac2(action_type,env,test_env,device,GAMMA,LEARNING_RATE,ENTROPY_BETA)
[ "Steed.drllib.common.unpack_batch_a2c", "numpy.clip", "torch.log", "Steed.drllib.utils.float32_preprocessor", "argparse.ArgumentParser", "Steed.drllib.models.AgentA2C", "os.makedirs", "Steed.drllib.models.ModelA2C", "os.path.join", "torch.sqrt", "Steed.optimizationfns.MultiClassLM.LM", "time.t...
[((1146, 1186), 'os.path.join', 'os.path.join', (['"""saves"""', "('ddpg-' + RunName)"], {}), "('saves', 'ddpg-' + RunName)\n", (1158, 1186), False, 'import os\n'), ((1191, 1228), 'os.makedirs', 'os.makedirs', (['save_path'], {'exist_ok': '(True)'}), '(save_path, exist_ok=True)\n', (1202, 1228), False, 'import os\n'), ((1647, 1682), 'Steed.drllib.models.AgentA2C', 'models.AgentA2C', (['net'], {'device': 'device'}), '(net, device=device)\n', (1662, 1682), False, 'from Steed.drllib import models, utils, common\n'), ((1700, 1776), 'Steed.drllib.utils.ExperienceSourceFirstLast', 'utils.ExperienceSourceFirstLast', (['env', 'agent', 'GAMMA'], {'steps_count': 'REWARD_STEPS'}), '(env, agent, GAMMA, steps_count=REWARD_STEPS)\n', (1731, 1776), False, 'from Steed.drllib import models, utils, common\n'), ((3740, 3765), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (3763, 3765), False, 'import argparse\n'), ((4499, 4538), 'torch.device', 'torch.device', (["('cuda' if cuda else 'cpu')"], {}), "('cuda' if cuda else 'cpu')\n", (4511, 4538), False, 'import torch\n'), ((2800, 2892), 'Steed.drllib.common.unpack_batch_a2c', 'common.unpack_batch_a2c', (['batch', 'net'], {'last_val_gamma': '(GAMMA ** REWARD_STEPS)', 'device': 'device'}), '(batch, net, last_val_gamma=GAMMA ** REWARD_STEPS,\n device=device)\n', (2823, 2892), False, 'from Steed.drllib import models, utils, common\n'), ((631, 653), 'numpy.clip', 'np.clip', (['action', '(-1)', '(1)'], {}), '(action, -1, 1)\n', (638, 653), True, 'import numpy as np\n'), ((974, 1005), 'torch.sqrt', 'torch.sqrt', (['(2 * math.pi * var_v)'], {}), '(2 * math.pi * var_v)\n', (984, 1005), False, 'import torch\n'), ((2050, 2061), 'time.time', 'time.time', ([], {}), '()\n', (2059, 2061), False, 'import time\n'), ((3658, 3675), 'Steed.optimizationfns.MultiClassLM.LM', 'MultiClassLM.LM', ([], {}), '()\n', (3673, 3675), False, 'from Steed.optimizationfns import MultiClassLM\n'), ((1534, 1608), 'Steed.drllib.models.ModelA2C', 'models.ModelA2C', (['env.observation_space.shape[0]', 'env.action_space.shape[0]'], {}), '(env.observation_space.shape[0], env.action_space.shape[0])\n', (1549, 1608), False, 'from Steed.drllib import models, utils, common\n'), ((472, 505), 'Steed.drllib.utils.float32_preprocessor', 'utils.float32_preprocessor', (['[obs]'], {}), '([obs])\n', (498, 505), False, 'from Steed.drllib import models, utils, common\n'), ((1316, 1387), 'Steed.drllib.models.ModelA2C', 'models.ModelA2C', (['env.observation_space.shape[0]', '(env.action_space.n - 1)'], {}), '(env.observation_space.shape[0], env.action_space.n - 1)\n', (1331, 1387), False, 'from Steed.drllib import models, utils, common\n'), ((1431, 1498), 'Steed.drllib.models.ModelA2C', 'models.ModelA2C', (['env.observation_space.shape[0]', 'env.action_space.n'], {}), '(env.observation_space.shape[0], env.action_space.n)\n', (1446, 1498), False, 'from Steed.drllib import models, utils, common\n'), ((2540, 2569), 'os.path.join', 'os.path.join', (['save_path', 'name'], {}), '(save_path, name)\n', (2552, 2569), False, 'import os\n'), ((2215, 2226), 'time.time', 'time.time', ([], {}), '()\n', (2224, 2226), False, 'import time\n'), ((3411, 3441), 'torch.log', 'torch.log', (['(2 * math.pi * var_v)'], {}), '(2 * math.pi * var_v)\n', (3420, 3441), False, 'import torch\n')]
import numpy as np import pandas as pd import matplotlib.pyplot as plt selected_df = pd.read_csv('./../selected_countries.csv') # LatAm latAm = selected_df.loc[selected_df['region'] == 'Latin America & the Caribbean'] latAm = latAm.groupby(['year']).mean().reset_index() # Iterate over main categories main_categories = ['hf_score', 'pf_rol', 'pf_ss', 'pf_movement', 'pf_religion', 'pf_assembly', 'pf_expression', 'pf_identity', 'pf_score', 'ef_government', 'ef_legal', 'ef_money', 'ef_trade', 'ef_regulation', 'ef_score'] for i in main_categories: cat = np.array(latAm[i]) plt.plot(range(2008, 2020), cat) plt.title('Latin America | {0} score over time'.format(i)) plt.savefig('latAm_{0}.jpg'.format(i)) plt.show()
[ "numpy.array", "pandas.read_csv", "matplotlib.pyplot.show" ]
[((86, 128), 'pandas.read_csv', 'pd.read_csv', (['"""./../selected_countries.csv"""'], {}), "('./../selected_countries.csv')\n", (97, 128), True, 'import pandas as pd\n'), ((601, 619), 'numpy.array', 'np.array', (['latAm[i]'], {}), '(latAm[i])\n', (609, 619), True, 'import numpy as np\n'), ((767, 777), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (775, 777), True, 'import matplotlib.pyplot as plt\n')]
import cv2 import numpy as np import pycocotools.mask as mask_util import torch from utils.data.structures.bounding_box import BoxList from utils.data.structures.boxlist_ops import cat_boxlist, boxlist_nms, \ boxlist_ml_nms, boxlist_soft_nms, boxlist_box_voting from utils.data.structures.parsing import flip_parsing_featuremap from rcnn.core.config import cfg def im_detect_bbox(model, ims): box_results = [[] for _ in range(len(ims))] features = [] semseg_pred_results = [] results, net_imgs_size, blob_conv, semseg_pred = im_detect_bbox_net(model, ims, cfg.TEST.SCALE, cfg.TEST.MAX_SIZE) if cfg.RPN.RPN_ONLY: return results, None add_results(box_results, results) features.append((net_imgs_size, blob_conv)) semseg_pred_results.append(semseg_pred) if cfg.TEST.BBOX_AUG.ENABLED: if cfg.TEST.BBOX_AUG.H_FLIP: results_hf, net_imgs_size_hf, blob_conv_hf, semseg_pred_hf = im_detect_bbox_net( model, ims, cfg.TEST.SCALE, cfg.TEST.MAX_SIZE, True, net_imgs_size ) add_results(box_results, results_hf) features.append((net_imgs_size_hf, blob_conv_hf)) semseg_pred_results.append(semseg_pred_hf) for scale in cfg.TEST.BBOX_AUG.SCALES: max_size = cfg.TEST.BBOX_AUG.MAX_SIZE results_scl, net_imgs_size_scl, blob_conv_scl, semseg_pred_scl = im_detect_bbox_net( model, ims, scale, max_size, False, net_imgs_size ) add_results(box_results, results_scl) features.append((net_imgs_size_scl, blob_conv_scl)) semseg_pred_results.append(semseg_pred_scl) if cfg.TEST.BBOX_AUG.H_FLIP: results_scl_hf, net_imgs_size_scl_hf, blob_conv_scl_hf, semseg_pred_scl_hf = im_detect_bbox_net( model, ims, scale, max_size, True, net_imgs_size ) add_results(box_results, results_scl_hf) features.append((net_imgs_size_scl_hf, blob_conv_scl_hf)) semseg_pred_results.append(semseg_pred_scl_hf) box_results = [cat_boxlist(result) for result in box_results] if cfg.MODEL.FASTER_ON: box_results = [filter_results(result) for result in box_results] if cfg.MODEL.SEMSEG_ON: semseg_pred_results = np.asarray(semseg_pred_results).transpose((1, 0, 2, 3, 4)) for i in range(len(box_results)): semseg_pred = np.mean(semseg_pred_results[i], axis=0) box_results[i].add_field("semseg", semseg_pred) return box_results, features def im_detect_mask(model, rois, features): _idx = 0 mask_results = [[] for _ in range(len(rois))] mask_scores = [[] for _ in range(len(rois))] conv_features = features[_idx][1] _idx += 1 results = model.mask_net(conv_features, rois, targets=None) if cfg.TEST.BBOX_AUG.ENABLED and cfg.TEST.MASK_AUG.ENABLED: if len(rois[0]) == 0: return results masks = [result.get_field("mask") for result in results] add_results(mask_results, masks) scores = [result.get_field("mask_scores") for result in results] add_results(mask_scores, scores) if cfg.TEST.BBOX_AUG.H_FLIP: rois_hf = [roi.transpose(0) for roi in rois] features_hf = features[_idx][1] _idx += 1 results_hf = model.mask_net(features_hf, rois_hf, targets=None) masks_hf = [result_hf.get_field("mask") for result_hf in results_hf] masks_hf = [mask_hf[:, :, :, ::-1] for mask_hf in masks_hf] add_results(mask_results, masks_hf) scores_hf = [result_hf.get_field("mask_scores") for result_hf in results_hf] add_results(mask_scores, scores_hf) for scale in cfg.TEST.BBOX_AUG.SCALES: rois_scl = [roi.resize(size) for roi, size in zip(rois, features[_idx][0])] features_scl = features[_idx][1] _idx += 1 results_scl = model.mask_net(features_scl, rois_scl, targets=None) masks_scl = [result_scl.get_field("mask") for result_scl in results_scl] add_results(mask_results, masks_scl) scores_scl = [result_scl.get_field("mask_scores") for result_scl in results_scl] add_results(mask_scores, scores_scl) if cfg.TEST.BBOX_AUG.H_FLIP: rois_scl_hf = [roi.resize(size) for roi, size in zip(rois, features[_idx][0])] rois_scl_hf = [roi.transpose(0) for roi in rois_scl_hf] features_scl_hf = features[_idx][1] _idx += 1 results_scl_hf = model.mask_net(features_scl_hf, rois_scl_hf, targets=None) masks_scl_hf = [result_scl_hf.get_field("mask") for result_scl_hf in results_scl_hf] masks_scl_hf = [mask_scl_hf[:, :, :, ::-1] for mask_scl_hf in masks_scl_hf] add_results(mask_results, masks_scl_hf) scores_scl_hf = [result_scl_hf.get_field("mask_scores") for result_scl_hf in results_scl_hf] add_results(mask_scores, scores_scl_hf) for masks_ts, scores_ts, result in zip(mask_results, mask_scores, results): scores_c = np.mean(scores_ts, axis=0) # Combine the predicted soft masks if cfg.TEST.MASK_AUG.HEUR == 'SOFT_AVG': masks_c = np.mean(masks_ts, axis=0) elif cfg.TEST.MASK_AUG.HEUR == 'SOFT_MAX': masks_c = np.amax(masks_ts, axis=0) elif cfg.TEST.MASK_AUG.HEUR == 'LOGIT_AVG': def logit(y): return -1.0 * np.log((1.0 - y) / np.maximum(y, 1e-20)) logit_masks = [logit(y) for y in masks_ts] logit_masks = np.mean(logit_masks, axis=0) masks_c = 1.0 / (1.0 + np.exp(-logit_masks)) else: raise NotImplementedError('Heuristic {} not supported'.format(cfg.TEST.MASK_AUG.HEUR)) result.add_field("mask", masks_c) result.add_field("mask_scores", scores_c) return results def im_detect_parsing(model, rois, features): _idx = 0 parsing_results = [[] for _ in range(len(rois))] parsing_scores = [[] for _ in range(len(rois))] conv_features = features[_idx][1] _idx += 1 results = model.parsing_net(conv_features, rois, targets=None) if cfg.TEST.BBOX_AUG.ENABLED and cfg.TEST.PARSING_AUG.ENABLED: if len(rois[0]) == 0: return results parsings = [result.get_field("parsing") for result in results] add_results(parsing_results, parsings) scores = [result.get_field("parsing_scores") for result in results] add_results(parsing_scores, scores) if cfg.TEST.BBOX_AUG.H_FLIP: rois_hf = [roi.transpose(0) for roi in rois] features_hf = features[_idx][1] _idx += 1 results_hf = model.parsing_net(features_hf, rois_hf, targets=None) parsings_hf = [result_hf.get_field("parsing") for result_hf in results_hf] parsings_hf = [flip_parsing_featuremap(parsing_hf) for parsing_hf in parsings_hf] add_results(parsing_results, parsings_hf) scores_hf = [result_hf.get_field("parsing_scores") for result_hf in results_hf] add_results(parsing_scores, scores_hf) for scale in cfg.TEST.BBOX_AUG.SCALES: rois_scl = [roi.resize(size) for roi, size in zip(rois, features[_idx][0])] features_scl = features[_idx][1] _idx += 1 results_scl = model.parsing_net(features_scl, rois_scl, targets=None) parsings_scl = [result_scl.get_field("parsing") for result_scl in results_scl] add_results(parsing_results, parsings_scl) scores_scl = [result_scl.get_field("parsing_scores") for result_scl in results_scl] add_results(parsing_scores, scores_scl) if cfg.TEST.BBOX_AUG.H_FLIP: rois_scl_hf = [roi.resize(size) for roi, size in zip(rois, features[_idx][0])] rois_scl_hf = [roi.transpose(0) for roi in rois_scl_hf] features_scl_hf = features[_idx][1] _idx += 1 results_scl_hf = model.parsing_net(features_scl_hf, rois_scl_hf, targets=None) parsings_scl_hf = [result_scl_hf.get_field("parsing") for result_scl_hf in results_scl_hf] parsings_scl_hf = [flip_parsing_featuremap(parsing_scl_hf) for parsing_scl_hf in parsings_scl_hf] add_results(parsing_results, parsings_scl_hf) scores_scl_hf = [result_scl_hf.get_field("parsing_scores") for result_scl_hf in results_scl_hf] add_results(parsing_scores, scores_scl_hf) for parsings_ts, scores_ts, result in zip(parsing_results, parsing_scores, results): scores_c = np.mean(scores_ts, axis=0) # Combine the predicted soft parsings if cfg.TEST.PARSING_AUG.HEUR == 'SOFT_AVG': parsings_c = np.mean(parsings_ts, axis=0) elif cfg.TEST.PARSING_AUG.HEUR == 'SOFT_MAX': parsings_c = np.amax(parsings_ts, axis=0) elif cfg.TEST.PARSING_AUG.HEUR == 'LOGIT_AVG': def logit(y): return -1.0 * np.log((1.0 - y) / np.maximum(y, 1e-20)) logit_parsings = [logit(y) for y in parsings_ts] logit_parsings = np.mean(logit_parsings, axis=0) parsings_c = 1.0 / (1.0 + np.exp(-logit_parsings)) else: raise NotImplementedError('Heuristic {} not supported'.format(cfg.TEST.PARSING_AUG.HEUR)) result.add_field("parsing", parsings_c) result.add_field("parsing_scores", scores_c) return results def im_detect_bbox_net(model, ims, target_scale, target_max_size, flip=False, size=None): net_imgs_size = [] results = [] ims_blob = get_blob(ims, target_scale, target_max_size, flip) blob_conv, _results, semseg_pred = model.box_net(ims_blob) if cfg.MODEL.SEMSEG_ON: semseg_pred = semseg_pred.cpu().numpy() if flip: semseg_pred = flip_parsing_featuremap(semseg_pred) semseg_pred = semseg_pred.transpose((0, 2, 3, 1)) im_h, im_w = ims[0].shape[0:2] semseg_pred_resized = [cv2.resize(pred, (im_w, im_h), interpolation=cv2.INTER_LINEAR) for pred in semseg_pred] else: semseg_pred_resized = None for i, im_result in enumerate(_results): net_img_size = im_result.size net_imgs_size.append(net_img_size) if flip: im_result = im_result.transpose(0) if len(cfg.TRAIN.LEFT_RIGHT) > 0: scores = im_result.get_field("scores").reshape(-1, cfg.MODEL.NUM_CLASSES) boxes = im_result.bbox.reshape(-1, cfg.MODEL.NUM_CLASSES, 4) idx = torch.arange(cfg.MODEL.NUM_CLASSES) for j in cfg.TRAIN.LEFT_RIGHT: idx[j[0]] = j[1] idx[j[1]] = j[0] boxes = boxes[:, idx].reshape(-1, 4) scores = scores[:, idx].reshape(-1) im_result.bbox = boxes im_result.add_field("scores", scores) if size: im_result = im_result.resize(size[i]) results.append(im_result) return results, net_imgs_size, blob_conv, semseg_pred_resized def add_results(all_results, results): for i in range(len(all_results)): all_results[i].append(results[i]) def get_blob(ims, target_scale, target_max_size, flip): ims_processed = [] for im in ims: if flip: im = im[:, ::-1, :] im = im.astype(np.float32, copy=False) im_shape = im.shape im_size_min = np.min(im_shape[0:2]) im_size_max = np.max(im_shape[0:2]) im_scale = float(target_scale) / float(im_size_min) # Prevent the biggest axis from being more than max_size if np.round(im_scale * im_size_max) > target_max_size: im_scale = float(target_max_size) / float(im_size_max) im_resized = cv2.resize(im, None, None, fx=im_scale, fy=im_scale, interpolation=cv2.INTER_LINEAR) im_processed = im_resized.transpose(2, 0, 1) im_processed = torch.from_numpy(im_processed).to(torch.device(cfg.DEVICE)) ims_processed.append(im_processed) return ims_processed def filter_results(boxlist): num_classes = cfg.MODEL.NUM_CLASSES if not cfg.TEST.SOFT_NMS.ENABLED and not cfg.TEST.BBOX_VOTE.ENABLED: # multiclass nms scores = boxlist.get_field("scores") device = scores.device num_repeat = int(boxlist.bbox.shape[0] / num_classes) labels = np.tile(np.arange(num_classes), num_repeat) boxlist.add_field("labels", torch.from_numpy(labels).to(dtype=torch.int64, device=device)) fg_labels = torch.from_numpy( (np.arange(boxlist.bbox.shape[0]) % num_classes != 0).astype(int) ).to(dtype=torch.uint8, device=device) _scores = scores > cfg.FAST_RCNN.SCORE_THRESH inds_all = _scores & fg_labels.bool() result = boxlist_ml_nms(boxlist[inds_all], cfg.FAST_RCNN.NMS) else: boxes = boxlist.bbox.reshape(-1, num_classes * 4) scores = boxlist.get_field("scores").reshape(-1, num_classes) device = scores.device result = [] # Apply threshold on detection probabilities and apply NMS # Skip j = 0, because it's the background class inds_all = scores > cfg.FAST_RCNN.SCORE_THRESH for j in range(1, num_classes): inds = inds_all[:, j].nonzero().squeeze(1) scores_j = scores[inds, j] boxes_j = boxes[inds, j * 4: (j + 1) * 4] boxlist_for_class = BoxList(boxes_j, boxlist.size, mode="xyxy") boxlist_for_class.add_field("scores", scores_j) boxlist_for_class_old = boxlist_for_class if cfg.TEST.SOFT_NMS.ENABLED: boxlist_for_class = boxlist_soft_nms( boxlist_for_class, sigma=cfg.TEST.SOFT_NMS.SIGMA, overlap_thresh=cfg.FAST_RCNN.NMS, score_thresh=0.0001, method=cfg.TEST.SOFT_NMS.METHOD ) else: boxlist_for_class = boxlist_nms( boxlist_for_class, cfg.FAST_RCNN.NMS ) # Refine the post-NMS boxes using bounding-box voting if cfg.TEST.BBOX_VOTE.ENABLED and boxes_j.shape[0] > 0: boxlist_for_class = boxlist_box_voting( boxlist_for_class, boxlist_for_class_old, cfg.TEST.BBOX_VOTE.VOTE_TH, scoring_method=cfg.TEST.BBOX_VOTE.SCORING_METHOD ) num_labels = len(boxlist_for_class) boxlist_for_class.add_field( "labels", torch.full((num_labels,), j, dtype=torch.int64, device=device) ) result.append(boxlist_for_class) result = cat_boxlist(result) number_of_detections = len(result) # Limit to max_per_image detections **over all classes** if number_of_detections > cfg.FAST_RCNN.DETECTIONS_PER_IMG > 0: cls_scores = result.get_field("scores") image_thresh, _ = torch.kthvalue( cls_scores.cpu(), number_of_detections - cfg.FAST_RCNN.DETECTIONS_PER_IMG + 1 ) keep = cls_scores >= image_thresh.item() keep = torch.nonzero(keep).squeeze(1) result = result[keep] return result
[ "utils.data.structures.bounding_box.BoxList", "torch.from_numpy", "numpy.arange", "torch.arange", "numpy.mean", "numpy.asarray", "numpy.max", "numpy.exp", "numpy.min", "utils.data.structures.boxlist_ops.boxlist_ml_nms", "numpy.maximum", "utils.data.structures.boxlist_ops.boxlist_nms", "numpy...
[((2178, 2197), 'utils.data.structures.boxlist_ops.cat_boxlist', 'cat_boxlist', (['result'], {}), '(result)\n', (2189, 2197), False, 'from utils.data.structures.boxlist_ops import cat_boxlist, boxlist_nms, boxlist_ml_nms, boxlist_soft_nms, boxlist_box_voting\n'), ((12086, 12107), 'numpy.min', 'np.min', (['im_shape[0:2]'], {}), '(im_shape[0:2])\n', (12092, 12107), True, 'import numpy as np\n'), ((12131, 12152), 'numpy.max', 'np.max', (['im_shape[0:2]'], {}), '(im_shape[0:2])\n', (12137, 12152), True, 'import numpy as np\n'), ((12436, 12525), 'cv2.resize', 'cv2.resize', (['im', 'None', 'None'], {'fx': 'im_scale', 'fy': 'im_scale', 'interpolation': 'cv2.INTER_LINEAR'}), '(im, None, None, fx=im_scale, fy=im_scale, interpolation=cv2.\n INTER_LINEAR)\n', (12446, 12525), False, 'import cv2\n'), ((13497, 13549), 'utils.data.structures.boxlist_ops.boxlist_ml_nms', 'boxlist_ml_nms', (['boxlist[inds_all]', 'cfg.FAST_RCNN.NMS'], {}), '(boxlist[inds_all], cfg.FAST_RCNN.NMS)\n', (13511, 13549), False, 'from utils.data.structures.boxlist_ops import cat_boxlist, boxlist_nms, boxlist_ml_nms, boxlist_soft_nms, boxlist_box_voting\n'), ((15492, 15511), 'utils.data.structures.boxlist_ops.cat_boxlist', 'cat_boxlist', (['result'], {}), '(result)\n', (15503, 15511), False, 'from utils.data.structures.boxlist_ops import cat_boxlist, boxlist_nms, boxlist_ml_nms, boxlist_soft_nms, boxlist_box_voting\n'), ((2521, 2560), 'numpy.mean', 'np.mean', (['semseg_pred_results[i]'], {'axis': '(0)'}), '(semseg_pred_results[i], axis=0)\n', (2528, 2560), True, 'import numpy as np\n'), ((5358, 5384), 'numpy.mean', 'np.mean', (['scores_ts'], {'axis': '(0)'}), '(scores_ts, axis=0)\n', (5365, 5384), True, 'import numpy as np\n'), ((9095, 9121), 'numpy.mean', 'np.mean', (['scores_ts'], {'axis': '(0)'}), '(scores_ts, axis=0)\n', (9102, 9121), True, 'import numpy as np\n'), ((10430, 10466), 'utils.data.structures.parsing.flip_parsing_featuremap', 'flip_parsing_featuremap', (['semseg_pred'], {}), '(semseg_pred)\n', (10453, 10466), False, 'from utils.data.structures.parsing import flip_parsing_featuremap\n'), ((10598, 10660), 'cv2.resize', 'cv2.resize', (['pred', '(im_w, im_h)'], {'interpolation': 'cv2.INTER_LINEAR'}), '(pred, (im_w, im_h), interpolation=cv2.INTER_LINEAR)\n', (10608, 10660), False, 'import cv2\n'), ((12294, 12326), 'numpy.round', 'np.round', (['(im_scale * im_size_max)'], {}), '(im_scale * im_size_max)\n', (12302, 12326), True, 'import numpy as np\n'), ((12633, 12657), 'torch.device', 'torch.device', (['cfg.DEVICE'], {}), '(cfg.DEVICE)\n', (12645, 12657), False, 'import torch\n'), ((13075, 13097), 'numpy.arange', 'np.arange', (['num_classes'], {}), '(num_classes)\n', (13084, 13097), True, 'import numpy as np\n'), ((14150, 14193), 'utils.data.structures.bounding_box.BoxList', 'BoxList', (['boxes_j', 'boxlist.size'], {'mode': '"""xyxy"""'}), "(boxes_j, boxlist.size, mode='xyxy')\n", (14157, 14193), False, 'from utils.data.structures.bounding_box import BoxList\n'), ((2392, 2423), 'numpy.asarray', 'np.asarray', (['semseg_pred_results'], {}), '(semseg_pred_results)\n', (2402, 2423), True, 'import numpy as np\n'), ((5514, 5539), 'numpy.mean', 'np.mean', (['masks_ts'], {'axis': '(0)'}), '(masks_ts, axis=0)\n', (5521, 5539), True, 'import numpy as np\n'), ((7271, 7306), 'utils.data.structures.parsing.flip_parsing_featuremap', 'flip_parsing_featuremap', (['parsing_hf'], {}), '(parsing_hf)\n', (7294, 7306), False, 'from utils.data.structures.parsing import flip_parsing_featuremap\n'), ((9260, 9288), 'numpy.mean', 'np.mean', (['parsings_ts'], {'axis': '(0)'}), '(parsings_ts, axis=0)\n', (9267, 9288), True, 'import numpy as np\n'), ((11169, 11204), 'torch.arange', 'torch.arange', (['cfg.MODEL.NUM_CLASSES'], {}), '(cfg.MODEL.NUM_CLASSES)\n', (11181, 11204), False, 'import torch\n'), ((12599, 12629), 'torch.from_numpy', 'torch.from_numpy', (['im_processed'], {}), '(im_processed)\n', (12615, 12629), False, 'import torch\n'), ((14390, 14553), 'utils.data.structures.boxlist_ops.boxlist_soft_nms', 'boxlist_soft_nms', (['boxlist_for_class'], {'sigma': 'cfg.TEST.SOFT_NMS.SIGMA', 'overlap_thresh': 'cfg.FAST_RCNN.NMS', 'score_thresh': '(0.0001)', 'method': 'cfg.TEST.SOFT_NMS.METHOD'}), '(boxlist_for_class, sigma=cfg.TEST.SOFT_NMS.SIGMA,\n overlap_thresh=cfg.FAST_RCNN.NMS, score_thresh=0.0001, method=cfg.TEST.\n SOFT_NMS.METHOD)\n', (14406, 14553), False, 'from utils.data.structures.boxlist_ops import cat_boxlist, boxlist_nms, boxlist_ml_nms, boxlist_soft_nms, boxlist_box_voting\n'), ((14725, 14774), 'utils.data.structures.boxlist_ops.boxlist_nms', 'boxlist_nms', (['boxlist_for_class', 'cfg.FAST_RCNN.NMS'], {}), '(boxlist_for_class, cfg.FAST_RCNN.NMS)\n', (14736, 14774), False, 'from utils.data.structures.boxlist_ops import cat_boxlist, boxlist_nms, boxlist_ml_nms, boxlist_soft_nms, boxlist_box_voting\n'), ((14988, 15131), 'utils.data.structures.boxlist_ops.boxlist_box_voting', 'boxlist_box_voting', (['boxlist_for_class', 'boxlist_for_class_old', 'cfg.TEST.BBOX_VOTE.VOTE_TH'], {'scoring_method': 'cfg.TEST.BBOX_VOTE.SCORING_METHOD'}), '(boxlist_for_class, boxlist_for_class_old, cfg.TEST.\n BBOX_VOTE.VOTE_TH, scoring_method=cfg.TEST.BBOX_VOTE.SCORING_METHOD)\n', (15006, 15131), False, 'from utils.data.structures.boxlist_ops import cat_boxlist, boxlist_nms, boxlist_ml_nms, boxlist_soft_nms, boxlist_box_voting\n'), ((15348, 15410), 'torch.full', 'torch.full', (['(num_labels,)', 'j'], {'dtype': 'torch.int64', 'device': 'device'}), '((num_labels,), j, dtype=torch.int64, device=device)\n', (15358, 15410), False, 'import torch\n'), ((15947, 15966), 'torch.nonzero', 'torch.nonzero', (['keep'], {}), '(keep)\n', (15960, 15966), False, 'import torch\n'), ((5623, 5648), 'numpy.amax', 'np.amax', (['masks_ts'], {'axis': '(0)'}), '(masks_ts, axis=0)\n', (5630, 5648), True, 'import numpy as np\n'), ((8660, 8699), 'utils.data.structures.parsing.flip_parsing_featuremap', 'flip_parsing_featuremap', (['parsing_scl_hf'], {}), '(parsing_scl_hf)\n', (8683, 8699), False, 'from utils.data.structures.parsing import flip_parsing_featuremap\n'), ((9378, 9406), 'numpy.amax', 'np.amax', (['parsings_ts'], {'axis': '(0)'}), '(parsings_ts, axis=0)\n', (9385, 9406), True, 'import numpy as np\n'), ((13148, 13172), 'torch.from_numpy', 'torch.from_numpy', (['labels'], {}), '(labels)\n', (13164, 13172), False, 'import torch\n'), ((5908, 5936), 'numpy.mean', 'np.mean', (['logit_masks'], {'axis': '(0)'}), '(logit_masks, axis=0)\n', (5915, 5936), True, 'import numpy as np\n'), ((9678, 9709), 'numpy.mean', 'np.mean', (['logit_parsings'], {'axis': '(0)'}), '(logit_parsings, axis=0)\n', (9685, 9709), True, 'import numpy as np\n'), ((5977, 5997), 'numpy.exp', 'np.exp', (['(-logit_masks)'], {}), '(-logit_masks)\n', (5983, 5997), True, 'import numpy as np\n'), ((9753, 9776), 'numpy.exp', 'np.exp', (['(-logit_parsings)'], {}), '(-logit_parsings)\n', (9759, 9776), True, 'import numpy as np\n'), ((13264, 13296), 'numpy.arange', 'np.arange', (['boxlist.bbox.shape[0]'], {}), '(boxlist.bbox.shape[0])\n', (13273, 13296), True, 'import numpy as np\n'), ((5793, 5813), 'numpy.maximum', 'np.maximum', (['y', '(1e-20)'], {}), '(y, 1e-20)\n', (5803, 5813), True, 'import numpy as np\n'), ((9554, 9574), 'numpy.maximum', 'np.maximum', (['y', '(1e-20)'], {}), '(y, 1e-20)\n', (9564, 9574), True, 'import numpy as np\n')]
""" This script is used to download the public planck data To run it: python get_planck_data.py global.dict It will download maps, likelihood masks and beams of planck """ import numpy as np from pspy import pspy_utils, so_dict import sys import wget import tarfile import astropy.io.fits as fits d = so_dict.so_dict() d.read_from_file(sys.argv[1]) # You have to spefify the data directory in which the products will be downloaded data_dir = d["data_dir"] freqs = d["freqs"] pspy_utils.create_directory(data_dir) # Choose what you want to download, if this is your first try, all of this should be set to True download_maps = False download_likelihood_mask = False download_beams = True if download_maps == True: print("Download Planck data maps") maps_dir = data_dir + "/maps" pspy_utils.create_directory(maps_dir) # Planck keep inconsistent notation for the halfmission, sometimes 'halfmission-1' sometimes 'hm1' splits = ["halfmission-1", "halfmission-2"] for hm in splits: for f in freqs: url = "http://pla.esac.esa.int/pla/aio/product-action?MAP.MAP_ID=HFI_SkyMap_%s_2048_R3.01_%s.fits" % (f, hm) print(url) if f != "353": wget.download(url, "%s/HFI_SkyMap_%s_2048_R3.01_%s.fits" % (maps_dir, f, hm)) else: wget.download(url, "%s/HFI_SkyMap_%s-psb_2048_R3.01_%s.fits" % (maps_dir, f, hm)) if download_likelihood_mask == True: print("Download Planck likelihood mask") likelihood_mask_dir = data_dir + "/likelihood_mask" pspy_utils.create_directory(likelihood_mask_dir) splits = ["hm1", "hm2"] for hm in splits: for f in freqs: if f == "353": continue url = "http://pla.esac.esa.int/pla/aio/product-action?MAP.MAP_ID=COM_Mask_Likelihood-temperature-%s-%s_2048_R3.00.fits" % (f, hm) wget.download(url, "%s/COM_Mask_Likelihood-temperature-%s-%s_2048_R3.00.fits" % (likelihood_mask_dir, f, hm)) url = "http://pla.esac.esa.int/pla/aio/product-action?MAP.MAP_ID=COM_Mask_Likelihood-polarization-%s-%s_2048_R3.00.fits" % (f, hm) wget.download(url, "%s/COM_Mask_Likelihood-polarization-%s-%s_2048_R3.00.fits" % (likelihood_mask_dir, f, hm)) if download_beams == True: print("Download Planck beams") beam_dir = data_dir + "/beams" pspy_utils.create_directory(beam_dir) url = "http://pla.esac.esa.int/pla/aio/product-action?DOCUMENT.DOCUMENT_ID=HFI_RIMO_BEAMS_R3.01.tar.gz" wget.download(url, "%s/HFI_RIMO_BEAMS_R3.01.tar.gz" % beam_dir) tf = tarfile.open("%s/HFI_RIMO_BEAMS_R3.01.tar.gz" % beam_dir) tf.extractall(beam_dir) tf.close() spectra = ["TT", "EE", "BB", "TE"] leakage_term = {} for spec in spectra: leakage_term[spec] = ["%s_2_TT" % spec, "%s_2_EE" % spec, "%s_2_BB" % spec, "%s_2_TE" % spec, "%s_2_TB" % spec, "%s_2_EB" % spec, "%s_2_ET" % spec, "%s_2_BT" % spec, "%s_2_BE" % spec] splits = ["hm1","hm2"] my_lmax = 6000 for hm in splits: for f in freqs: # if f == "353": continue Wl = fits.open("%s/BeamWf_HFI_R3.01/Wl_R3.01_fullsky_%s%sx%s%s.fits" % (beam_dir, f, hm, f, hm)) Wl_dict = {} num = 1 for spec in spectra: for leak in leakage_term[spec]: Wl_dict[leak] = Wl[num].data[leak] num += 1 lmax = len(Wl_dict["TT_2_TT"][0]) bl_T = np.zeros(my_lmax) bl_pol = np.zeros(my_lmax) # We will call Planck beam the sqrt or the XX_2_XX term of the beam leakage matrix bl_T[:lmax] = np.sqrt(Wl_dict["TT_2_TT"][0]) bl_pol[:lmax] = np.sqrt(Wl_dict["EE_2_EE"][0]) # Here we 'extrapolate' slighty the Planck beam, just repeating the same value after l=max(l) in Planck # In practice this won't be used in the analysis bl_T[lmax:] = bl_T[lmax-1] bl_pol[lmax:] = bl_pol[lmax-1] l=np.arange(my_lmax) np.savetxt("%s/beam_T_%s_%s.dat" % (beam_dir, f, hm), np.transpose([l, bl_T])) np.savetxt("%s/beam_pol_%s_%s.dat" % (beam_dir, f, hm), np.transpose([l, bl_pol]))
[ "pspy.so_dict.so_dict", "wget.download", "tarfile.open", "numpy.sqrt", "pspy.pspy_utils.create_directory", "numpy.zeros", "astropy.io.fits.open", "numpy.transpose", "numpy.arange" ]
[((303, 320), 'pspy.so_dict.so_dict', 'so_dict.so_dict', ([], {}), '()\n', (318, 320), False, 'from pspy import pspy_utils, so_dict\n'), ((479, 516), 'pspy.pspy_utils.create_directory', 'pspy_utils.create_directory', (['data_dir'], {}), '(data_dir)\n', (506, 516), False, 'from pspy import pspy_utils, so_dict\n'), ((796, 833), 'pspy.pspy_utils.create_directory', 'pspy_utils.create_directory', (['maps_dir'], {}), '(maps_dir)\n', (823, 833), False, 'from pspy import pspy_utils, so_dict\n'), ((1555, 1603), 'pspy.pspy_utils.create_directory', 'pspy_utils.create_directory', (['likelihood_mask_dir'], {}), '(likelihood_mask_dir)\n', (1582, 1603), False, 'from pspy import pspy_utils, so_dict\n'), ((2347, 2384), 'pspy.pspy_utils.create_directory', 'pspy_utils.create_directory', (['beam_dir'], {}), '(beam_dir)\n', (2374, 2384), False, 'from pspy import pspy_utils, so_dict\n'), ((2497, 2560), 'wget.download', 'wget.download', (['url', "('%s/HFI_RIMO_BEAMS_R3.01.tar.gz' % beam_dir)"], {}), "(url, '%s/HFI_RIMO_BEAMS_R3.01.tar.gz' % beam_dir)\n", (2510, 2560), False, 'import wget\n'), ((2570, 2627), 'tarfile.open', 'tarfile.open', (["('%s/HFI_RIMO_BEAMS_R3.01.tar.gz' % beam_dir)"], {}), "('%s/HFI_RIMO_BEAMS_R3.01.tar.gz' % beam_dir)\n", (2582, 2627), False, 'import tarfile\n'), ((1869, 1988), 'wget.download', 'wget.download', (['url', "('%s/COM_Mask_Likelihood-temperature-%s-%s_2048_R3.00.fits' % (\n likelihood_mask_dir, f, hm))"], {}), "(url, \n '%s/COM_Mask_Likelihood-temperature-%s-%s_2048_R3.00.fits' % (\n likelihood_mask_dir, f, hm))\n", (1882, 1988), False, 'import wget\n'), ((2134, 2254), 'wget.download', 'wget.download', (['url', "('%s/COM_Mask_Likelihood-polarization-%s-%s_2048_R3.00.fits' % (\n likelihood_mask_dir, f, hm))"], {}), "(url, \n '%s/COM_Mask_Likelihood-polarization-%s-%s_2048_R3.00.fits' % (\n likelihood_mask_dir, f, hm))\n", (2147, 2254), False, 'import wget\n'), ((3350, 3445), 'astropy.io.fits.open', 'fits.open', (["('%s/BeamWf_HFI_R3.01/Wl_R3.01_fullsky_%s%sx%s%s.fits' % (beam_dir, f, hm,\n f, hm))"], {}), "('%s/BeamWf_HFI_R3.01/Wl_R3.01_fullsky_%s%sx%s%s.fits' % (beam_dir,\n f, hm, f, hm))\n", (3359, 3445), True, 'import astropy.io.fits as fits\n'), ((3719, 3736), 'numpy.zeros', 'np.zeros', (['my_lmax'], {}), '(my_lmax)\n', (3727, 3736), True, 'import numpy as np\n'), ((3758, 3775), 'numpy.zeros', 'np.zeros', (['my_lmax'], {}), '(my_lmax)\n', (3766, 3775), True, 'import numpy as np\n'), ((3898, 3928), 'numpy.sqrt', 'np.sqrt', (["Wl_dict['TT_2_TT'][0]"], {}), "(Wl_dict['TT_2_TT'][0])\n", (3905, 3928), True, 'import numpy as np\n'), ((3957, 3987), 'numpy.sqrt', 'np.sqrt', (["Wl_dict['EE_2_EE'][0]"], {}), "(Wl_dict['EE_2_EE'][0])\n", (3964, 3987), True, 'import numpy as np\n'), ((4263, 4281), 'numpy.arange', 'np.arange', (['my_lmax'], {}), '(my_lmax)\n', (4272, 4281), True, 'import numpy as np\n'), ((1218, 1295), 'wget.download', 'wget.download', (['url', "('%s/HFI_SkyMap_%s_2048_R3.01_%s.fits' % (maps_dir, f, hm))"], {}), "(url, '%s/HFI_SkyMap_%s_2048_R3.01_%s.fits' % (maps_dir, f, hm))\n", (1231, 1295), False, 'import wget\n'), ((1330, 1415), 'wget.download', 'wget.download', (['url', "('%s/HFI_SkyMap_%s-psb_2048_R3.01_%s.fits' % (maps_dir, f, hm))"], {}), "(url, '%s/HFI_SkyMap_%s-psb_2048_R3.01_%s.fits' % (maps_dir, f,\n hm))\n", (1343, 1415), False, 'import wget\n'), ((4348, 4371), 'numpy.transpose', 'np.transpose', (['[l, bl_T]'], {}), '([l, bl_T])\n', (4360, 4371), True, 'import numpy as np\n'), ((4441, 4466), 'numpy.transpose', 'np.transpose', (['[l, bl_pol]'], {}), '([l, bl_pol])\n', (4453, 4466), True, 'import numpy as np\n')]
import os print(os.environ.get('tushare_token')) import numpy as np print(np.__version__) # 1.15.1 import matplotlib print(matplotlib.matplotlib_fname()) # import matplotlib.pyplot as plt # x = np.array([1, 2, 3, 4, 5, 6]) # y = np.array([10, 5, 15, 10, 30, 20]) # plt.plot(x, y, color='blue') # plt.show() # plt.savefig('testblueline.jpg')#将生成的图表保存为图片 import numpy as np import matplotlib.pyplot as plt import matplotlib.patches as patches import matplotlib.path as path import matplotlib.animation as animation # Fixing random state for reproducibility np.random.seed(19680801) # histogram our data with numpy data = np.random.randn(1000) n, bins = np.histogram(data, 100) # get the corners of the rectangles for the histogram left = bins[:-1] right = bins[1:] bottom = np.zeros(len(left)) top = bottom + n nrects = len(left) nverts = nrects * (1 + 3 + 1) verts = np.zeros((nverts, 2)) codes = np.full(nverts, path.Path.LINETO) codes[0::5] = path.Path.MOVETO codes[4::5] = path.Path.CLOSEPOLY verts[0::5, 0] = left verts[0::5, 1] = bottom verts[1::5, 0] = left verts[1::5, 1] = top verts[2::5, 0] = right verts[2::5, 1] = top verts[3::5, 0] = right verts[3::5, 1] = bottom patch = None def animate(i): # simulate new data coming in data = np.random.randn(1000) n, bins = np.histogram(data, 100) top = bottom + n verts[1::5, 1] = top verts[2::5, 1] = top return [patch, ] fig, ax = plt.subplots() barpath = path.Path(verts, codes) patch = patches.PathPatch(barpath, facecolor='green', edgecolor='yellow', alpha=0.5) ax.add_patch(patch) ax.set_xlim(left[0], right[-1]) ax.set_ylim(bottom.min(), top.max()) ani = animation.FuncAnimation(fig, animate, 50, repeat=False, blit=True) plt.show()
[ "numpy.histogram", "matplotlib.path.Path", "matplotlib.animation.FuncAnimation", "os.environ.get", "numpy.zeros", "matplotlib.patches.PathPatch", "numpy.random.seed", "numpy.full", "numpy.random.randn", "matplotlib.pyplot.subplots", "matplotlib.matplotlib_fname", "matplotlib.pyplot.show" ]
[((560, 584), 'numpy.random.seed', 'np.random.seed', (['(19680801)'], {}), '(19680801)\n', (574, 584), True, 'import numpy as np\n'), ((625, 646), 'numpy.random.randn', 'np.random.randn', (['(1000)'], {}), '(1000)\n', (640, 646), True, 'import numpy as np\n'), ((657, 680), 'numpy.histogram', 'np.histogram', (['data', '(100)'], {}), '(data, 100)\n', (669, 680), True, 'import numpy as np\n'), ((873, 894), 'numpy.zeros', 'np.zeros', (['(nverts, 2)'], {}), '((nverts, 2))\n', (881, 894), True, 'import numpy as np\n'), ((903, 936), 'numpy.full', 'np.full', (['nverts', 'path.Path.LINETO'], {}), '(nverts, path.Path.LINETO)\n', (910, 936), True, 'import numpy as np\n'), ((1421, 1435), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (1433, 1435), True, 'import matplotlib.pyplot as plt\n'), ((1446, 1469), 'matplotlib.path.Path', 'path.Path', (['verts', 'codes'], {}), '(verts, codes)\n', (1455, 1469), True, 'import matplotlib.path as path\n'), ((1478, 1554), 'matplotlib.patches.PathPatch', 'patches.PathPatch', (['barpath'], {'facecolor': '"""green"""', 'edgecolor': '"""yellow"""', 'alpha': '(0.5)'}), "(barpath, facecolor='green', edgecolor='yellow', alpha=0.5)\n", (1495, 1554), True, 'import matplotlib.patches as patches\n'), ((1652, 1718), 'matplotlib.animation.FuncAnimation', 'animation.FuncAnimation', (['fig', 'animate', '(50)'], {'repeat': '(False)', 'blit': '(True)'}), '(fig, animate, 50, repeat=False, blit=True)\n', (1675, 1718), True, 'import matplotlib.animation as animation\n'), ((1719, 1729), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1727, 1729), True, 'import matplotlib.pyplot as plt\n'), ((16, 47), 'os.environ.get', 'os.environ.get', (['"""tushare_token"""'], {}), "('tushare_token')\n", (30, 47), False, 'import os\n'), ((126, 155), 'matplotlib.matplotlib_fname', 'matplotlib.matplotlib_fname', ([], {}), '()\n', (153, 155), False, 'import matplotlib\n'), ((1258, 1279), 'numpy.random.randn', 'np.random.randn', (['(1000)'], {}), '(1000)\n', (1273, 1279), True, 'import numpy as np\n'), ((1294, 1317), 'numpy.histogram', 'np.histogram', (['data', '(100)'], {}), '(data, 100)\n', (1306, 1317), True, 'import numpy as np\n')]
import numpy as np from nlplingo.tasks.common.binary.binary_event_entity import BinaryEventEntity from nlplingo.common.data_types import int_type class EventArgumentExample(BinaryEventEntity): def __init__(self, arg0, arg1, event_domain, label_str): # def __init__(self, anchor, argument, sentence, event_domain, extractor_params, features, hyper_params, event_role=None, usable_features=None): """We are given an anchor, candidate argument, sentence as context, and a role label (absent in decoding) :type anchor: nlplingo.text.text_span.Anchor :type argument: nlplingo.text.text_span.EntityMention :type sentence: nlplingo.text.text_span.Sentence :type event_domain: nlplingo.event.event_domain.EventDomain :type extractor_params: dict :type features: nlplingo.tasks.eventargument.feature.EventArgumentFeature :type hyper_params: nlplingo.nn.extractor.HyperParameters :type event_role: str """ super(EventArgumentExample, self).__init__(arg0, arg1, event_domain, label_str) num_labels = len(self.event_domain.event_roles) self.label = np.zeros(num_labels, dtype=int_type) # vec_size = extractor_params['embeddings']['vector_size'] # anchor_datapoint = EventDatapoint( # anchor, event_domain, vec_size, anchor.label, usable_features) #argument_datapoint = EntityDatapoint( # argument, event_domain, vec_size, argument.label, usable_features) #super(EventArgumentExample, self).__init__( # anchor_datapoint, argument_datapoint, # event_domain, features, event_role, usable_features) # self.sentence = sentence # self.anchor_obj = None # if 'none_token_index' in extractor_params['embeddings']: # none_token_index = extractor_params['embeddings']['none_token_index'] # else: # none_token_index = 1 #self._allocate_arrays(hyper_params, # extractor_params['embeddings']['vector_size'], # none_token_index, # features) @property def event_role(self): """:rtype: str""" return self.label_str @event_role.setter def event_role(self, label): """:type label: str""" self.label_str = label @property def anchor(self): """:rtype: nlplingo.text.text_span.Anchor""" return self.arg0.span @property def argument(self): """:rtype: nlplingo.text.text_span.EventArgument""" return self.arg1.span """ @argument.setter def argument(self, argument): :type argument: nlplingo.text.text_span.EventArgument argument_datapoint = EntityDatapoint( argument, self.event_domain, self.argument.embedding_vector_size, argument.label, usable_features) self.right_datapoint = argument_datapoint """ def get_event_role_index(self): """ +1 """ return self.event_domain.get_event_role_index(self.event_role) def to_triplet_with_relation(self): # This can only be used for within-sentence relations. triplet = self.to_triplet() triplet.update({'relation' : self.event_role}) return triplet
[ "numpy.zeros" ]
[((1154, 1190), 'numpy.zeros', 'np.zeros', (['num_labels'], {'dtype': 'int_type'}), '(num_labels, dtype=int_type)\n', (1162, 1190), True, 'import numpy as np\n')]
# Imports here import pandas as pd import numpy as np import time import matplotlib.pyplot as plt import torch from torch import nn, optim from torchvision import datasets, transforms, models, utils import json import scipy.io from pprint import pprint from collections import OrderedDict from PIL import Image import warnings warnings.filterwarnings('ignore') import argparse # get the data. def load_data(): # paths for data. data_dir = '../aipnd-project/flowers' train_dir = data_dir + '/train' valid_dir = data_dir + '/valid' test_dir = data_dir + '/test' # transform data. train_transforms = transforms.Compose([ transforms.Resize(255), transforms.RandomRotation(30), transforms.RandomHorizontalFlip(), transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) ]) tv_transforms = transforms.Compose([ transforms.Resize(255), transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) ]) # load the data. train_data = datasets.ImageFolder(train_dir, transform = train_transforms) test_data = datasets.ImageFolder(test_dir, transform = tv_transforms) valid_data = datasets.ImageFolder(valid_dir, transform = tv_transforms) # define dataloaders. trainloader = torch.utils.data.DataLoader(train_data, batch_size = 64, shuffle = True) testloader = torch.utils.data.DataLoader(test_data, batch_size = 64) validloader = torch.utils.data.DataLoader(valid_data, batch_size = 64) class_to_idx = train_data.class_to_idx return trainloader, testloader, validloader, class_to_idx # build model and set up network. def build_model(hidden_layers, learning_rate, class_to_idx, power): device = torch.device("cuda" if power and torch.cuda.is_available() else "cpu") model = models.densenet161(pretrained=True) for param in model.parameters(): param.requires_grad = False classifier_input_size = model.classifier.in_features output_size = 102 classifier = nn.Sequential(OrderedDict([ ('fc1', nn.Linear(classifier_input_size, hidden_layers)), ('relu', nn.ReLU()), ('fc2', nn.Linear(hidden_layers, output_size)), ('output', nn.LogSoftmax(dim=1)) ])) model.classifier = classifier model.class_to_idx = class_to_idx criterion = nn.NLLLoss() optimizer = optim.Adam(model.classifier.parameters(), learning_rate) model.to(device) return model, criterion, optimizer # train the model. def train_model(model, learning_rate, criterion, optimizer, trainloader, validloader, power): device = torch.device("cuda" if power and torch.cuda.is_available() else "cpu") model.train() epochs = 10 steps = 0 running_loss = 0 print_every = 50 for epoch in range(epochs): for inputs, labels in trainloader: steps += 1 # Move input and label tensors to the default device inputs, labels = inputs.to(device), labels.to(device) optimizer.zero_grad() logps = model.forward(inputs) loss = criterion(logps, labels) loss.backward() optimizer.step() running_loss += loss.item() if steps % print_every == 0: test_loss = 0 accuracy = 0 model.eval() with torch.no_grad(): for inputs, labels in validloader: inputs, labels = inputs.to(device), labels.to(device) logps = model.forward(inputs) batch_loss = criterion(logps, labels) test_loss += batch_loss.item() # Calculate accuracy ps = torch.exp(logps) top_p, top_class = ps.topk(1, dim=1) equals = top_class == labels.view(*top_class.shape) accuracy += torch.mean(equals.type(torch.FloatTensor)).item() print(f"Epoch {epoch+1}/{epochs}.. " f"Train loss: {running_loss/print_every:.3f}.. " f"Valid loss: {test_loss/len(validloader):.3f}.. " f"Valid accuracy: {accuracy/len(validloader):.3f}") running_loss = 0 model.train() return model # save the checkpoint. def save_checkpoint(model, optimizer, path, hidden_layers, learning_rate, epochs): model.cpu model.class_to_idx = train_data.class_to_idx torch.save({ "arch": "densenet121", "learning_rate": learning_rate, "hidden_layers": hidden_layers, "epochs": epochs, "state_dict": model.state_dict(), "optimizer" : optimizer.state_dict(), "class_to_idx" : model.class_to_idx}, path) print ("model is saved.") # load the checkpoint. def load_checkpoint(path="checkpoint.pth"): state = torch.load(path) learning_rate = state["learning_rate"] class_to_idx = state["class_to_idx"] hidden_layers = state["hidden_layers"] model, _, _ = build_model(hidden_layers, learning_rate, class_to_idx, power="gpu") optimizer = optim.Adam(model.classifier.parameters(), lr=0.001) optimizer.load_state_dict(state["optimizer"]) model.load_state_dict(state["state_dict"]) return model # open & process data. def process_image(image_path): import_image = Image.open(image_path) make_adjustments = transforms.Compose([ transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) ]) adjusted_image = make_adjustments(import_image) return adjusted_image # predict with processed picture def predict(image_path, model, topk, power): model.eval() device = torch.device("cuda" if torch.cuda.is_available() else "cpu") image = process_image(image_path) image = image.unsqueeze(0) image = image.float() with torch.no_grad(): output = model.forward(image.to(device)) top_prob, top_labels = torch.topk(output, topk) top_prob = nn.functional.softmax(output.data,dim=1) return top_prob.topk(topk) def output(image_path, topk, model, power, class_to_idx, cat_to_name): device = torch.device("cuda" if torch.cuda.is_available() else "cpu") top_prob, top_classes = predict(image_path, model, topk, power) top_classes = list(np.array(top_classes)[0]) labels = [] for class_idx in top_classes: string_label = list(class_to_idx.keys())[list(class_to_idx.values()).index(int(class_idx))] actual_label = cat_to_name[string_label] labels.append(actual_label) a = list(np.array(top_prob[0])) b = labels print (a) print (b) print(f"Correct classification: {a[0]}") print(f"Correct prediction: {b[0]}")
[ "torch.nn.ReLU", "torchvision.models.densenet161", "torch.exp", "numpy.array", "torch.cuda.is_available", "torch.nn.functional.softmax", "torchvision.datasets.ImageFolder", "torchvision.transforms.ToTensor", "torch.topk", "torchvision.transforms.RandomHorizontalFlip", "torch.nn.NLLLoss", "torc...
[((327, 360), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (350, 360), False, 'import warnings\n'), ((1201, 1260), 'torchvision.datasets.ImageFolder', 'datasets.ImageFolder', (['train_dir'], {'transform': 'train_transforms'}), '(train_dir, transform=train_transforms)\n', (1221, 1260), False, 'from torchvision import datasets, transforms, models, utils\n'), ((1311, 1366), 'torchvision.datasets.ImageFolder', 'datasets.ImageFolder', (['test_dir'], {'transform': 'tv_transforms'}), '(test_dir, transform=tv_transforms)\n', (1331, 1366), False, 'from torchvision import datasets, transforms, models, utils\n'), ((1418, 1474), 'torchvision.datasets.ImageFolder', 'datasets.ImageFolder', (['valid_dir'], {'transform': 'tv_transforms'}), '(valid_dir, transform=tv_transforms)\n', (1438, 1474), False, 'from torchvision import datasets, transforms, models, utils\n'), ((1554, 1622), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['train_data'], {'batch_size': '(64)', 'shuffle': '(True)'}), '(train_data, batch_size=64, shuffle=True)\n', (1581, 1622), False, 'import torch\n'), ((1724, 1777), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['test_data'], {'batch_size': '(64)'}), '(test_data, batch_size=64)\n', (1751, 1777), False, 'import torch\n'), ((1838, 1892), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['valid_data'], {'batch_size': '(64)'}), '(valid_data, batch_size=64)\n', (1865, 1892), False, 'import torch\n'), ((2241, 2276), 'torchvision.models.densenet161', 'models.densenet161', ([], {'pretrained': '(True)'}), '(pretrained=True)\n', (2259, 2276), False, 'from torchvision import datasets, transforms, models, utils\n'), ((2768, 2780), 'torch.nn.NLLLoss', 'nn.NLLLoss', ([], {}), '()\n', (2778, 2780), False, 'from torch import nn, optim\n'), ((5375, 5391), 'torch.load', 'torch.load', (['path'], {}), '(path)\n', (5385, 5391), False, 'import torch\n'), ((5878, 5900), 'PIL.Image.open', 'Image.open', (['image_path'], {}), '(image_path)\n', (5888, 5900), False, 'from PIL import Image\n'), ((6523, 6538), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (6536, 6538), False, 'import torch\n'), ((6620, 6644), 'torch.topk', 'torch.topk', (['output', 'topk'], {}), '(output, topk)\n', (6630, 6644), False, 'import torch\n'), ((6673, 6714), 'torch.nn.functional.softmax', 'nn.functional.softmax', (['output.data'], {'dim': '(1)'}), '(output.data, dim=1)\n', (6694, 6714), False, 'from torch import nn, optim\n'), ((7287, 7308), 'numpy.array', 'np.array', (['top_prob[0]'], {}), '(top_prob[0])\n', (7295, 7308), True, 'import numpy as np\n'), ((653, 675), 'torchvision.transforms.Resize', 'transforms.Resize', (['(255)'], {}), '(255)\n', (670, 675), False, 'from torchvision import datasets, transforms, models, utils\n'), ((681, 710), 'torchvision.transforms.RandomRotation', 'transforms.RandomRotation', (['(30)'], {}), '(30)\n', (706, 710), False, 'from torchvision import datasets, transforms, models, utils\n'), ((716, 749), 'torchvision.transforms.RandomHorizontalFlip', 'transforms.RandomHorizontalFlip', ([], {}), '()\n', (747, 749), False, 'from torchvision import datasets, transforms, models, utils\n'), ((755, 781), 'torchvision.transforms.CenterCrop', 'transforms.CenterCrop', (['(224)'], {}), '(224)\n', (776, 781), False, 'from torchvision import datasets, transforms, models, utils\n'), ((787, 808), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (806, 808), False, 'from torchvision import datasets, transforms, models, utils\n'), ((814, 880), 'torchvision.transforms.Normalize', 'transforms.Normalize', (['[0.485, 0.456, 0.406]', '[0.229, 0.224, 0.225]'], {}), '([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n', (834, 880), False, 'from torchvision import datasets, transforms, models, utils\n'), ((961, 983), 'torchvision.transforms.Resize', 'transforms.Resize', (['(255)'], {}), '(255)\n', (978, 983), False, 'from torchvision import datasets, transforms, models, utils\n'), ((993, 1019), 'torchvision.transforms.CenterCrop', 'transforms.CenterCrop', (['(224)'], {}), '(224)\n', (1014, 1019), False, 'from torchvision import datasets, transforms, models, utils\n'), ((1029, 1050), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (1048, 1050), False, 'from torchvision import datasets, transforms, models, utils\n'), ((1060, 1126), 'torchvision.transforms.Normalize', 'transforms.Normalize', (['[0.485, 0.456, 0.406]', '[0.229, 0.224, 0.225]'], {}), '([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n', (1080, 1126), False, 'from torchvision import datasets, transforms, models, utils\n'), ((5953, 5975), 'torchvision.transforms.Resize', 'transforms.Resize', (['(256)'], {}), '(256)\n', (5970, 5975), False, 'from torchvision import datasets, transforms, models, utils\n'), ((5985, 6011), 'torchvision.transforms.CenterCrop', 'transforms.CenterCrop', (['(224)'], {}), '(224)\n', (6006, 6011), False, 'from torchvision import datasets, transforms, models, utils\n'), ((6021, 6042), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (6040, 6042), False, 'from torchvision import datasets, transforms, models, utils\n'), ((6052, 6127), 'torchvision.transforms.Normalize', 'transforms.Normalize', ([], {'mean': '[0.485, 0.456, 0.406]', 'std': '[0.229, 0.224, 0.225]'}), '(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])\n', (6072, 6127), False, 'from torchvision import datasets, transforms, models, utils\n'), ((6376, 6401), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (6399, 6401), False, 'import torch\n'), ((6862, 6887), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (6885, 6887), False, 'import torch\n'), ((6991, 7012), 'numpy.array', 'np.array', (['top_classes'], {}), '(top_classes)\n', (6999, 7012), True, 'import numpy as np\n'), ((2191, 2216), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (2214, 2216), False, 'import torch\n'), ((3075, 3100), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (3098, 3100), False, 'import torch\n'), ((2496, 2543), 'torch.nn.Linear', 'nn.Linear', (['classifier_input_size', 'hidden_layers'], {}), '(classifier_input_size, hidden_layers)\n', (2505, 2543), False, 'from torch import nn, optim\n'), ((2563, 2572), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (2570, 2572), False, 'from torch import nn, optim\n'), ((2591, 2628), 'torch.nn.Linear', 'nn.Linear', (['hidden_layers', 'output_size'], {}), '(hidden_layers, output_size)\n', (2600, 2628), False, 'from torch import nn, optim\n'), ((2650, 2670), 'torch.nn.LogSoftmax', 'nn.LogSoftmax', ([], {'dim': '(1)'}), '(dim=1)\n', (2663, 2670), False, 'from torch import nn, optim\n'), ((3803, 3818), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (3816, 3818), False, 'import torch\n'), ((4200, 4216), 'torch.exp', 'torch.exp', (['logps'], {}), '(logps)\n', (4209, 4216), False, 'import torch\n')]
import numpy as np from UTILS.Calculus import Calculus from UTILS.Tools import Tools # Theoretical background https://arxiv.org/abs/1401.5176 # Mocak, Meakin, Viallet, Arnett, 2014, Compressible Hydrodynamic Mean-Field # # Equations in Spherical Geometry and their Application to Turbulent Stellar # # Convection Data # class TotalEnergyEquationCalculation(Calculus, Tools, object): def __init__(self, filename, ig, intc): super(TotalEnergyEquationCalculation, self).__init__(ig) # load data to structured array eht = self.customLoad(filename) # load grid xzn0 = self.getRAdata(eht, 'xzn0') nx = self.getRAdata(eht, 'nx') # pick equation-specific Reynolds-averaged mean fields according to: # https://github.com/mmicromegas/ransX/blob/master/DOCS/ransXimplementationGuide.pdf dd = self.getRAdata(eht, 'dd')[intc] ux = self.getRAdata(eht, 'ux')[intc] pp = self.getRAdata(eht, 'pp')[intc] ddux = self.getRAdata(eht, 'ddux')[intc] dduy = self.getRAdata(eht, 'dduy')[intc] dduz = self.getRAdata(eht, 'dduz')[intc] dduxux = self.getRAdata(eht, 'dduxux')[intc] dduyuy = self.getRAdata(eht, 'dduyuy')[intc] dduzuz = self.getRAdata(eht, 'dduzuz')[intc] dduxuy = self.getRAdata(eht, 'dduxuy')[intc] dduxuz = self.getRAdata(eht, 'dduxuz')[intc] ddekux = self.getRAdata(eht, 'ddekux')[intc] ddek = self.getRAdata(eht, 'ddek')[intc] ddei = self.getRAdata(eht, 'ddei')[intc] ddeiux = self.getRAdata(eht, 'ddeiux')[intc] divu = self.getRAdata(eht, 'divu')[intc] ppdivu = self.getRAdata(eht, 'ppdivu')[intc] ppux = self.getRAdata(eht, 'ppux')[intc] ddenuc1 = self.getRAdata(eht, 'ddenuc1')[intc] ddenuc2 = self.getRAdata(eht, 'ddenuc2')[intc] ####################### # TOTAL ENERGY EQUATION ####################### # store time series for time derivatives t_timec = self.getRAdata(eht, 'timec') t_dd = self.getRAdata(eht, 'dd') t_ddei = self.getRAdata(eht, 'ddei') t_ddux = self.getRAdata(eht, 'ddux') t_dduy = self.getRAdata(eht, 'dduy') t_dduz = self.getRAdata(eht, 'dduz') t_dduxux = self.getRAdata(eht, 'dduxux') t_dduyuy = self.getRAdata(eht, 'dduyuy') t_dduzuz = self.getRAdata(eht, 'dduzuz') t_uxux = self.getRAdata(eht, 'uxux') t_uyuy = self.getRAdata(eht, 'uyuy') t_uzuz = self.getRAdata(eht, 'uzuz') t_fht_ek = 0.5 * (t_dduxux + t_dduyuy + t_dduzuz) / t_dd t_fht_ei = t_ddei / t_dd # construct equation-specific mean fields # fht_ek = 0.5*(dduxux + dduyuy + dduzuz)/dd fht_ek = ddek / dd fht_ux = ddux / dd fht_ei = ddei / dd fei = ddeiux - ddux * ddei / dd fekx = ddekux - fht_ux * fht_ek fpx = ppux - pp * ux # LHS -dq/dt self.minus_dt_eht_dd_fht_ek = -self.dt(t_dd * t_fht_ek, xzn0, t_timec, intc) self.minus_dt_eht_dd_fht_ei = -self.dt(t_dd * t_fht_ei, xzn0, t_timec, intc) self.minus_dt_eht_dd_fht_et = self.minus_dt_eht_dd_fht_ek + \ self.minus_dt_eht_dd_fht_ei # LHS -div dd ux te self.minus_div_eht_dd_fht_ux_fht_ek = -self.Div(dd * fht_ux * fht_ek, xzn0) self.minus_div_eht_dd_fht_ux_fht_ei = -self.Div(dd * fht_ux * fht_ei, xzn0) self.minus_div_eht_dd_fht_ux_fht_et = self.minus_div_eht_dd_fht_ux_fht_ek + \ self.minus_div_eht_dd_fht_ux_fht_ei # RHS -div fei self.minus_div_fei = -self.Div(fei, xzn0) # RHS -div ftt (not included) heat flux self.minus_div_ftt = -np.zeros(nx) # -div kinetic energy flux self.minus_div_fekx = -self.Div(fekx, xzn0) # -div acoustic flux self.minus_div_fpx = -self.Div(fpx, xzn0) # RHS warning ax = overline{+u''_x} self.plus_ax = -ux + fht_ux # +buoyancy work self.plus_wb = self.plus_ax * self.Grad(pp, xzn0) # RHS -P d = - eht_pp Div eht_ux self.minus_pp_div_ux = -pp * self.Div(ux, xzn0) # -R grad u rxx = dduxux - ddux * ddux / dd rxy = dduxuy - ddux * dduy / dd rxz = dduxuz - ddux * dduz / dd self.minus_r_grad_u = -(rxx * self.Grad(ddux / dd, xzn0) + \ rxy * self.Grad(dduy / dd, xzn0) + \ rxz * self.Grad(dduz / dd, xzn0)) # +dd Dt fht_ui_fht_ui_o_two t_fht_ux = t_ddux / t_dd t_fht_uy = t_dduy / t_dd t_fht_uz = t_dduz / t_dd fht_ux = ddux / dd fht_uy = dduy / dd fht_uz = dduz / dd self.plus_dd_Dt_fht_ui_fht_ui_o_two = \ +self.dt(t_dd * (t_fht_ux ** 2. + t_fht_uy ** 2. + t_fht_uz ** 2.), xzn0, t_timec, intc) - \ self.Div(dd * fht_ux * (fht_ux ** 2. + fht_uy ** 2. + fht_uz ** 2.), xzn0) / 2. # RHS source + dd enuc self.plus_dd_fht_enuc = ddenuc1 + ddenuc2 # -res self.minus_resTeEquation = - (self.minus_dt_eht_dd_fht_et + self.minus_div_eht_dd_fht_ux_fht_et + self.minus_div_fei + self.minus_div_ftt + self.minus_div_fekx + self.minus_div_fpx + self.minus_r_grad_u + self.minus_pp_div_ux + self.plus_wb + self.plus_dd_fht_enuc + self.plus_dd_Dt_fht_ui_fht_ui_o_two) ########################### # END TOTAL ENERGY EQUATION ########################### def getTotalEnergyEquationField(self): # return fields field = {'minus_resTeEquation': self.minus_resTeEquation} return {'minus_resTeEquation': field['minus_resTeEquation']}
[ "numpy.zeros" ]
[((3812, 3824), 'numpy.zeros', 'np.zeros', (['nx'], {}), '(nx)\n', (3820, 3824), True, 'import numpy as np\n')]
#!/usr/bin/env python3 """ File name: viewnet.py Author: <NAME> email: <EMAIL> Date created: 02/09/2017 (DD/MM/YYYY) Python Version: 3.5 Description: Module used for visualization of the network systems generated using netsim.py """ import argparse, os, time,traceback,sys import numpy as np import pandas as pd import matplotlib import matplotlib.pyplot as plt from matplotlib.collections import LineCollection import matplotlib.patches as patches import matplotlib.tri as tri from mpl_toolkits.axes_grid1.inset_locator import inset_axes import networkx as nx from netsim import RandomConductingNetwork ,RandomCNTNetwork def open_data(path): df=pd.read_csv(path) for device in df.seed.drop_duplicates(): if len(df[df.seed==device])==1: pass else: for gatetype in ['back','partial','total']: try: singlechipmask=(df.seed==device)&(df.gate==gatetype) on=df.loc[singlechipmask&(df.gatevoltage==-10),'current'].values[0] off=df.loc[singlechipmask&(df.gatevoltage==10),'current'].values[0] df.loc[singlechipmask,'onoff']=on/off except: print ("ERROR calculating onoff for device seed : {}".format(device)) df['relative_maxclust']=df.maxclust/df.sticks df['logonoff']=np.log10(df.onoff) df = df[['seed', 'sticks', 'scaling', 'density', 'current', 'gatevoltage', 'gate', 'onoff','logonoff', 'nclust', 'maxclust', 'relative_maxclust', 'fname', 'onoffmap', 'runtime', 'element']] return df class CNTNetviewer(RandomCNTNetwork): def __init__(self,**kwargs): super(CNTNetviewer, self).__init__(**kwargs) self.label_clusters() # from percolation def show_system(self,clustering=True, junctions=True, conduction=True, show=True, save=False,figsize=(6.3,4)): fig, axes = plt.subplots(nrows=2,ncols=3,figsize=figsize, sharex=True, sharey=True, gridspec_kw={'wspace':0.1, 'hspace':0.05}) axes=axes.flat self.label_clusters() if clustering: self.show_sticks(ax=axes[0],junctions=False, clusters=True) axes[0].set_title("Sticks") if junctions: self.show_sticks(ax=axes[3],junctions=True, clusters=False) # axes[3].set_title("ms labeling and junctions") try: if conduction and self.percolating: self.plot_voltages(axes[1]) self.plot_regions(axes[1]) self.plot_currents(axes[2]) self.plot_regions(axes[2]) axes[1].set_title("Voltage") axes[2].set_title("Current") self.plot_contour('voltage',ax=axes[4]) self.plot_contour('current',ax=axes[5]) except Exception as e: print(e) pass for ax in axes: ax.tick_params(axis='both',direction='in',right=True, top =True) for ax in [axes[0],axes[3]]: ax.set_yticks([0,0.2,0.4,0.6,0.8,1]) ax.set_yticklabels(['{:.0f}'.format(i/5*self.scaling) for i in range(6)]) ax.set_ylabel("$\mu m$") for ax in [axes[3],axes[4],axes[5]]: ax.set_xticks([0,0.2,0.4,0.6,0.8,1]) ax.set_xticklabels(['{:.0f}'.format(i/5*self.scaling) for i in range(6)]) ax.set_xlabel("$\mu m$") plt.tight_layout() if save: print("saving system at {}".format(self.fname)) plt.savefig(self.fname+'_plots.png') plt.savefig(self.fname+'_plots.pdf') if show: plt.show() return fig, axes def show_sticks(self,ax=False, clusters=False, junctions=True): sticks=self.sticks intersects=self.intersects if not(ax): fig = plt.figure(figsize=(5,5),facecolor='white') ax=fig.add_subplot(111) if clusters: colors=np.append([[0,0,0]], np.random.rand(len(sticks),3), axis=0) stick_colors=[colors[i] for i in sticks.cluster.values] else: stick_cmap={'s':'b','m':'r','v':'k'} stick_colors=[stick_cmap[i] for i in sticks.kind] collection=LineCollection(sticks.endarray.values,linewidth=0.5,colors=stick_colors) ax.add_collection(collection) if junctions: isect_cmap={'ms':'g','sm':'g', 'mm':'None','ss':'None','vs':'None','sv':' ','vm':'None','mv':'None'} isect_colors=[isect_cmap[i] for i in self.intersects.kind] ax.scatter(intersects.x, intersects.y, edgecolors=isect_colors, facecolors='None', s=20, linewidth=1, marker="o",alpha=0.8) ax.set_xlim((-0.02,1.02)) ax.set_ylim((-0.02,1.02)) if not(ax): plt.show() pass # from network def show_cnet(self,ax=False,v=False, current = True, voltage=True): if not(ax): fig = plt.figure(figsize=(5,5),facecolor='white') ax=plt.subplot(111) self.plot_cnet(ax,v=v, current = current, voltage=voltage) if not(ax): plt.show() pass def show_device(self,v=False,ax=False,current = True, voltage=True,legend=False): if not(ax): fig = plt.figure(figsize=(5,5),facecolor='white') ax=plt.subplot(111) self.plot_cnet(ax,v=v, current = current, voltage=voltage) self.plot_regions(ax) if legend: ax.legend() if not(ax): plt.show() pass def plot_regions(self,ax): for a in self.cnet.gate_areas: ax.add_patch(patches.Rectangle( (a[0][0]-a[0][2]/2,a[0][1]-a[0][3]/2), a[0][2],a[0][3], edgecolor='b', fill=False, label="Local $V_G$ = {} V".format(a[1]))) ax.add_patch(patches.Rectangle( (-0.02,.48), 0.04,0.04, edgecolor='r', fill=False,label="Source = {} V".format(self.cnet.vds))) ax.add_patch(patches.Rectangle( (.98,0.48), 0.04,0.04, edgecolor='k', fill=False, label="GND = 0 V")) pass def plot_cnet(self,ax1,v=False,current=True,voltage=True): pos={k:self.cnet.graph.nodes[k]['pos'] for k in self.cnet.graph.nodes} # for i in range(self.network_rows): # for j in range(self.network_columns): # pos[(i,j)]=j,i edges,currents = zip(*nx.get_edge_attributes(self.cnet.graph,'current').items()) nodes,voltages = zip(*nx.get_node_attributes(self.cnet.graph,'voltage').items()) if voltage: nodes=nx.draw_networkx_nodes(self.cnet.graph, pos, width=2,nodelist=nodes, node_color=voltages, cmap=plt.get_cmap('YlOrRd'), node_size=30, ax=ax1,edgecolors='k') else: nodes=nx.draw_networkx_nodes(self.cnet.graph, pos, width=2,nodelist=nodes, node_color='r', node_size=30, ax=ax1) if current: edges=nx.draw_networkx_edges(self.cnet.graph, pos, width=1, edgelist=edges, edge_color=currents, edge_cmap=plt.get_cmap('YlGn'), ax=ax1) else: edges=nx.draw_networkx_edges(self.cnet.graph, pos, width=2, edgelist=edges, edge_color='b', ax=ax1) if v: nodelabels=nx.get_node_attributes(self.graph,'voltage') nx.draw_networkx_labels(self.graph,pos,labels={k:'{}\n {:.1e}V'.format(k,nodelabels[k]) for k in nodelabels}) edgecurrents=nx.get_edge_attributes(self.graph,'current') edgeresistance=nx.get_edge_attributes(self.graph,'resistance') nx.draw_networkx_edge_labels(self.graph,pos, edge_labels={k:'{:.1e}A\n{:.1e}$\Omega$'.format(edgecurrents[k], edgeresistance[k]) for k in edgecurrents}) pass def plot_currents(self,ax1,v=False): pos={k:self.cnet.graph.nodes[k]['pos'] for k in self.cnet.graph.nodes} edges,currents = zip(*nx.get_edge_attributes(self.cnet.graph,'current').items()) nodes,voltages = zip(*nx.get_node_attributes(self.cnet.graph,'voltage').items()) edges=nx.draw_networkx_edges(self.cnet.graph, pos, width=2, edgelist=edges, edge_color=currents, edge_cmap=plt.get_cmap('YlOrRd'), ax=ax1) nodes=nx.draw_networkx_nodes(self.cnet.graph, pos, width=1,nodelist=nodes, node_color='k', node_size=1, ax=ax1) pass def plot_voltages(self,ax1,v=False): pos={k:self.cnet.graph.nodes[k]['pos'] for k in self.cnet.graph.nodes} edges,currents = zip(*nx.get_edge_attributes(self.cnet.graph,'current').items()) nodes,voltages = zip(*nx.get_node_attributes(self.cnet.graph,'voltage').items()) nodes=nx.draw_networkx_nodes(self.cnet.graph, pos, width=2,nodelist=nodes, node_color=voltages, cmap=plt.get_cmap('YlOrRd'), node_size=30, ax=ax1,edgecolors='k') edges=nx.draw_networkx_edges(self.cnet.graph, pos, width=0.5, edgelist=edges, edge_color='k', ax=ax1) pass def plot_contour(self,value,scale=True,ax=False,show=False,save=False,colormap="YlOrRd"): if value=='current': z=np.array(list(nx.get_edge_attributes(self.cnet.graph,value).values())) pos=np.array(list(nx.get_edge_attributes(self.cnet.graph,'pos').values())) label= 'I' if value=='voltage': z=np.array(list(nx.get_node_attributes(self.cnet.graph,value).values())) pos=np.array(list(nx.get_node_attributes(self.cnet.graph,'pos').values())) label= 'V' x=pos[:,0] y=pos[:,1] #creat grid values xi = np.linspace(0,1,100) yi = np.linspace(0,1,100) # Perform linear interpolation of the data (x,y) # on a grid defined by (xi,yi) triang = tri.Triangulation(x, y) interpolator = tri.LinearTriInterpolator(triang, z) Xi, Yi = np.meshgrid(xi, yi) zi = interpolator(Xi, Yi) if not(ax): fig, ax = plt.subplots(1,figsize=(6.3,6.3)) ax.set_title("{} gate = {:04.1f} V".format(self.gatetype,float(self.gatevoltage))) # ax.contour(xi, yi, zi, 14, linewidths=0.5, colors='k') cntr1 = ax.contourf(xi, yi, zi, 8, cmap=colormap,alpha=0.7) # if not(ax): # fig.colorbar(cntr1, ax=ax,label=value) # ax.plot(x, y, 'wo', ms=3) # ax.axis((0,1,0,1)) if save or show: ax.set_yticks([0,0.2,0.4,0.6,0.8,1]) ax.set_yticklabels(['{:.0f}'.format(i/5*self.scaling) for i in range(6)]) ax.set_xticks([0,0.2,0.4,0.6,0.8,1]) ax.set_xticklabels(['{:.0f}'.format(i/5*self.scaling) for i in range(6)]) ax.set_ylabel("$\mu m$") ax.set_xlabel("$\mu m$") if scale: axins = inset_axes(ax, width="40%", height="5%", loc=9, bbox_to_anchor=(0, 0, 1, 1), bbox_transform=ax.transAxes, borderpad=0) values=[0,zi.max()] cbar=plt.colorbar(cntr1, cax=axins,ticks=values,format='%.0e', orientation='horizontal') # cbar.set_ticks([cmin+(0.1*range),cmax-(0.1*range)]) cbar.set_ticklabels(["{:.1f}".format(values[0]),"{:.0e}".format(values[1])]) cbar.set_label(label,labelpad=-10) if show: plt.show() if ax and save: plt.tight_layout() plt.savefig("{}.png".format(save)) plt.savefig("{}.pdf".format(save)) plt.close() pass if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("-t", "--test", action="store_true") parser.add_argument('--fname',type=str,default='') args = parser.parse_args() if args.test: cond_network=RandomConductingNetwork(500) cond_network.save_system() netview=CNTNetviewer(fname=(os.path.basename(cond_network.fname))) netview.show_system()
[ "numpy.log10", "pandas.read_csv", "mpl_toolkits.axes_grid1.inset_locator.inset_axes", "matplotlib.tri.Triangulation", "matplotlib.collections.LineCollection", "networkx.draw_networkx_nodes", "networkx.draw_networkx_edges", "argparse.ArgumentParser", "networkx.get_edge_attributes", "netsim.RandomCo...
[((683, 700), 'pandas.read_csv', 'pd.read_csv', (['path'], {}), '(path)\n', (694, 700), True, 'import pandas as pd\n'), ((1384, 1402), 'numpy.log10', 'np.log10', (['df.onoff'], {}), '(df.onoff)\n', (1392, 1402), True, 'import numpy as np\n'), ((11384, 11409), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (11407, 11409), False, 'import argparse, os, time, traceback, sys\n'), ((1925, 2047), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'nrows': '(2)', 'ncols': '(3)', 'figsize': 'figsize', 'sharex': '(True)', 'sharey': '(True)', 'gridspec_kw': "{'wspace': 0.1, 'hspace': 0.05}"}), "(nrows=2, ncols=3, figsize=figsize, sharex=True, sharey=True,\n gridspec_kw={'wspace': 0.1, 'hspace': 0.05})\n", (1937, 2047), True, 'import matplotlib.pyplot as plt\n'), ((3425, 3443), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (3441, 3443), True, 'import matplotlib.pyplot as plt\n'), ((4245, 4319), 'matplotlib.collections.LineCollection', 'LineCollection', (['sticks.endarray.values'], {'linewidth': '(0.5)', 'colors': 'stick_colors'}), '(sticks.endarray.values, linewidth=0.5, colors=stick_colors)\n', (4259, 4319), False, 'from matplotlib.collections import LineCollection\n'), ((8137, 8247), 'networkx.draw_networkx_nodes', 'nx.draw_networkx_nodes', (['self.cnet.graph', 'pos'], {'width': '(1)', 'nodelist': 'nodes', 'node_color': '"""k"""', 'node_size': '(1)', 'ax': 'ax1'}), "(self.cnet.graph, pos, width=1, nodelist=nodes,\n node_color='k', node_size=1, ax=ax1)\n", (8159, 8247), True, 'import networkx as nx\n'), ((8744, 8843), 'networkx.draw_networkx_edges', 'nx.draw_networkx_edges', (['self.cnet.graph', 'pos'], {'width': '(0.5)', 'edgelist': 'edges', 'edge_color': '"""k"""', 'ax': 'ax1'}), "(self.cnet.graph, pos, width=0.5, edgelist=edges,\n edge_color='k', ax=ax1)\n", (8766, 8843), True, 'import networkx as nx\n'), ((9476, 9498), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', '(100)'], {}), '(0, 1, 100)\n', (9487, 9498), True, 'import numpy as np\n'), ((9510, 9532), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', '(100)'], {}), '(0, 1, 100)\n', (9521, 9532), True, 'import numpy as np\n'), ((9645, 9668), 'matplotlib.tri.Triangulation', 'tri.Triangulation', (['x', 'y'], {}), '(x, y)\n', (9662, 9668), True, 'import matplotlib.tri as tri\n'), ((9692, 9728), 'matplotlib.tri.LinearTriInterpolator', 'tri.LinearTriInterpolator', (['triang', 'z'], {}), '(triang, z)\n', (9717, 9728), True, 'import matplotlib.tri as tri\n'), ((9746, 9765), 'numpy.meshgrid', 'np.meshgrid', (['xi', 'yi'], {}), '(xi, yi)\n', (9757, 9765), True, 'import numpy as np\n'), ((11597, 11625), 'netsim.RandomConductingNetwork', 'RandomConductingNetwork', (['(500)'], {}), '(500)\n', (11620, 11625), False, 'from netsim import RandomConductingNetwork, RandomCNTNetwork\n'), ((3533, 3571), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(self.fname + '_plots.png')"], {}), "(self.fname + '_plots.png')\n", (3544, 3571), True, 'import matplotlib.pyplot as plt\n'), ((3582, 3620), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(self.fname + '_plots.pdf')"], {}), "(self.fname + '_plots.pdf')\n", (3593, 3620), True, 'import matplotlib.pyplot as plt\n'), ((3648, 3658), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3656, 3658), True, 'import matplotlib.pyplot as plt\n'), ((3853, 3898), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(5, 5)', 'facecolor': '"""white"""'}), "(figsize=(5, 5), facecolor='white')\n", (3863, 3898), True, 'import matplotlib.pyplot as plt\n'), ((4798, 4808), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4806, 4808), True, 'import matplotlib.pyplot as plt\n'), ((4952, 4997), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(5, 5)', 'facecolor': '"""white"""'}), "(figsize=(5, 5), facecolor='white')\n", (4962, 4997), True, 'import matplotlib.pyplot as plt\n'), ((5011, 5027), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(111)'], {}), '(111)\n', (5022, 5027), True, 'import matplotlib.pyplot as plt\n'), ((5127, 5137), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (5135, 5137), True, 'import matplotlib.pyplot as plt\n'), ((5276, 5321), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(5, 5)', 'facecolor': '"""white"""'}), "(figsize=(5, 5), facecolor='white')\n", (5286, 5321), True, 'import matplotlib.pyplot as plt\n'), ((5335, 5351), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(111)'], {}), '(111)\n', (5346, 5351), True, 'import matplotlib.pyplot as plt\n'), ((5524, 5534), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (5532, 5534), True, 'import matplotlib.pyplot as plt\n'), ((5945, 6038), 'matplotlib.patches.Rectangle', 'patches.Rectangle', (['(0.98, 0.48)', '(0.04)', '(0.04)'], {'edgecolor': '"""k"""', 'fill': '(False)', 'label': '"""GND = 0 V"""'}), "((0.98, 0.48), 0.04, 0.04, edgecolor='k', fill=False,\n label='GND = 0 V')\n", (5962, 6038), True, 'import matplotlib.patches as patches\n'), ((6734, 6845), 'networkx.draw_networkx_nodes', 'nx.draw_networkx_nodes', (['self.cnet.graph', 'pos'], {'width': '(2)', 'nodelist': 'nodes', 'node_color': '"""r"""', 'node_size': '(30)', 'ax': 'ax1'}), "(self.cnet.graph, pos, width=2, nodelist=nodes,\n node_color='r', node_size=30, ax=ax1)\n", (6756, 6845), True, 'import networkx as nx\n'), ((7044, 7141), 'networkx.draw_networkx_edges', 'nx.draw_networkx_edges', (['self.cnet.graph', 'pos'], {'width': '(2)', 'edgelist': 'edges', 'edge_color': '"""b"""', 'ax': 'ax1'}), "(self.cnet.graph, pos, width=2, edgelist=edges,\n edge_color='b', ax=ax1)\n", (7066, 7141), True, 'import networkx as nx\n'), ((7176, 7221), 'networkx.get_node_attributes', 'nx.get_node_attributes', (['self.graph', '"""voltage"""'], {}), "(self.graph, 'voltage')\n", (7198, 7221), True, 'import networkx as nx\n'), ((7374, 7419), 'networkx.get_edge_attributes', 'nx.get_edge_attributes', (['self.graph', '"""current"""'], {}), "(self.graph, 'current')\n", (7396, 7419), True, 'import networkx as nx\n'), ((7446, 7494), 'networkx.get_edge_attributes', 'nx.get_edge_attributes', (['self.graph', '"""resistance"""'], {}), "(self.graph, 'resistance')\n", (7468, 7494), True, 'import networkx as nx\n'), ((9843, 9878), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)'], {'figsize': '(6.3, 6.3)'}), '(1, figsize=(6.3, 6.3))\n', (9855, 9878), True, 'import matplotlib.pyplot as plt\n'), ((10662, 10784), 'mpl_toolkits.axes_grid1.inset_locator.inset_axes', 'inset_axes', (['ax'], {'width': '"""40%"""', 'height': '"""5%"""', 'loc': '(9)', 'bbox_to_anchor': '(0, 0, 1, 1)', 'bbox_transform': 'ax.transAxes', 'borderpad': '(0)'}), "(ax, width='40%', height='5%', loc=9, bbox_to_anchor=(0, 0, 1, 1),\n bbox_transform=ax.transAxes, borderpad=0)\n", (10672, 10784), False, 'from mpl_toolkits.axes_grid1.inset_locator import inset_axes\n'), ((10831, 10921), 'matplotlib.pyplot.colorbar', 'plt.colorbar', (['cntr1'], {'cax': 'axins', 'ticks': 'values', 'format': '"""%.0e"""', 'orientation': '"""horizontal"""'}), "(cntr1, cax=axins, ticks=values, format='%.0e', orientation=\n 'horizontal')\n", (10843, 10921), True, 'import matplotlib.pyplot as plt\n'), ((11146, 11156), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (11154, 11156), True, 'import matplotlib.pyplot as plt\n'), ((11193, 11211), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (11209, 11211), True, 'import matplotlib.pyplot as plt\n'), ((11318, 11329), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (11327, 11329), True, 'import matplotlib.pyplot as plt\n'), ((8090, 8112), 'matplotlib.pyplot.get_cmap', 'plt.get_cmap', (['"""YlOrRd"""'], {}), "('YlOrRd')\n", (8102, 8112), True, 'import matplotlib.pyplot as plt\n'), ((8668, 8690), 'matplotlib.pyplot.get_cmap', 'plt.get_cmap', (['"""YlOrRd"""'], {}), "('YlOrRd')\n", (8680, 8690), True, 'import matplotlib.pyplot as plt\n'), ((11697, 11733), 'os.path.basename', 'os.path.basename', (['cond_network.fname'], {}), '(cond_network.fname)\n', (11713, 11733), False, 'import argparse, os, time, traceback, sys\n'), ((6641, 6663), 'matplotlib.pyplot.get_cmap', 'plt.get_cmap', (['"""YlOrRd"""'], {}), "('YlOrRd')\n", (6653, 6663), True, 'import matplotlib.pyplot as plt\n'), ((6982, 7002), 'matplotlib.pyplot.get_cmap', 'plt.get_cmap', (['"""YlGn"""'], {}), "('YlGn')\n", (6994, 7002), True, 'import matplotlib.pyplot as plt\n'), ((6358, 6408), 'networkx.get_edge_attributes', 'nx.get_edge_attributes', (['self.cnet.graph', '"""current"""'], {}), "(self.cnet.graph, 'current')\n", (6380, 6408), True, 'import networkx as nx\n'), ((6448, 6498), 'networkx.get_node_attributes', 'nx.get_node_attributes', (['self.cnet.graph', '"""voltage"""'], {}), "(self.cnet.graph, 'voltage')\n", (6470, 6498), True, 'import networkx as nx\n'), ((7824, 7874), 'networkx.get_edge_attributes', 'nx.get_edge_attributes', (['self.cnet.graph', '"""current"""'], {}), "(self.cnet.graph, 'current')\n", (7846, 7874), True, 'import networkx as nx\n'), ((7914, 7964), 'networkx.get_node_attributes', 'nx.get_node_attributes', (['self.cnet.graph', '"""voltage"""'], {}), "(self.cnet.graph, 'voltage')\n", (7936, 7964), True, 'import networkx as nx\n'), ((8408, 8458), 'networkx.get_edge_attributes', 'nx.get_edge_attributes', (['self.cnet.graph', '"""current"""'], {}), "(self.cnet.graph, 'current')\n", (8430, 8458), True, 'import networkx as nx\n'), ((8498, 8548), 'networkx.get_node_attributes', 'nx.get_node_attributes', (['self.cnet.graph', '"""voltage"""'], {}), "(self.cnet.graph, 'voltage')\n", (8520, 8548), True, 'import networkx as nx\n'), ((9005, 9051), 'networkx.get_edge_attributes', 'nx.get_edge_attributes', (['self.cnet.graph', 'value'], {}), '(self.cnet.graph, value)\n', (9027, 9051), True, 'import networkx as nx\n'), ((9092, 9138), 'networkx.get_edge_attributes', 'nx.get_edge_attributes', (['self.cnet.graph', '"""pos"""'], {}), "(self.cnet.graph, 'pos')\n", (9114, 9138), True, 'import networkx as nx\n'), ((9229, 9275), 'networkx.get_node_attributes', 'nx.get_node_attributes', (['self.cnet.graph', 'value'], {}), '(self.cnet.graph, value)\n', (9251, 9275), True, 'import networkx as nx\n'), ((9316, 9362), 'networkx.get_node_attributes', 'nx.get_node_attributes', (['self.cnet.graph', '"""pos"""'], {}), "(self.cnet.graph, 'pos')\n", (9338, 9362), True, 'import networkx as nx\n')]
from dataclasses import dataclass from collections import defaultdict from functools import lru_cache from typing import Dict, List import json import warnings from scipy.spatial import distance as spd from torch.distributions.categorical import Categorical from tqdm import tqdm import joblib import langdetect import numpy as np import torch import yaml from multiprobe.utils import jsd_, chunk class LanguageFamilyData(object): def __init__(self, family_map): self.family_map = family_map self.code_family_map = defaultdict(lambda: 'none') for family, languages in family_map.items(): for lang, data in languages.items(): self.code_family_map[data['code']] = family @property def families(self): return list(self.family_map.keys()) def find_family(self, lang_code): return self.code_family_map[lang_code] @classmethod def from_yaml(cls, filename): with open(filename) as f: family_map = yaml.load(f) return cls(family_map) def safe_js(p, q): js_dist = spd.jensenshannon(p, q, 2.0) # SciPy has numerical issues if np.isnan(js_dist): js_dist = 0 return js_dist def sum_js(p_list, q_list, verbose=True): with warnings.catch_warnings(): warnings.filterwarnings('ignore') return sum(safe_js(p, q) for p, q in zip(p_list, q_list)) def sum_js_cuda(p_list, q_list): dist = 0 for p, q in tqdm(zip(p_list, q_list), position=1): js_dist = jsd_(torch.Tensor(p).cuda(), torch.Tensor(q).cuda()).cpu().item() dist += js_dist return dist @dataclass class TokenLanguageStatistics(object): data: Dict[str, Dict[str, int]] vocab: Dict[str, int] languages: List[str] @classmethod def from_file(cls, path): with open(path) as f: data = json.load(f) languages = sorted(data['languages']) return cls(data['statistics'], data['vocab'], languages) def compute_distribution(self, tokens, weights=None): probs = [] new_weights = [] for token, weight in zip(tokens, weights): token_probs = np.zeros(len(self.languages)) if token not in self.data: continue for language, count in self.data[token].items(): token_probs[self.languages.index(language)] += count if np.sum(token_probs) > 0: token_probs = token_probs / np.sum(token_probs) probs.append(token_probs) new_weights.append(weight) if len(probs) == 0: raise ValueError('No counts found for those tokens.') if weights is None: probs = np.mean(np.array(probs), 0) else: weights = np.array(new_weights) probs = np.array(probs) probs = np.sum(np.repeat(np.expand_dims(weights, 1), probs.shape[1], 1) * probs, 0) / np.sum(weights) return Categorical(probs=torch.Tensor(probs)) @lru_cache(maxsize=1000000) def detect_language(string): return langdetect.detect(string)
[ "warnings.catch_warnings", "yaml.load", "torch.Tensor", "langdetect.detect", "numpy.array", "numpy.sum", "collections.defaultdict", "numpy.isnan", "numpy.expand_dims", "json.load", "functools.lru_cache", "warnings.filterwarnings", "scipy.spatial.distance.jensenshannon" ]
[((3019, 3045), 'functools.lru_cache', 'lru_cache', ([], {'maxsize': '(1000000)'}), '(maxsize=1000000)\n', (3028, 3045), False, 'from functools import lru_cache\n'), ((1089, 1117), 'scipy.spatial.distance.jensenshannon', 'spd.jensenshannon', (['p', 'q', '(2.0)'], {}), '(p, q, 2.0)\n', (1106, 1117), True, 'from scipy.spatial import distance as spd\n'), ((1158, 1175), 'numpy.isnan', 'np.isnan', (['js_dist'], {}), '(js_dist)\n', (1166, 1175), True, 'import numpy as np\n'), ((3086, 3111), 'langdetect.detect', 'langdetect.detect', (['string'], {}), '(string)\n', (3103, 3111), False, 'import langdetect\n'), ((540, 568), 'collections.defaultdict', 'defaultdict', (["(lambda : 'none')"], {}), "(lambda : 'none')\n", (551, 568), False, 'from collections import defaultdict\n'), ((1269, 1294), 'warnings.catch_warnings', 'warnings.catch_warnings', ([], {}), '()\n', (1292, 1294), False, 'import warnings\n'), ((1304, 1337), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (1327, 1337), False, 'import warnings\n'), ((1010, 1022), 'yaml.load', 'yaml.load', (['f'], {}), '(f)\n', (1019, 1022), False, 'import yaml\n'), ((1867, 1879), 'json.load', 'json.load', (['f'], {}), '(f)\n', (1876, 1879), False, 'import json\n'), ((2790, 2811), 'numpy.array', 'np.array', (['new_weights'], {}), '(new_weights)\n', (2798, 2811), True, 'import numpy as np\n'), ((2832, 2847), 'numpy.array', 'np.array', (['probs'], {}), '(probs)\n', (2840, 2847), True, 'import numpy as np\n'), ((2410, 2429), 'numpy.sum', 'np.sum', (['token_probs'], {}), '(token_probs)\n', (2416, 2429), True, 'import numpy as np\n'), ((2734, 2749), 'numpy.array', 'np.array', (['probs'], {}), '(probs)\n', (2742, 2749), True, 'import numpy as np\n'), ((2946, 2961), 'numpy.sum', 'np.sum', (['weights'], {}), '(weights)\n', (2952, 2961), True, 'import numpy as np\n'), ((2995, 3014), 'torch.Tensor', 'torch.Tensor', (['probs'], {}), '(probs)\n', (3007, 3014), False, 'import torch\n'), ((2479, 2498), 'numpy.sum', 'np.sum', (['token_probs'], {}), '(token_probs)\n', (2485, 2498), True, 'import numpy as np\n'), ((2885, 2911), 'numpy.expand_dims', 'np.expand_dims', (['weights', '(1)'], {}), '(weights, 1)\n', (2899, 2911), True, 'import numpy as np\n'), ((1530, 1545), 'torch.Tensor', 'torch.Tensor', (['p'], {}), '(p)\n', (1542, 1545), False, 'import torch\n'), ((1554, 1569), 'torch.Tensor', 'torch.Tensor', (['q'], {}), '(q)\n', (1566, 1569), False, 'import torch\n')]
import datetime import math import operator import sqlite3 import uuid import numpy as np import pandas as pd import pandas.testing as tm import pytest from packaging.version import parse import ibis import ibis.expr.datatypes as dt from ibis import config from ibis import literal as L sa = pytest.importorskip("sqlalchemy") @pytest.mark.parametrize( ('func', 'expected'), [ ( lambda t: t.double_col.cast(dt.int8), lambda at: sa.cast(at.c.double_col, sa.SMALLINT), ), ( lambda t: t.string_col.cast(dt.double), lambda at: sa.cast(at.c.string_col, sa.REAL), ), ( lambda t: t.string_col.cast(dt.float), lambda at: sa.cast(at.c.string_col, sa.REAL), ), ], ) def test_cast(alltypes, alltypes_sqla, translate, func, expected): assert translate(func(alltypes)) == str(expected(alltypes_sqla)) @pytest.mark.parametrize( ('func', 'expected_func'), [ ( lambda t: t.timestamp_col.cast(dt.timestamp), lambda at: sa.func.strftime( '%Y-%m-%d %H:%M:%f', at.c.timestamp_col ), ), ( lambda t: t.int_col.cast(dt.timestamp), lambda at: sa.func.datetime(at.c.int_col, 'unixepoch'), ), ], ) def test_timestamp_cast_noop( alltypes, func, translate, alltypes_sqla, expected_func, sqla_compile ): # See GH #592 result = func(alltypes) expected = expected_func(alltypes_sqla) assert translate(result) == sqla_compile(expected) TIMESTAMP_CONSTANT = ibis.literal('2015-09-01 14:48:05.359').cast('timestamp') @pytest.mark.parametrize( ('expr', 'expected'), [ (TIMESTAMP_CONSTANT.strftime('%Y%m%d'), '20150901'), (TIMESTAMP_CONSTANT.year(), 2015), (TIMESTAMP_CONSTANT.month(), 9), (TIMESTAMP_CONSTANT.day(), 1), (TIMESTAMP_CONSTANT.hour(), 14), (TIMESTAMP_CONSTANT.minute(), 48), (TIMESTAMP_CONSTANT.second(), 5), (TIMESTAMP_CONSTANT.millisecond(), 359), ], ) def test_timestamp_functions(con, expr, expected): assert con.execute(expr) == expected def test_now(con): expr = ibis.now().strftime('%Y%m%d %H') result = con.execute(expr) expected = datetime.datetime.utcnow().strftime('%Y%m%d %H') assert result == expected @pytest.mark.parametrize( ('expr', 'expected'), [ (L(3) + L(4), 7), (L(3) - L(4), -1), (L(3) * L(4), 12), (L(12) / L(4), 3), (L(12) ** L(2), 144), (L(12) % L(5), 2), ], ) def test_binary_arithmetic(con, expr, expected): assert con.execute(expr) == expected @pytest.mark.parametrize( ('expr', 'expected'), [ (L(7) / L(2), 3.5), (L(7) // L(2), 3), (L(7).floordiv(2), 3), (L(2).rfloordiv(7), 3), ], ) def test_div_floordiv(con, expr, expected): assert con.execute(expr) == expected @pytest.mark.parametrize( ('expr', 'expected'), [ (L('foo_bar').typeof(), 'text'), (L(5).typeof(), 'integer'), (ibis.NA.typeof(), 'null'), (L(1.2345).typeof(), 'real'), ], ) def test_typeof(con, expr, expected): assert con.execute(expr) == expected @pytest.mark.parametrize( ('expr', 'expected'), [(L(0).nullifzero(), None), (L(5.5).nullifzero(), 5.5)], ) def test_nullifzero(con, expr, expected): assert con.execute(expr) == expected @pytest.mark.parametrize( ('expr', 'expected'), [(L('foo_bar').length(), 7), (L('').length(), 0)] ) def test_string_length(con, expr, expected): assert con.execute(expr) == expected @pytest.mark.parametrize( ('expr', 'expected'), [ (L('foo_bar').left(3), 'foo'), (L('foo_bar').right(3), 'bar'), (L('foo_bar').substr(0, 3), 'foo'), (L('foo_bar').substr(4, 3), 'bar'), (L('foo_bar').substr(1), 'oo_bar'), ], ) def test_string_substring(con, expr, expected): assert con.execute(expr) == expected @pytest.mark.parametrize( ('expr', 'expected'), [ (L(' foo ').lstrip(), 'foo '), (L(' foo ').rstrip(), ' foo'), (L(' foo ').strip(), 'foo'), ], ) def test_string_strip(con, expr, expected): assert con.execute(expr) == expected @pytest.mark.parametrize( ('expr', 'expected'), [(L('foo').upper(), 'FOO'), (L('FOO').lower(), 'foo')], ) def test_string_upper_lower(con, expr, expected): assert con.execute(expr) == expected @pytest.mark.parametrize( ('expr', 'expected'), [ (L('foobar').contains('bar'), True), (L('foobar').contains('foo'), True), (L('foobar').contains('baz'), False), ], ) def test_string_contains(con, expr, expected): assert con.execute(expr) == expected @pytest.mark.parametrize( ('expr', 'expected'), [(L('foobar').find('bar'), 3), (L('foobar').find('baz'), -1)], ) def test_string_find(con, expr, expected): assert con.execute(expr) == expected @pytest.mark.parametrize( ('expr', 'expected'), [ (L('foobar').like('%bar'), True), (L('foobar').like('foo%'), True), (L('foobar').like('%baz%'), False), (L('foobar').like(['%bar']), True), (L('foobar').like(['foo%']), True), (L('foobar').like(['%baz%']), False), (L('foobar').like(['%bar', 'foo%']), True), ], ) def test_string_like(con, expr, expected): assert con.execute(expr) == expected def test_str_replace(con): expr = L('foobarfoo').replace('foo', 'H') expected = 'HbarH' assert con.execute(expr) == expected @pytest.mark.parametrize( ('expr', 'expected'), [ (L(-5).abs(), 5), (L(5).abs(), 5), (ibis.least(L(5), L(10), L(1)), 1), (ibis.greatest(L(5), L(10), L(1)), 10), (L(5.5).round(), 6.0), (L(5.556).round(2), 5.56), (L(5.556).sqrt(), math.sqrt(5.556)), (L(5.556).ceil(), 6.0), (L(5.556).floor(), 5.0), (L(5.556).exp(), math.exp(5.556)), (L(5.556).sign(), 1), (L(-5.556).sign(), -1), (L(0).sign(), 0), (L(5.556).log(2), math.log(5.556, 2)), (L(5.556).ln(), math.log(5.556)), (L(5.556).log2(), math.log(5.556, 2)), (L(5.556).log10(), math.log10(5.556)), ], ) def test_math_functions(con, expr, expected): assert con.execute(expr) == expected NULL_STRING = L(None).cast(dt.string) NULL_INT64 = L(None).cast(dt.int64) @pytest.mark.parametrize( ('expr', 'expected'), [ (L('abcd').re_search('[a-z]'), True), (L('abcd').re_search(r'[\d]+'), False), (L('1222').re_search(r'[\d]+'), True), (L('abcd').re_search(None), None), (NULL_STRING.re_search('[a-z]'), None), (NULL_STRING.re_search(NULL_STRING), None), ], ) def test_regexp_search(con, expr, expected): assert con.execute(expr) == expected @pytest.mark.parametrize( ('expr', 'expected'), [ (L('abcd').re_replace('[ab]', ''), 'cd'), (L(None).cast(dt.string).re_replace(NULL_STRING, NULL_STRING), None), (L('abcd').re_replace(NULL_STRING, NULL_STRING), None), (L('abcd').re_replace('a', NULL_STRING), None), (L('abcd').re_replace(NULL_STRING, 'a'), None), (NULL_STRING.re_replace('a', NULL_STRING), None), (NULL_STRING.re_replace(NULL_STRING, 'a'), None), ], ) def test_regexp_replace(con, expr, expected): assert con.execute(expr) == expected @pytest.mark.parametrize( ('expr', 'expected'), [ (L('1222').re_extract(r'1(22)\d+', 1).cast('int64'), 22), (L('abcd').re_extract(r'(\d+)', 1), None), (L('1222').re_extract('([a-z]+)', 1), None), (L('1222').re_extract(r'1(22)\d+', 2), None), # extract nulls (NULL_STRING.re_extract(NULL_STRING, NULL_INT64), None), (L('abcd').re_extract(NULL_STRING, NULL_INT64), None), (L('abcd').re_extract('a', NULL_INT64), None), (L('abcd').re_extract(NULL_STRING, 1), None), (NULL_STRING.re_extract('a', NULL_INT64), None), (NULL_STRING.re_extract(NULL_STRING, 1), None), ], ) def test_regexp_extract(con, expr, expected): assert con.execute(expr) == expected @pytest.mark.parametrize( ('expr', 'expected'), [ (ibis.NA.fillna(5), 5), (L(5).fillna(10), 5), (L(5).nullif(5), None), (L(10).nullif(5), 10), ], ) def test_fillna_nullif(con, expr, expected): assert con.execute(expr) == expected def test_numeric_builtins_work(alltypes, df): expr = alltypes.double_col.fillna(0) result = expr.execute() expected = df.double_col.fillna(0) expected.name = 'tmp' tm.assert_series_equal(result, expected) @pytest.mark.parametrize( ('func', 'expected_func'), [ ( lambda t: (t.double_col > 20).ifelse(10, -20), lambda df: pd.Series( np.where(df.double_col > 20, 10, -20), name='tmp', dtype='int8' ), ), ( lambda t: (t.double_col > 20).ifelse(10, -20).abs(), lambda df: pd.Series( np.where(df.double_col > 20, 10, -20), name='tmp', dtype='int8' ).abs(), ), ], ) def test_ifelse(alltypes, df, func, expected_func): result = func(alltypes).execute() expected = expected_func(df) tm.assert_series_equal(result, expected) @pytest.mark.parametrize( ('func', 'expected_func'), [ # tier and histogram ( lambda d: d.bucket([0, 10, 25, 50, 100]), lambda s: pd.cut( s, [0, 10, 25, 50, 100], right=False, labels=False ), ), ( lambda d: d.bucket([0, 10, 25, 50], include_over=True), lambda s: pd.cut( s, [0, 10, 25, 50, np.inf], right=False, labels=False ), ), ( lambda d: d.bucket([0, 10, 25, 50], close_extreme=False), lambda s: pd.cut(s, [0, 10, 25, 50], right=False, labels=False), ), ( lambda d: d.bucket( [0, 10, 25, 50], closed='right', close_extreme=False ), lambda s: pd.cut( s, [0, 10, 25, 50], include_lowest=False, right=True, labels=False, ), ), ( lambda d: d.bucket([10, 25, 50, 100], include_under=True), lambda s: pd.cut( s, [0, 10, 25, 50, 100], right=False, labels=False ), ), ], ) def test_bucket(alltypes, df, func, expected_func): expr = func(alltypes.double_col) result = expr.execute() expected = expected_func(df.double_col) expected = pd.Series(pd.Categorical(expected)) tm.assert_series_equal(result, expected, check_names=False) def test_category_label(alltypes, df): bins = [0, 10, 25, 50, 100] labels = ['a', 'b', 'c', 'd'] expr = alltypes.double_col.bucket(bins).label(labels) result = expr.execute() result = pd.Series(pd.Categorical(result, ordered=True)) result.name = 'double_col' expected = pd.cut(df.double_col, bins, labels=labels, right=False) tm.assert_series_equal(result, expected) @pytest.mark.xfail( parse(sqlite3.sqlite_version) < parse('3.8.3'), raises=sa.exc.OperationalError, reason='SQLite versions < 3.8.3 do not support the WITH statement', ) def test_union(alltypes): t = alltypes expr = ( t.group_by('string_col') .aggregate(t.double_col.sum().name('foo')) .sort_by('string_col') ) t1 = expr.limit(4) t2 = expr.limit(4, offset=4) t3 = expr.limit(8) result = t1.union(t2).execute() expected = t3.execute() assert (result.string_col == expected.string_col).all() @pytest.mark.parametrize( ('func', 'expected_func'), [ ( lambda t, cond: t.bool_col.count(), lambda df, cond: df.bool_col.count(), ), (lambda t, cond: t.bool_col.any(), lambda df, cond: df.bool_col.any()), (lambda t, cond: t.bool_col.all(), lambda df, cond: df.bool_col.all()), ( lambda t, cond: t.bool_col.notany(), lambda df, cond: ~df.bool_col.any(), ), ( lambda t, cond: t.bool_col.notall(), lambda df, cond: ~df.bool_col.all(), ), ( lambda t, cond: t.double_col.sum(), lambda df, cond: df.double_col.sum(), ), ( lambda t, cond: t.double_col.mean(), lambda df, cond: df.double_col.mean(), ), ( lambda t, cond: t.double_col.min(), lambda df, cond: df.double_col.min(), ), ( lambda t, cond: t.double_col.max(), lambda df, cond: df.double_col.max(), ), ( lambda t, cond: t.double_col.var(), lambda df, cond: df.double_col.var(), ), ( lambda t, cond: t.double_col.std(), lambda df, cond: df.double_col.std(), ), ( lambda t, cond: t.double_col.var(how='sample'), lambda df, cond: df.double_col.var(ddof=1), ), ( lambda t, cond: t.double_col.std(how='pop'), lambda df, cond: df.double_col.std(ddof=0), ), ( lambda t, cond: t.bool_col.count(where=cond), lambda df, cond: df.bool_col[cond].count(), ), ( lambda t, cond: t.double_col.sum(where=cond), lambda df, cond: df.double_col[cond].sum(), ), ( lambda t, cond: t.double_col.mean(where=cond), lambda df, cond: df.double_col[cond].mean(), ), ( lambda t, cond: t.double_col.min(where=cond), lambda df, cond: df.double_col[cond].min(), ), ( lambda t, cond: t.double_col.max(where=cond), lambda df, cond: df.double_col[cond].max(), ), ( lambda t, cond: t.double_col.var(where=cond), lambda df, cond: df.double_col[cond].var(), ), ( lambda t, cond: t.double_col.std(where=cond), lambda df, cond: df.double_col[cond].std(), ), ( lambda t, cond: t.double_col.var(where=cond, how='sample'), lambda df, cond: df.double_col[cond].var(), ), ( lambda t, cond: t.double_col.std(where=cond, how='pop'), lambda df, cond: df.double_col[cond].std(ddof=0), ), ], ) def test_aggregations_execute(alltypes, func, df, expected_func): cond = alltypes.string_col.isin(['1', '7']) expr = func(alltypes, cond) result = expr.execute() expected = expected_func(df, df.string_col.isin(['1', '7'])) np.testing.assert_allclose(result, expected) def test_not_contains(alltypes, df): n = 100 table = alltypes.limit(n) expr = table.string_col.notin(['1', '7']) result = expr.execute() expected = ~df.head(n).string_col.isin(['1', '7']) tm.assert_series_equal(result, expected, check_names=False) def test_distinct_aggregates(alltypes, df): expr = alltypes.double_col.nunique() result = expr.execute() expected = df.double_col.nunique() assert result == expected def test_not_exists_works(alltypes): t = alltypes t2 = t.view() expr = t[-((t.string_col == t2.string_col).any())] expr.execute() def test_interactive_repr_shows_error(alltypes): # #591. Doing this in SQLite because so many built-in functions are not # available expr = alltypes.double_col.approx_nunique() with config.option_context('interactive', True): result = repr(expr) assert 'no translation rule' in result.lower() def test_subquery(alltypes, df): t = alltypes expr = ( t.mutate(d=t.double_col.fillna(0)) .limit(1000) .group_by('string_col') .size() ) result = expr.execute() expected = ( df.assign(d=df.double_col.fillna(0)) .head(1000) .groupby('string_col') .size() .reset_index() .rename(columns={0: 'count'}) ) tm.assert_frame_equal(result, expected) def test_filter(alltypes, df): expr = alltypes.filter(alltypes.year == 2010).float_col result = expr.execute().squeeze().reset_index(drop=True) expected = df.query('year == 2010').float_col assert len(result) == len(expected) @pytest.mark.parametrize( 'column', [lambda t: 'float_col', lambda t: t['float_col']] ) def test_column_access_after_sort(alltypes, df, column): expr = alltypes.sort_by(column(alltypes)).head(10).string_col result = expr.execute() expected = ( df.sort_values('float_col').string_col.head(10).reset_index(drop=True) ) tm.assert_series_equal(result, expected) @pytest.fixture def mj1(con): con.create_table( "mj1", schema=ibis.schema(dict(id1="int32", val1="float64")), force=True, ) try: con.insert( "mj1", pd.DataFrame(dict(id1=[1, 2], val1=[10, 20])), overwrite=True, ) yield con.table("mj1") finally: con.drop_table("mj1", force=True) @pytest.fixture def mj2(con): con.create_table( "mj2", schema=ibis.schema(dict(id2="int32", val2="float64")), force=True, ) try: con.insert( "mj2", pd.DataFrame(dict(id2=[1, 2], val2=[15, 25])), overwrite=True, ) yield con.table("mj2") finally: con.drop_table("mj2", force=True) def test_simple_join(con, mj1, mj2): joined = mj1.join(mj2, mj1.id1 == mj2.id2) result = joined.val2.execute() assert len(result) == 2 def test_anonymous_aggregate(alltypes, df): expr = alltypes[alltypes.double_col > alltypes.double_col.mean()] result = expr.execute() expected = df[df.double_col > df.double_col.mean()].reset_index(drop=True) tm.assert_frame_equal(result, expected) def test_head(alltypes): t = alltypes result = t.head().execute() expected = t.limit(5).execute() tm.assert_frame_equal(result, expected) def test_identical_to(alltypes): t = alltypes dt = t[['tinyint_col', 'double_col']].execute() expr = t.tinyint_col.identical_to(t.double_col) result = expr.execute() expected = (dt.tinyint_col.isnull() & dt.double_col.isnull()) | ( dt.tinyint_col == dt.double_col ) expected.name = result.name tm.assert_series_equal(result, expected) @pytest.mark.xfail( raises=AttributeError, reason="truncate method is not yet implemented", ) def test_truncate_method(con, alltypes): expr = alltypes.limit(5) name = str(uuid.uuid4()) con.create_table(name, expr) t = con.table(name) assert len(t.execute()) == 5 t.truncate() assert len(t.execute()) == 0 def test_truncate_from_connection(con, alltypes): expr = alltypes.limit(5) name = str(uuid.uuid4()) con.create_table(name, expr) t = con.table(name) assert len(t.execute()) == 5 con.truncate_table(name) assert len(t.execute()) == 0 def test_not(alltypes): t = alltypes.limit(10) expr = t.projection([(~t.double_col.isnull()).name('double_col')]) result = expr.execute().double_col expected = ~t.execute().double_col.isnull() tm.assert_series_equal(result, expected) def test_compile_with_named_table(): t = ibis.table([('a', 'string')], name='t') result = ibis.sqlite.compile(t.a) st = sa.table('t', sa.column('a', sa.String)).alias('t0') assert str(result) == str(sa.select([st.c.a])) def test_compile_with_unnamed_table(): t = ibis.table([('a', 'string')]) result = ibis.sqlite.compile(t.a) st = sa.table(t.op().name, sa.column('a', sa.String)).alias('t0') assert str(result) == str(sa.select([st.c.a])) def test_compile_with_multiple_unnamed_tables(): t = ibis.table([('a', 'string')]) s = ibis.table([('b', 'string')]) join = t.join(s, t.a == s.b) result = ibis.sqlite.compile(join) sqla_t = sa.table(t.op().name, sa.column('a', sa.String)).alias('t0') sqla_s = sa.table(s.op().name, sa.column('b', sa.String)).alias('t1') sqla_join = sqla_t.join(sqla_s, sqla_t.c.a == sqla_s.c.b) expected = sa.select([sqla_t.c.a, sqla_s.c.b]).select_from(sqla_join) assert str(result) == str(expected) def test_compile_with_one_unnamed_table(): t = ibis.table([('a', 'string')]) s = ibis.table([('b', 'string')], name='s') join = t.join(s, t.a == s.b) result = ibis.sqlite.compile(join) sqla_t = sa.table(t.op().name, sa.column('a', sa.String)).alias('t0') sqla_s = sa.table('s', sa.column('b', sa.String)).alias('t1') sqla_join = sqla_t.join(sqla_s, sqla_t.c.a == sqla_s.c.b) expected = sa.select([sqla_t.c.a, sqla_s.c.b]).select_from(sqla_join) assert str(result) == str(expected) @pytest.mark.parametrize( ('attr', 'expected'), [ (operator.methodcaller('year'), {2009, 2010}), (operator.methodcaller('month'), set(range(1, 13))), (operator.methodcaller('day'), set(range(1, 32))), ], ) def test_date_extract_field(alltypes, attr, expected): t = alltypes expr = attr(t.timestamp_col.cast('date')).distinct() result = expr.execute().astype(int) assert set(result) == expected def test_scalar_parameter(alltypes): start = ibis.param(dt.date) end = ibis.param(dt.date) t = alltypes col = t.date_string_col.cast('date') expr = col.between(start, end) start_string, end_string = '2009-03-01', '2010-07-03' result = expr.execute(params={start: start_string, end: end_string}) expected = col.between(start_string, end_string).execute() tm.assert_series_equal(result, expected) def test_compile_twice(dbpath): con1 = ibis.sqlite.connect(dbpath) t1 = con1.table('batting') sort_key1 = ibis.desc(t1.playerID) sorted_table1 = t1.sort_by(sort_key1) expr1 = sorted_table1.count() con2 = ibis.sqlite.connect(dbpath) t2 = con2.table('batting') sort_key2 = ibis.desc(t2.playerID) sorted_table2 = t2.sort_by(sort_key2) expr2 = sorted_table2.count() result1 = str(expr1.compile()) result2 = str(expr2.compile()) assert result1 == result2 def test_count_on_order_by(con): t = con.table("batting") sort_key = ibis.desc(t.playerID) sorted_table = t.sort_by(sort_key) expr = sorted_table.count() result = str( expr.compile().compile(compile_kwargs={'literal_binds': True}) ) expected = ( "SELECT count('*') AS count \nFROM main.batting AS t0" # noqa: W291 ) assert result == expected
[ "ibis.sqlite.compile", "math.sqrt", "math.log", "pandas.testing.assert_frame_equal", "math.exp", "math.log10", "ibis.NA.fillna", "pytest.mark.xfail", "numpy.where", "numpy.testing.assert_allclose", "pandas.Categorical", "ibis.param", "ibis.table", "packaging.version.parse", "ibis.expr.da...
[((295, 328), 'pytest.importorskip', 'pytest.importorskip', (['"""sqlalchemy"""'], {}), "('sqlalchemy')\n", (314, 328), False, 'import pytest\n'), ((16637, 16726), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""column"""', "[lambda t: 'float_col', lambda t: t['float_col']]"], {}), "('column', [lambda t: 'float_col', lambda t: t[\n 'float_col']])\n", (16660, 16726), False, 'import pytest\n'), ((18756, 18850), 'pytest.mark.xfail', 'pytest.mark.xfail', ([], {'raises': 'AttributeError', 'reason': '"""truncate method is not yet implemented"""'}), "(raises=AttributeError, reason=\n 'truncate method is not yet implemented')\n", (18773, 18850), False, 'import pytest\n'), ((8730, 8770), 'pandas.testing.assert_series_equal', 'tm.assert_series_equal', (['result', 'expected'], {}), '(result, expected)\n', (8752, 8770), True, 'import pandas.testing as tm\n'), ((9402, 9442), 'pandas.testing.assert_series_equal', 'tm.assert_series_equal', (['result', 'expected'], {}), '(result, expected)\n', (9424, 9442), True, 'import pandas.testing as tm\n'), ((10856, 10915), 'pandas.testing.assert_series_equal', 'tm.assert_series_equal', (['result', 'expected'], {'check_names': '(False)'}), '(result, expected, check_names=False)\n', (10878, 10915), True, 'import pandas.testing as tm\n'), ((11218, 11273), 'pandas.cut', 'pd.cut', (['df.double_col', 'bins'], {'labels': 'labels', 'right': '(False)'}), '(df.double_col, bins, labels=labels, right=False)\n', (11224, 11273), True, 'import pandas as pd\n'), ((11278, 11318), 'pandas.testing.assert_series_equal', 'tm.assert_series_equal', (['result', 'expected'], {}), '(result, expected)\n', (11300, 11318), True, 'import pandas.testing as tm\n'), ((14957, 15001), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['result', 'expected'], {}), '(result, expected)\n', (14983, 15001), True, 'import numpy as np\n'), ((15216, 15275), 'pandas.testing.assert_series_equal', 'tm.assert_series_equal', (['result', 'expected'], {'check_names': '(False)'}), '(result, expected, check_names=False)\n', (15238, 15275), True, 'import pandas.testing as tm\n'), ((16350, 16389), 'pandas.testing.assert_frame_equal', 'tm.assert_frame_equal', (['result', 'expected'], {}), '(result, expected)\n', (16371, 16389), True, 'import pandas.testing as tm\n'), ((16985, 17025), 'pandas.testing.assert_series_equal', 'tm.assert_series_equal', (['result', 'expected'], {}), '(result, expected)\n', (17007, 17025), True, 'import pandas.testing as tm\n'), ((18180, 18219), 'pandas.testing.assert_frame_equal', 'tm.assert_frame_equal', (['result', 'expected'], {}), '(result, expected)\n', (18201, 18219), True, 'import pandas.testing as tm\n'), ((18336, 18375), 'pandas.testing.assert_frame_equal', 'tm.assert_frame_equal', (['result', 'expected'], {}), '(result, expected)\n', (18357, 18375), True, 'import pandas.testing as tm\n'), ((18712, 18752), 'pandas.testing.assert_series_equal', 'tm.assert_series_equal', (['result', 'expected'], {}), '(result, expected)\n', (18734, 18752), True, 'import pandas.testing as tm\n'), ((19573, 19613), 'pandas.testing.assert_series_equal', 'tm.assert_series_equal', (['result', 'expected'], {}), '(result, expected)\n', (19595, 19613), True, 'import pandas.testing as tm\n'), ((19661, 19700), 'ibis.table', 'ibis.table', (["[('a', 'string')]"], {'name': '"""t"""'}), "([('a', 'string')], name='t')\n", (19671, 19700), False, 'import ibis\n'), ((19714, 19738), 'ibis.sqlite.compile', 'ibis.sqlite.compile', (['t.a'], {}), '(t.a)\n', (19733, 19738), False, 'import ibis\n'), ((19901, 19930), 'ibis.table', 'ibis.table', (["[('a', 'string')]"], {}), "([('a', 'string')])\n", (19911, 19930), False, 'import ibis\n'), ((19944, 19968), 'ibis.sqlite.compile', 'ibis.sqlite.compile', (['t.a'], {}), '(t.a)\n', (19963, 19968), False, 'import ibis\n'), ((20149, 20178), 'ibis.table', 'ibis.table', (["[('a', 'string')]"], {}), "([('a', 'string')])\n", (20159, 20178), False, 'import ibis\n'), ((20187, 20216), 'ibis.table', 'ibis.table', (["[('b', 'string')]"], {}), "([('b', 'string')])\n", (20197, 20216), False, 'import ibis\n'), ((20263, 20288), 'ibis.sqlite.compile', 'ibis.sqlite.compile', (['join'], {}), '(join)\n', (20282, 20288), False, 'import ibis\n'), ((20666, 20695), 'ibis.table', 'ibis.table', (["[('a', 'string')]"], {}), "([('a', 'string')])\n", (20676, 20695), False, 'import ibis\n'), ((20704, 20743), 'ibis.table', 'ibis.table', (["[('b', 'string')]"], {'name': '"""s"""'}), "([('b', 'string')], name='s')\n", (20714, 20743), False, 'import ibis\n'), ((20790, 20815), 'ibis.sqlite.compile', 'ibis.sqlite.compile', (['join'], {}), '(join)\n', (20809, 20815), False, 'import ibis\n'), ((21631, 21650), 'ibis.param', 'ibis.param', (['dt.date'], {}), '(dt.date)\n', (21641, 21650), False, 'import ibis\n'), ((21661, 21680), 'ibis.param', 'ibis.param', (['dt.date'], {}), '(dt.date)\n', (21671, 21680), False, 'import ibis\n'), ((21972, 22012), 'pandas.testing.assert_series_equal', 'tm.assert_series_equal', (['result', 'expected'], {}), '(result, expected)\n', (21994, 22012), True, 'import pandas.testing as tm\n'), ((22058, 22085), 'ibis.sqlite.connect', 'ibis.sqlite.connect', (['dbpath'], {}), '(dbpath)\n', (22077, 22085), False, 'import ibis\n'), ((22133, 22155), 'ibis.desc', 'ibis.desc', (['t1.playerID'], {}), '(t1.playerID)\n', (22142, 22155), False, 'import ibis\n'), ((22244, 22271), 'ibis.sqlite.connect', 'ibis.sqlite.connect', (['dbpath'], {}), '(dbpath)\n', (22263, 22271), False, 'import ibis\n'), ((22319, 22341), 'ibis.desc', 'ibis.desc', (['t2.playerID'], {}), '(t2.playerID)\n', (22328, 22341), False, 'import ibis\n'), ((22599, 22620), 'ibis.desc', 'ibis.desc', (['t.playerID'], {}), '(t.playerID)\n', (22608, 22620), False, 'import ibis\n'), ((1609, 1648), 'ibis.literal', 'ibis.literal', (['"""2015-09-01 14:48:05.359"""'], {}), "('2015-09-01 14:48:05.359')\n", (1621, 1648), False, 'import ibis\n'), ((6435, 6442), 'ibis.literal', 'L', (['None'], {}), '(None)\n', (6436, 6442), True, 'from ibis import literal as L\n'), ((6472, 6479), 'ibis.literal', 'L', (['None'], {}), '(None)\n', (6473, 6479), True, 'from ibis import literal as L\n'), ((10825, 10849), 'pandas.Categorical', 'pd.Categorical', (['expected'], {}), '(expected)\n', (10839, 10849), True, 'import pandas as pd\n'), ((11132, 11168), 'pandas.Categorical', 'pd.Categorical', (['result'], {'ordered': '(True)'}), '(result, ordered=True)\n', (11146, 11168), True, 'import pandas as pd\n'), ((11345, 11374), 'packaging.version.parse', 'parse', (['sqlite3.sqlite_version'], {}), '(sqlite3.sqlite_version)\n', (11350, 11374), False, 'from packaging.version import parse\n'), ((11377, 11391), 'packaging.version.parse', 'parse', (['"""3.8.3"""'], {}), "('3.8.3')\n", (11382, 11391), False, 'from packaging.version import parse\n'), ((15811, 15853), 'ibis.config.option_context', 'config.option_context', (['"""interactive"""', '(True)'], {}), "('interactive', True)\n", (15832, 15853), False, 'from ibis import config\n'), ((18942, 18954), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (18952, 18954), False, 'import uuid\n'), ((19192, 19204), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (19202, 19204), False, 'import uuid\n'), ((2219, 2229), 'ibis.now', 'ibis.now', ([], {}), '()\n', (2227, 2229), False, 'import ibis\n'), ((2298, 2324), 'datetime.datetime.utcnow', 'datetime.datetime.utcnow', ([], {}), '()\n', (2322, 2324), False, 'import datetime\n'), ((3118, 3134), 'ibis.NA.typeof', 'ibis.NA.typeof', ([], {}), '()\n', (3132, 3134), False, 'import ibis\n'), ((5531, 5545), 'ibis.literal', 'L', (['"""foobarfoo"""'], {}), "('foobarfoo')\n", (5532, 5545), True, 'from ibis import literal as L\n'), ((5925, 5941), 'math.sqrt', 'math.sqrt', (['(5.556)'], {}), '(5.556)\n', (5934, 5941), False, 'import math\n'), ((6034, 6049), 'math.exp', 'math.exp', (['(5.556)'], {}), '(5.556)\n', (6042, 6049), False, 'import math\n'), ((6166, 6184), 'math.log', 'math.log', (['(5.556)', '(2)'], {}), '(5.556, 2)\n', (6174, 6184), False, 'import math\n'), ((6211, 6226), 'math.log', 'math.log', (['(5.556)'], {}), '(5.556)\n', (6219, 6226), False, 'import math\n'), ((6255, 6273), 'math.log', 'math.log', (['(5.556)', '(2)'], {}), '(5.556, 2)\n', (6263, 6273), False, 'import math\n'), ((6303, 6320), 'math.log10', 'math.log10', (['(5.556)'], {}), '(5.556)\n', (6313, 6320), False, 'import math\n'), ((8333, 8350), 'ibis.NA.fillna', 'ibis.NA.fillna', (['(5)'], {}), '(5)\n', (8347, 8350), False, 'import ibis\n'), ((18576, 18599), 'ibis.expr.datatypes.tinyint_col.isnull', 'dt.tinyint_col.isnull', ([], {}), '()\n', (18597, 18599), True, 'import ibis.expr.datatypes as dt\n'), ((18602, 18624), 'ibis.expr.datatypes.double_col.isnull', 'dt.double_col.isnull', ([], {}), '()\n', (18622, 18624), True, 'import ibis.expr.datatypes as dt\n'), ((21201, 21230), 'operator.methodcaller', 'operator.methodcaller', (['"""year"""'], {}), "('year')\n", (21222, 21230), False, 'import operator\n'), ((21256, 21286), 'operator.methodcaller', 'operator.methodcaller', (['"""month"""'], {}), "('month')\n", (21277, 21286), False, 'import operator\n'), ((21317, 21345), 'operator.methodcaller', 'operator.methodcaller', (['"""day"""'], {}), "('day')\n", (21338, 21345), False, 'import operator\n'), ((2446, 2450), 'ibis.literal', 'L', (['(3)'], {}), '(3)\n', (2447, 2450), True, 'from ibis import literal as L\n'), ((2453, 2457), 'ibis.literal', 'L', (['(4)'], {}), '(4)\n', (2454, 2457), True, 'from ibis import literal as L\n'), ((2472, 2476), 'ibis.literal', 'L', (['(3)'], {}), '(3)\n', (2473, 2476), True, 'from ibis import literal as L\n'), ((2479, 2483), 'ibis.literal', 'L', (['(4)'], {}), '(4)\n', (2480, 2483), True, 'from ibis import literal as L\n'), ((2499, 2503), 'ibis.literal', 'L', (['(3)'], {}), '(3)\n', (2500, 2503), True, 'from ibis import literal as L\n'), ((2506, 2510), 'ibis.literal', 'L', (['(4)'], {}), '(4)\n', (2507, 2510), True, 'from ibis import literal as L\n'), ((2526, 2531), 'ibis.literal', 'L', (['(12)'], {}), '(12)\n', (2527, 2531), True, 'from ibis import literal as L\n'), ((2534, 2538), 'ibis.literal', 'L', (['(4)'], {}), '(4)\n', (2535, 2538), True, 'from ibis import literal as L\n'), ((2553, 2558), 'ibis.literal', 'L', (['(12)'], {}), '(12)\n', (2554, 2558), True, 'from ibis import literal as L\n'), ((2562, 2566), 'ibis.literal', 'L', (['(2)'], {}), '(2)\n', (2563, 2566), True, 'from ibis import literal as L\n'), ((2583, 2588), 'ibis.literal', 'L', (['(12)'], {}), '(12)\n', (2584, 2588), True, 'from ibis import literal as L\n'), ((2591, 2595), 'ibis.literal', 'L', (['(5)'], {}), '(5)\n', (2592, 2595), True, 'from ibis import literal as L\n'), ((2769, 2773), 'ibis.literal', 'L', (['(7)'], {}), '(7)\n', (2770, 2773), True, 'from ibis import literal as L\n'), ((2776, 2780), 'ibis.literal', 'L', (['(2)'], {}), '(2)\n', (2777, 2780), True, 'from ibis import literal as L\n'), ((2797, 2801), 'ibis.literal', 'L', (['(7)'], {}), '(7)\n', (2798, 2801), True, 'from ibis import literal as L\n'), ((2805, 2809), 'ibis.literal', 'L', (['(2)'], {}), '(2)\n', (2806, 2809), True, 'from ibis import literal as L\n'), ((5761, 5765), 'ibis.literal', 'L', (['(5)'], {}), '(5)\n', (5762, 5765), True, 'from ibis import literal as L\n'), ((5767, 5772), 'ibis.literal', 'L', (['(10)'], {}), '(10)\n', (5768, 5772), True, 'from ibis import literal as L\n'), ((5774, 5778), 'ibis.literal', 'L', (['(1)'], {}), '(1)\n', (5775, 5778), True, 'from ibis import literal as L\n'), ((5808, 5812), 'ibis.literal', 'L', (['(5)'], {}), '(5)\n', (5809, 5812), True, 'from ibis import literal as L\n'), ((5814, 5819), 'ibis.literal', 'L', (['(10)'], {}), '(10)\n', (5815, 5819), True, 'from ibis import literal as L\n'), ((5821, 5825), 'ibis.literal', 'L', (['(1)'], {}), '(1)\n', (5822, 5825), True, 'from ibis import literal as L\n'), ((9623, 9681), 'pandas.cut', 'pd.cut', (['s', '[0, 10, 25, 50, 100]'], {'right': '(False)', 'labels': '(False)'}), '(s, [0, 10, 25, 50, 100], right=False, labels=False)\n', (9629, 9681), True, 'import pandas as pd\n'), ((9824, 9885), 'pandas.cut', 'pd.cut', (['s', '[0, 10, 25, 50, np.inf]'], {'right': '(False)', 'labels': '(False)'}), '(s, [0, 10, 25, 50, np.inf], right=False, labels=False)\n', (9830, 9885), True, 'import pandas as pd\n'), ((10030, 10083), 'pandas.cut', 'pd.cut', (['s', '[0, 10, 25, 50]'], {'right': '(False)', 'labels': '(False)'}), '(s, [0, 10, 25, 50], right=False, labels=False)\n', (10036, 10083), True, 'import pandas as pd\n'), ((10244, 10318), 'pandas.cut', 'pd.cut', (['s', '[0, 10, 25, 50]'], {'include_lowest': '(False)', 'right': '(True)', 'labels': '(False)'}), '(s, [0, 10, 25, 50], include_lowest=False, right=True, labels=False)\n', (10250, 10318), True, 'import pandas as pd\n'), ((10529, 10587), 'pandas.cut', 'pd.cut', (['s', '[0, 10, 25, 50, 100]'], {'right': '(False)', 'labels': '(False)'}), '(s, [0, 10, 25, 50, 100], right=False, labels=False)\n', (10535, 10587), True, 'import pandas as pd\n'), ((2824, 2828), 'ibis.literal', 'L', (['(7)'], {}), '(7)\n', (2825, 2828), True, 'from ibis import literal as L\n'), ((2855, 2859), 'ibis.literal', 'L', (['(2)'], {}), '(2)\n', (2856, 2859), True, 'from ibis import literal as L\n'), ((3041, 3053), 'ibis.literal', 'L', (['"""foo_bar"""'], {}), "('foo_bar')\n", (3042, 3053), True, 'from ibis import literal as L\n'), ((3082, 3086), 'ibis.literal', 'L', (['(5)'], {}), '(5)\n', (3083, 3086), True, 'from ibis import literal as L\n'), ((3154, 3163), 'ibis.literal', 'L', (['(1.2345)'], {}), '(1.2345)\n', (3155, 3163), True, 'from ibis import literal as L\n'), ((3331, 3335), 'ibis.literal', 'L', (['(0)'], {}), '(0)\n', (3332, 3335), True, 'from ibis import literal as L\n'), ((3358, 3364), 'ibis.literal', 'L', (['(5.5)'], {}), '(5.5)\n', (3359, 3364), True, 'from ibis import literal as L\n'), ((3527, 3539), 'ibis.literal', 'L', (['"""foo_bar"""'], {}), "('foo_bar')\n", (3528, 3539), True, 'from ibis import literal as L\n'), ((3555, 3560), 'ibis.literal', 'L', (['""""""'], {}), "('')\n", (3556, 3560), True, 'from ibis import literal as L\n'), ((3732, 3744), 'ibis.literal', 'L', (['"""foo_bar"""'], {}), "('foo_bar')\n", (3733, 3744), True, 'from ibis import literal as L\n'), ((3771, 3783), 'ibis.literal', 'L', (['"""foo_bar"""'], {}), "('foo_bar')\n", (3772, 3783), True, 'from ibis import literal as L\n'), ((3811, 3823), 'ibis.literal', 'L', (['"""foo_bar"""'], {}), "('foo_bar')\n", (3812, 3823), True, 'from ibis import literal as L\n'), ((3855, 3867), 'ibis.literal', 'L', (['"""foo_bar"""'], {}), "('foo_bar')\n", (3856, 3867), True, 'from ibis import literal as L\n'), ((3899, 3911), 'ibis.literal', 'L', (['"""foo_bar"""'], {}), "('foo_bar')\n", (3900, 3911), True, 'from ibis import literal as L\n'), ((4101, 4115), 'ibis.literal', 'L', (['""" foo """'], {}), "(' foo ')\n", (4102, 4115), True, 'from ibis import literal as L\n'), ((4146, 4160), 'ibis.literal', 'L', (['""" foo """'], {}), "(' foo ')\n", (4147, 4160), True, 'from ibis import literal as L\n'), ((4191, 4205), 'ibis.literal', 'L', (['""" foo """'], {}), "(' foo ')\n", (4192, 4205), True, 'from ibis import literal as L\n'), ((4377, 4385), 'ibis.literal', 'L', (['"""foo"""'], {}), "('foo')\n", (4378, 4385), True, 'from ibis import literal as L\n'), ((4404, 4412), 'ibis.literal', 'L', (['"""FOO"""'], {}), "('FOO')\n", (4405, 4412), True, 'from ibis import literal as L\n'), ((4593, 4604), 'ibis.literal', 'L', (['"""foobar"""'], {}), "('foobar')\n", (4594, 4604), True, 'from ibis import literal as L\n'), ((4638, 4649), 'ibis.literal', 'L', (['"""foobar"""'], {}), "('foobar')\n", (4639, 4649), True, 'from ibis import literal as L\n'), ((4683, 4694), 'ibis.literal', 'L', (['"""foobar"""'], {}), "('foobar')\n", (4684, 4694), True, 'from ibis import literal as L\n'), ((4877, 4888), 'ibis.literal', 'L', (['"""foobar"""'], {}), "('foobar')\n", (4878, 4888), True, 'from ibis import literal as L\n'), ((4907, 4918), 'ibis.literal', 'L', (['"""foobar"""'], {}), "('foobar')\n", (4908, 4918), True, 'from ibis import literal as L\n'), ((5093, 5104), 'ibis.literal', 'L', (['"""foobar"""'], {}), "('foobar')\n", (5094, 5104), True, 'from ibis import literal as L\n'), ((5135, 5146), 'ibis.literal', 'L', (['"""foobar"""'], {}), "('foobar')\n", (5136, 5146), True, 'from ibis import literal as L\n'), ((5177, 5188), 'ibis.literal', 'L', (['"""foobar"""'], {}), "('foobar')\n", (5178, 5188), True, 'from ibis import literal as L\n'), ((5221, 5232), 'ibis.literal', 'L', (['"""foobar"""'], {}), "('foobar')\n", (5222, 5232), True, 'from ibis import literal as L\n'), ((5265, 5276), 'ibis.literal', 'L', (['"""foobar"""'], {}), "('foobar')\n", (5266, 5276), True, 'from ibis import literal as L\n'), ((5309, 5320), 'ibis.literal', 'L', (['"""foobar"""'], {}), "('foobar')\n", (5310, 5320), True, 'from ibis import literal as L\n'), ((5355, 5366), 'ibis.literal', 'L', (['"""foobar"""'], {}), "('foobar')\n", (5356, 5366), True, 'from ibis import literal as L\n'), ((5699, 5704), 'ibis.literal', 'L', (['(-5)'], {}), '(-5)\n', (5700, 5704), True, 'from ibis import literal as L\n'), ((5725, 5729), 'ibis.literal', 'L', (['(5)'], {}), '(5)\n', (5726, 5729), True, 'from ibis import literal as L\n'), ((5842, 5848), 'ibis.literal', 'L', (['(5.5)'], {}), '(5.5)\n', (5843, 5848), True, 'from ibis import literal as L\n'), ((5873, 5881), 'ibis.literal', 'L', (['(5.556)'], {}), '(5.556)\n', (5874, 5881), True, 'from ibis import literal as L\n'), ((5908, 5916), 'ibis.literal', 'L', (['(5.556)'], {}), '(5.556)\n', (5909, 5916), True, 'from ibis import literal as L\n'), ((5953, 5961), 'ibis.literal', 'L', (['(5.556)'], {}), '(5.556)\n', (5954, 5961), True, 'from ibis import literal as L\n'), ((5985, 5993), 'ibis.literal', 'L', (['(5.556)'], {}), '(5.556)\n', (5986, 5993), True, 'from ibis import literal as L\n'), ((6018, 6026), 'ibis.literal', 'L', (['(5.556)'], {}), '(5.556)\n', (6019, 6026), True, 'from ibis import literal as L\n'), ((6061, 6069), 'ibis.literal', 'L', (['(5.556)'], {}), '(5.556)\n', (6062, 6069), True, 'from ibis import literal as L\n'), ((6091, 6100), 'ibis.literal', 'L', (['(-5.556)'], {}), '(-5.556)\n', (6092, 6100), True, 'from ibis import literal as L\n'), ((6123, 6127), 'ibis.literal', 'L', (['(0)'], {}), '(0)\n', (6124, 6127), True, 'from ibis import literal as L\n'), ((6149, 6157), 'ibis.literal', 'L', (['(5.556)'], {}), '(5.556)\n', (6150, 6157), True, 'from ibis import literal as L\n'), ((6196, 6204), 'ibis.literal', 'L', (['(5.556)'], {}), '(5.556)\n', (6197, 6204), True, 'from ibis import literal as L\n'), ((6238, 6246), 'ibis.literal', 'L', (['(5.556)'], {}), '(5.556)\n', (6239, 6246), True, 'from ibis import literal as L\n'), ((6285, 6293), 'ibis.literal', 'L', (['(5.556)'], {}), '(5.556)\n', (6286, 6293), True, 'from ibis import literal as L\n'), ((6564, 6573), 'ibis.literal', 'L', (['"""abcd"""'], {}), "('abcd')\n", (6565, 6573), True, 'from ibis import literal as L\n'), ((6610, 6619), 'ibis.literal', 'L', (['"""abcd"""'], {}), "('abcd')\n", (6611, 6619), True, 'from ibis import literal as L\n'), ((6658, 6667), 'ibis.literal', 'L', (['"""1222"""'], {}), "('1222')\n", (6659, 6667), True, 'from ibis import literal as L\n'), ((6705, 6714), 'ibis.literal', 'L', (['"""abcd"""'], {}), "('abcd')\n", (6706, 6714), True, 'from ibis import literal as L\n'), ((7003, 7012), 'ibis.literal', 'L', (['"""abcd"""'], {}), "('abcd')\n", (7004, 7012), True, 'from ibis import literal as L\n'), ((7131, 7140), 'ibis.literal', 'L', (['"""abcd"""'], {}), "('abcd')\n", (7132, 7140), True, 'from ibis import literal as L\n'), ((7195, 7204), 'ibis.literal', 'L', (['"""abcd"""'], {}), "('abcd')\n", (7196, 7204), True, 'from ibis import literal as L\n'), ((7251, 7260), 'ibis.literal', 'L', (['"""abcd"""'], {}), "('abcd')\n", (7252, 7260), True, 'from ibis import literal as L\n'), ((7645, 7654), 'ibis.literal', 'L', (['"""abcd"""'], {}), "('abcd')\n", (7646, 7654), True, 'from ibis import literal as L\n'), ((7696, 7705), 'ibis.literal', 'L', (['"""1222"""'], {}), "('1222')\n", (7697, 7705), True, 'from ibis import literal as L\n'), ((7749, 7758), 'ibis.literal', 'L', (['"""1222"""'], {}), "('1222')\n", (7750, 7758), True, 'from ibis import literal as L\n'), ((7892, 7901), 'ibis.literal', 'L', (['"""abcd"""'], {}), "('abcd')\n", (7893, 7901), True, 'from ibis import literal as L\n'), ((7955, 7964), 'ibis.literal', 'L', (['"""abcd"""'], {}), "('abcd')\n", (7956, 7964), True, 'from ibis import literal as L\n'), ((8010, 8019), 'ibis.literal', 'L', (['"""abcd"""'], {}), "('abcd')\n", (8011, 8019), True, 'from ibis import literal as L\n'), ((8365, 8369), 'ibis.literal', 'L', (['(5)'], {}), '(5)\n', (8366, 8369), True, 'from ibis import literal as L\n'), ((8395, 8399), 'ibis.literal', 'L', (['(5)'], {}), '(5)\n', (8396, 8399), True, 'from ibis import literal as L\n'), ((8427, 8432), 'ibis.literal', 'L', (['(10)'], {}), '(10)\n', (8428, 8432), True, 'from ibis import literal as L\n'), ((8955, 8992), 'numpy.where', 'np.where', (['(df.double_col > 20)', '(10)', '(-20)'], {}), '(df.double_col > 20, 10, -20)\n', (8963, 8992), True, 'import numpy as np\n'), ((7053, 7060), 'ibis.literal', 'L', (['None'], {}), '(None)\n', (7054, 7060), True, 'from ibis import literal as L\n'), ((7579, 7588), 'ibis.literal', 'L', (['"""1222"""'], {}), "('1222')\n", (7580, 7588), True, 'from ibis import literal as L\n'), ((9170, 9207), 'numpy.where', 'np.where', (['(df.double_col > 20)', '(10)', '(-20)'], {}), '(df.double_col > 20, 10, -20)\n', (9178, 9207), True, 'import numpy as np\n')]
# logisitc regression classifier for the donut problem. # # the notes for this class can be found at: # https://deeplearningcourses.com/c/data-science-logistic-regression-in-python # https://www.udemy.com/data-science-logistic-regression-in-python from __future__ import print_function, division from builtins import range # Note: you may need to update your version of future # sudo pip install -U future import numpy as np import matplotlib.pyplot as plt N = 1000 D = 2 R_inner = 5 R_outer = 10 # distance from origin is radius + random normal # angle theta is uniformly distributed between (0, 2pi) R1 = np.random.randn(N//2) + R_inner theta = 2*np.pi*np.random.random(N//2) X_inner = np.concatenate([[R1 * np.cos(theta)], [R1 * np.sin(theta)]]).T R2 = np.random.randn(N//2) + R_outer theta = 2*np.pi*np.random.random(N//2) X_outer = np.concatenate([[R2 * np.cos(theta)], [R2 * np.sin(theta)]]).T X = np.concatenate([ X_inner, X_outer ]) T = np.array([0]*(N//2) + [1]*(N//2)) # labels: first 50 are 0, last 50 are 1 plt.scatter(X[:,0], X[:,1], c=T) plt.show() # add a column of ones # ones = np.array([[1]*N]).T # old ones = np.ones((N, 1)) # add a column of r = sqrt(x^2 + y^2) r = np.sqrt( (X * X).sum(axis=1) ).reshape(-1, 1) Xb = np.concatenate((ones, r, X), axis=1) # randomly initialize the weights w = np.random.randn(D + 2) # calculate the model output z = Xb.dot(w) def sigmoid(z): return 1/(1 + np.exp(-z)) Y = sigmoid(z) # calculate the cross-entropy error def cross_entropy(T, Y): return -(T*np.log(Y) + (1-T)*np.log(1-Y)).sum() # let's do gradient descent 100 times learning_rate = 0.0001 error = [] for i in range(5000): e = cross_entropy(T, Y) error.append(e) if i % 500 == 0: print(e) # gradient descent weight udpate with regularization w += learning_rate * ( Xb.T.dot(T - Y) - 0.1*w ) # recalculate Y Y = sigmoid(Xb.dot(w)) plt.plot(error) plt.title("Cross-entropy per iteration") plt.show() print("Final w:", w) print("Final classification rate:", 1 - np.abs(T - np.round(Y)).sum() / N)
[ "numpy.ones", "numpy.random.random", "matplotlib.pyplot.plot", "numpy.log", "numpy.exp", "numpy.array", "builtins.range", "numpy.cos", "matplotlib.pyplot.scatter", "numpy.concatenate", "numpy.sin", "matplotlib.pyplot.title", "numpy.random.randn", "numpy.round", "matplotlib.pyplot.show" ]
[((914, 948), 'numpy.concatenate', 'np.concatenate', (['[X_inner, X_outer]'], {}), '([X_inner, X_outer])\n', (928, 948), True, 'import numpy as np\n'), ((955, 996), 'numpy.array', 'np.array', (['([0] * (N // 2) + [1] * (N // 2))'], {}), '([0] * (N // 2) + [1] * (N // 2))\n', (963, 996), True, 'import numpy as np\n'), ((1030, 1064), 'matplotlib.pyplot.scatter', 'plt.scatter', (['X[:, 0]', 'X[:, 1]'], {'c': 'T'}), '(X[:, 0], X[:, 1], c=T)\n', (1041, 1064), True, 'import matplotlib.pyplot as plt\n'), ((1063, 1073), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1071, 1073), True, 'import matplotlib.pyplot as plt\n'), ((1142, 1157), 'numpy.ones', 'np.ones', (['(N, 1)'], {}), '((N, 1))\n', (1149, 1157), True, 'import numpy as np\n'), ((1252, 1288), 'numpy.concatenate', 'np.concatenate', (['(ones, r, X)'], {'axis': '(1)'}), '((ones, r, X), axis=1)\n', (1266, 1288), True, 'import numpy as np\n'), ((1328, 1350), 'numpy.random.randn', 'np.random.randn', (['(D + 2)'], {}), '(D + 2)\n', (1343, 1350), True, 'import numpy as np\n'), ((1656, 1667), 'builtins.range', 'range', (['(5000)'], {}), '(5000)\n', (1661, 1667), False, 'from builtins import range\n'), ((1915, 1930), 'matplotlib.pyplot.plot', 'plt.plot', (['error'], {}), '(error)\n', (1923, 1930), True, 'import matplotlib.pyplot as plt\n'), ((1931, 1971), 'matplotlib.pyplot.title', 'plt.title', (['"""Cross-entropy per iteration"""'], {}), "('Cross-entropy per iteration')\n", (1940, 1971), True, 'import matplotlib.pyplot as plt\n'), ((1972, 1982), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1980, 1982), True, 'import matplotlib.pyplot as plt\n'), ((615, 638), 'numpy.random.randn', 'np.random.randn', (['(N // 2)'], {}), '(N // 2)\n', (630, 638), True, 'import numpy as np\n'), ((663, 687), 'numpy.random.random', 'np.random.random', (['(N // 2)'], {}), '(N // 2)\n', (679, 687), True, 'import numpy as np\n'), ((765, 788), 'numpy.random.randn', 'np.random.randn', (['(N // 2)'], {}), '(N // 2)\n', (780, 788), True, 'import numpy as np\n'), ((813, 837), 'numpy.random.random', 'np.random.random', (['(N // 2)'], {}), '(N // 2)\n', (829, 837), True, 'import numpy as np\n'), ((1430, 1440), 'numpy.exp', 'np.exp', (['(-z)'], {}), '(-z)\n', (1436, 1440), True, 'import numpy as np\n'), ((718, 731), 'numpy.cos', 'np.cos', (['theta'], {}), '(theta)\n', (724, 731), True, 'import numpy as np\n'), ((740, 753), 'numpy.sin', 'np.sin', (['theta'], {}), '(theta)\n', (746, 753), True, 'import numpy as np\n'), ((868, 881), 'numpy.cos', 'np.cos', (['theta'], {}), '(theta)\n', (874, 881), True, 'import numpy as np\n'), ((890, 903), 'numpy.sin', 'np.sin', (['theta'], {}), '(theta)\n', (896, 903), True, 'import numpy as np\n'), ((1536, 1545), 'numpy.log', 'np.log', (['Y'], {}), '(Y)\n', (1542, 1545), True, 'import numpy as np\n'), ((1554, 1567), 'numpy.log', 'np.log', (['(1 - Y)'], {}), '(1 - Y)\n', (1560, 1567), True, 'import numpy as np\n'), ((2056, 2067), 'numpy.round', 'np.round', (['Y'], {}), '(Y)\n', (2064, 2067), True, 'import numpy as np\n')]
import numpy as np import pandas as pd def get_converging_models_option1(conc_df_interp: pd.DataFrame, n_models: int) -> list: non_converging_models = [] for model_i in range(n_models): last_conc_values = \ conc_df_interp[(conc_df_interp['model'] == model_i) & (conc_df_interp['time_point'].between(0.75, 1.05))][ 'concentration'].values if len(last_conc_values) == 0 or np.any(np.abs(last_conc_values) > 1.05) or np.any(np.abs(last_conc_values) < 0.95): non_converging_models.append(model_i) return non_converging_models def get_converging_models_option2(conc_df_interp: pd.DataFrame, n_models: int, met_names: list, rel_tol: float = 5 * 10**-3) -> list: non_converging_models = [] for model_i in range(n_models): for met in met_names: last_conc_values = conc_df_interp[(conc_df_interp['model'] == model_i) & (conc_df_interp['time_point'].between(0.75, 1.05)) & (conc_df_interp['met'] == met)]['concentration'].values assert len(last_conc_values) == 3 diff1 = np.abs(last_conc_values[0] - last_conc_values[1]) diff2 = np.abs(last_conc_values[1] - last_conc_values[2]) abs_tol = last_conc_values[0]*rel_tol if diff1 > abs_tol or diff2 > abs_tol: non_converging_models.append(model_i) return non_converging_models def remove_models(conc_df: pd.DataFrame, flux_df: pd.DataFrame, model_list: list) -> tuple: filtered_conc_df = conc_df.drop(conc_df[conc_df['model'].isin(model_list)].index) filtered_flux_df = flux_df.drop(flux_df[flux_df['model'].isin(model_list)].index) return filtered_conc_df, filtered_flux_df def get_time_series_quantiles(data_df: pd.DataFrame, time_points_spline: list, data_type: str, name_list: list, scaled: bool = True) -> dict: quantiles_dic = {'time_point': [], data_type: [], 'q025': np.array([]), 'median': np.array([]), 'q075': np.array([])} measure = 'concentration' if data_type == 'met' else 'flux' measure = f'{measure}_unscaled' if not scaled else measure n_time_points = len(time_points_spline) q025 = data_df.groupby([data_type, 'time_point']).quantile(q=0.25) q050 = data_df.groupby([data_type, 'time_point']).median() q075 = data_df.groupby([data_type, 'time_point']).quantile(q=0.75) for item in name_list: quantiles_dic[data_type].extend(np.repeat(item, n_time_points)) quantiles_dic['time_point'].extend(time_points_spline) quantiles_dic['q025'] = np.append(quantiles_dic['q025'], q025.loc[item, :][measure]) quantiles_dic['median'] = np.append(quantiles_dic['median'], q050.loc[item, :][measure]) quantiles_dic['q075'] = np.append(quantiles_dic['q075'], q075.loc[item, :][measure]) #data_df_quantiles = pd.DataFrame.from_dict(conc_dic) return quantiles_dic def filter_negative_residual_conc(data_df: pd.DataFrame, scaled: bool, threshold: float = -10**-5) -> pd.DataFrame: """ This function looks for concentrations lower than the given threshold and sets them to zero. Args: data_df: a pandas dataframe with a concentrations or concentrations_unscaled column. scaled: whether or not one wants to focus on scaled concentrations. threshold: concentrations lower than this will be set to zero. Returns: pandas dataframe with concentrations lower than threshold set to zero. """ data_df.loc[(data_df['concentration' if scaled else 'concentration_unscaled'] < 0) & (data_df['concentration' if scaled else 'concentration_unscaled'] > threshold), ['concentration_unscaled', 'concentration']] = 0 return data_df
[ "numpy.append", "numpy.array", "numpy.abs", "numpy.repeat" ]
[((2069, 2081), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (2077, 2081), True, 'import numpy as np\n'), ((2093, 2105), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (2101, 2105), True, 'import numpy as np\n'), ((2115, 2127), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (2123, 2127), True, 'import numpy as np\n'), ((2703, 2763), 'numpy.append', 'np.append', (["quantiles_dic['q025']", 'q025.loc[item, :][measure]'], {}), "(quantiles_dic['q025'], q025.loc[item, :][measure])\n", (2712, 2763), True, 'import numpy as np\n'), ((2798, 2860), 'numpy.append', 'np.append', (["quantiles_dic['median']", 'q050.loc[item, :][measure]'], {}), "(quantiles_dic['median'], q050.loc[item, :][measure])\n", (2807, 2860), True, 'import numpy as np\n'), ((2893, 2953), 'numpy.append', 'np.append', (["quantiles_dic['q075']", 'q075.loc[item, :][measure]'], {}), "(quantiles_dic['q075'], q075.loc[item, :][measure])\n", (2902, 2953), True, 'import numpy as np\n'), ((1209, 1258), 'numpy.abs', 'np.abs', (['(last_conc_values[0] - last_conc_values[1])'], {}), '(last_conc_values[0] - last_conc_values[1])\n', (1215, 1258), True, 'import numpy as np\n'), ((1279, 1328), 'numpy.abs', 'np.abs', (['(last_conc_values[1] - last_conc_values[2])'], {}), '(last_conc_values[1] - last_conc_values[2])\n', (1285, 1328), True, 'import numpy as np\n'), ((2575, 2605), 'numpy.repeat', 'np.repeat', (['item', 'n_time_points'], {}), '(item, n_time_points)\n', (2584, 2605), True, 'import numpy as np\n'), ((426, 450), 'numpy.abs', 'np.abs', (['last_conc_values'], {}), '(last_conc_values)\n', (432, 450), True, 'import numpy as np\n'), ((469, 493), 'numpy.abs', 'np.abs', (['last_conc_values'], {}), '(last_conc_values)\n', (475, 493), True, 'import numpy as np\n')]
""" HandTracker or HandTrakingModule ================================ It is a simple module to detect hands and do simple projects with hand recognition and machine learning. Hand Detector ------------- Uses: 1. To find and detect hand. 2. To find 21 landmarks in each hand. 3. To find the distance between any 2 landmarks. 4. To find if a finger is up or not. 5. Can create a rectangle for the best hand detection zone. Functions and theris least requirements: 1. HandDetector.FindHands: i. Requires `image` (with atleast one hand) ii. Returns an `image` with hand landmarks drawn on it 2. HandDetector.FindLocation: i. Requires `image` (with atleast one hand) ii. Returns location of hand landmarks `lmloc` (dict), location of hand `handloc` (dict) 3. HandDetector.DrawLandmarks: i. Requires `image` (with atleast one hand), `index` int value more than -1 but less than 21 ii. Returns None 4. HandDetector.fingersUp: i. Requires `image` (with atleast one hand) ii. Returns info dict [fingername: bool] 5. HandDetector.fingersUp_PROTO: i. Requires None ii. Returns info dict [fingername: bool] 6. HandDetector.findDistance: i. Requires `image` (with atleast one hand), `id` numbers of any two landmarks ii. Returns `image` with those landmarks drawn on it and a line connection those and the center point of that line, `length` the disance between 7. HandDetector.FindingZone: i. Requires `image` (with atleast one hand) ii. Returns location of rectangle `FindingZonedim` for the best hand detection zone Other Uses ---------- 1. It can provide all the finger names used in this module, which is stored in `Fingers`. 2. It can provide all the hand landmarks, which is stored in `HandLandmark`. 3. It can provide all the ways to flip an image by 'opencv-python', which is stored in `CVFlipCodes`. 4. It can provide all the corner point names used in this module, which is stored in `CornerPoints`. 5. It can put text at any given coordinate on the image screen with a background, with the help of `PutText` function. For further information about any module, please see for the docs provided in each of the modules. Thank You 🙂 ------------ """ # Importing modules from cProfile import label import setup import cv2 as cv import time as tm import numpy as np from math import hypot as hpt import mediapipe.python.solutions.hands as mphands import mediapipe.python.solutions.drawing_utils as mpdraw # Finger names class Fingers (): """Fingers names.""" THUMB = 'Thumb' INDEX_FINGER = 'Index' MIDDLE_FINGER = 'Middle' RING_FINGER = 'Ring' PINKY = 'Pinky' # Hand landmarks class HandLandmark (): """The 21 hand landmarks.""" WRIST = 0 THUMB_CMC = 1 THUMB_MCP = 2 THUMB_DIP = 3 THUMB_TIP = 4 INDEX_FINGER_MCP = 5 INDEX_FINGER_PIP = 6 INDEX_FINGER_DIP = 7 INDEX_FINGER_TIP = 8 MIDDLE_FINGER_MCP = 9 MIDDLE_FINGER_PIP = 10 MIDDLE_FINGER_DIP = 11 MIDDLE_FINGER_TIP = 12 RING_FINGER_MCP = 13 RING_FINGER_PIP = 14 RING_FINGER_DIP = 15 RING_FINGER_TIP = 16 PINKY_MCP = 17 PINKY_PIP = 18 PINKY_DIP = 19 PINKY_TIP = 20 MCPs = [1, 5, 9, 13, 17] PIPs = [2, 6, 10, 14, 18] DIPs = [3, 7, 11, 15, 19] TIPs = [4, 8, 12, 16, 20] # Ways to flip an image class CVFlipCodes (): """The 3 modes to flip the image.""" flip_vertically = 0 flip_horizontally = 1 flip_vertically_and_horizontally = -1 # Corner point names class CornerPoints (): """The 4 corners.""" Top_Left_Corner = 'xy' Top_Right_Corner = 'Xy' Bottom_Left_Corner = 'xY' Bottom_Right_Corner = 'XY' # Hand Detector Module class HandDetector (): def __init__(self, mode:bool = False, MaxHands: int = 2, complexity: int = 1, detectconf: float = 0.5, trackconf: float = 0.5, linethikness: int = 2, filled = cv.FILLED, radius: int = 5, linecolor: tuple [int, int, int] = (52, 255, 48)) -> None: """ Initialises the hand detector. """ self.mode = mode self.MaxHands = MaxHands self.complexity = complexity self.detectconf = detectconf self.trackconf = trackconf self.linethikness = linethikness self.filled = filled self.radius = radius self.linecolor = linecolor self.hands = mphands.Hands (self.mode, self.MaxHands, self.complexity, self.detectconf, self.trackconf) # Find the hand def FindHands (self, image: np.ndarray, draw: bool = True) -> tuple [np.ndarray, bool]: """ Detects the hand. """ imgRGB = cv.cvtColor (image, cv.COLOR_BGR2RGB) self.results = self.hands.process (imgRGB) inf = False if self.results.multi_hand_landmarks != None: inf = True lmloc, hbox = self.FindLocation (image, hbox = False) # Palm cv.line (image, lmloc [0], lmloc [5], self.linecolor, self.linethikness) cv.line (image, lmloc [0], lmloc [9], self.linecolor, self.linethikness) cv.line (image, lmloc [0], lmloc [13], self.linecolor, self.linethikness) cv.line (image, lmloc [0], lmloc [17], self.linecolor, self.linethikness) cv.line (image, lmloc [5], lmloc [9], self.linecolor, self.linethikness) cv.line (image, lmloc [9], lmloc [13], self.linecolor, self.linethikness) cv.line (image, lmloc [13], lmloc [17], self.linecolor, self.linethikness) # Thumb cv.line (image, lmloc [0], lmloc [1], self.linecolor, self.linethikness) cv.line (image, lmloc [1], lmloc [2], self.linecolor, self.linethikness) cv.line (image, lmloc [2], lmloc [3], self.linecolor, self.linethikness) cv.line (image, lmloc [3], lmloc [4], self.linecolor, self.linethikness) # Index finger cv.line (image, lmloc [5], lmloc [6], self.linecolor, self.linethikness) cv.line (image, lmloc [6], lmloc [7], self.linecolor, self.linethikness) cv.line (image, lmloc [7], lmloc [8], self.linecolor, self.linethikness) # Index finger cv.line (image, lmloc [9], lmloc [10], self.linecolor, self.linethikness) cv.line (image, lmloc [10], lmloc [11], self.linecolor, self.linethikness) cv.line (image, lmloc [11], lmloc [12], self.linecolor, self.linethikness) # Index finger cv.line (image, lmloc [13], lmloc [14], self.linecolor, self.linethikness) cv.line (image, lmloc [14], lmloc [15], self.linecolor, self.linethikness) cv.line (image, lmloc [15], lmloc [16], self.linecolor, self.linethikness) # Index finger cv.line (image, lmloc [17], lmloc [18], self.linecolor, self.linethikness) cv.line (image, lmloc [18], lmloc [19], self.linecolor, self.linethikness) cv.line (image, lmloc [19], lmloc [20], self.linecolor, self.linethikness) # Landmarks for i in range (21): cv.circle (image, lmloc [i], 4, (0, 0, 255), self.filled) cv.circle (image, lmloc [i], 6, (255, 255, 255), 1) return image, inf # Find location of hand landmarks def FindLocation (self, image: np.ndarray, Hands = "one", hbox: bool = True) -> tuple [dict [int, tuple [int, int]], dict [str, tuple [int, int]]]: """ Finds the location of the hand and the hand landmarks. """ self.lmloc = {} handloc = {} xloc = [] yloc = [] # Creating landmark: coordinate dictionary if self.results.multi_hand_landmarks != None: if Hands.lower () == "one": hand = self.results.multi_hand_landmarks [0] if Hands.lower () == "both": hand = self.results.multi_hand_landmarks for id, lm in enumerate (hand.landmark): h, w, c = image.shape cx, cy = int (lm.x * w), int (lm.y * h) self.lmloc [id] = (cx, cy) # finding the hand and packing it in a box if len (self.lmloc) >= 1: for i in range (21): xloc.append (self.lmloc [i][0]) yloc.append (self.lmloc [i][1]) box_R_x = min (xloc) box_R_y = min (yloc) handloc [CornerPoints.Top_Left_Corner] = (box_R_x, box_R_y) box_L_X = max (xloc) box_L_y = min (yloc) handloc [CornerPoints.Top_Right_Corner] = (box_L_X, box_L_y) box_r_x = min (xloc) box_r_Y = max (yloc) handloc [CornerPoints.Bottom_Left_Corner] = (box_r_x, box_r_Y) box_l_X = max (xloc) box_l_Y = max (yloc) handloc [CornerPoints.Bottom_Right_Corner] = (box_l_X, box_l_Y) # Making the box if hbox: cv.rectangle (image, (handloc [CornerPoints.Top_Left_Corner][0], handloc [CornerPoints.Top_Left_Corner][1]), (handloc [CornerPoints.Bottom_Right_Corner][0], handloc [CornerPoints.Bottom_Right_Corner][1]), self.linecolor, self.linethikness) return self.lmloc, handloc # Draw hand landmarks def DrawLandmarks (self, image: np.ndarray, index: int, loclist: dict [int, tuple [int, int]] = False, prnt: bool = False, color: tuple [int, int, int] = (255, 0, 255)) -> None: if not loclist: loclist = self.lmloc cv.circle (image, (loclist [index][0], loclist [index][1]), self.radius, color, self.filled) if not index: for i in len (loclist): cv.circle (image, (loclist [i][0], loclist [i][1]), self.radius, color, self.filled) if prnt: print (f"{index}: {loclist [index]}") # Detect if any finger is up ! def fingersUp (self, image: np.ndarray, loclist: dict [int, tuple [int, int]] = False, Draw: bool = False) -> dict [str, bool]: """ Working ------- It takes the distance between the `TIP` [4, 8, 12, 16, 20] of a finger and the `MCP` [1, 5, 9, 13, 17] point. Then after a certain range it detects it as the `finger is up`. Returns ------- It returns the information in the format of a dict consist of five `str` (finger names) and `bool` values. """ inf = {Fingers.THUMB: False, Fingers.INDEX_FINGER: False, Fingers.MIDDLE_FINGER: False, Fingers.RING_FINGER: False, Fingers.PINKY: False} if not loclist: loclist = self.lmloc # Thumb image, dist = self.findDistance (image, loclist, HandLandmark.THUMB_TIP, HandLandmark.THUMB_MCP, Draw) dist = int (dist) if dist >= 69: inf [Fingers.THUMB] = True else: inf [Fingers.THUMB] = False # Index finger image, dist = self.findDistance (image, loclist, HandLandmark.INDEX_FINGER_TIP, HandLandmark.INDEX_FINGER_MCP, Draw) dist = int (dist) if dist >= 100: inf [Fingers.INDEX_FINGER] = True else: inf [Fingers.INDEX_FINGER] = False # Middle finger image, dist = self.findDistance (image, loclist, HandLandmark.MIDDLE_FINGER_TIP, HandLandmark.MIDDLE_FINGER_MCP, Draw) dist = int (dist) if dist >= 110: inf [Fingers.MIDDLE_FINGER] = True else: inf [Fingers.MIDDLE_FINGER] = False # Ring finger image, dist = self.findDistance (image, loclist, HandLandmark.RING_FINGER_TIP, HandLandmark.RING_FINGER_MCP, Draw) dist = int (dist) if dist >= 100: inf [Fingers.RING_FINGER] = True else: inf [Fingers.RING_FINGER] = False # Pinky image, dist = self.findDistance (image, loclist, HandLandmark.PINKY_TIP, HandLandmark.PINKY_MCP, Draw) dist = int (dist) if dist >= 70: inf [Fingers.PINKY] = True else: inf [Fingers.PINKY] = False return inf # Detect if any finger is up ! def fingersUp_PROTO (self, loclist: dict [int, tuple [int, int]] = False) -> dict [str, bool]: """ Working ------- It takes the location of the `TIP` [8, 12, 16, 20] of a finger and the `DIP` [7, 11, 15, 19]. Then after a certain range it detects it as the `finger is up`. For the thumb, it takes the location of the `DIP` [3] and the `MCP` [2]. Returns ------- It returns the information in the format of a dict consist of five `str` (finger names) and `bool` values. """ fingers = {Fingers.THUMB: False, Fingers.INDEX_FINGER: False, Fingers.MIDDLE_FINGER: False, Fingers.RING_FINGER: False, Fingers.PINKY: False} if not loclist: loclist = self.lmloc # Thumb if loclist [HandLandmark.THUMB_DIP][0] > loclist [HandLandmark.THUMB_DIP - 1][0]: fingers [Fingers.THUMB] = True else: fingers [Fingers.THUMB] = False # Index finger if loclist [HandLandmark.INDEX_FINGER_TIP][1] < loclist [HandLandmark.INDEX_FINGER_TIP - 1][1]: fingers [Fingers.INDEX_FINGER] = True else: fingers [Fingers.INDEX_FINGER] = False # Middle finger if loclist [HandLandmark.MIDDLE_FINGER_TIP][1] < loclist [HandLandmark.MIDDLE_FINGER_TIP - 1][1]: fingers [Fingers.MIDDLE_FINGER] = True else: fingers [Fingers.MIDDLE_FINGER] = False # Ring finger if loclist [HandLandmark.RING_FINGER_TIP][1] < loclist [HandLandmark.RING_FINGER_TIP - 1][1]: fingers [Fingers.RING_FINGER] = True else: fingers [Fingers.RING_FINGER] = False # Pinky if loclist [HandLandmark.PINKY_TIP][1] < loclist [HandLandmark.PINKY_TIP - 1][1]: fingers [Fingers.PINKY] = True else: fingers [Fingers.PINKY] = False return fingers # Finds distance def findDistance (self, image: np.ndarray, loclist: dict [int, tuple [int, int]], id1: int, id2: int, draw: bool = True, col1: tuple [int, int, int] = (255, 0, 255)) -> tuple [np.ndarray, float]: """ Working ------- It takes the locations of two points and finds the ditance between them by the hypot function of the math module. Returns ------- Image with three circles drawn on it, and the length between those two points. """ point1 = (loclist [id1][0], loclist [id1][1]) point3 = (loclist [id2][0], loclist [id2][1]) point2 = ((point1 [0] + point3 [0])//2, (point1 [1] + point3 [1])//2) length = hpt (point1 [0] - point3 [0], point1 [1] - point3 [1]) # To draw if draw: col2 = (255 - col1 [0], 255 - col1 [1], 255 - col1 [2]) cv.line (image, point1, point3, col1, self.linethikness) cv.circle (image, point1, self.radius, col1, self.filled) cv.circle (image, point2, self.radius, col2, self.filled) cv.circle (image, point3, self.radius, col1, self.filled) return image, length # Safe working zone def FindingZone (self, image: np.ndarray, space: int = 100, camdim: tuple [int, int] = (640, 480), color: tuple [int, int, int] = (0, 0, 255)) -> dict [str, tuple [int, int]]: FindingZonedim = {CornerPoints.Top_Left_Corner: (space, space), CornerPoints.Top_Right_Corner: (camdim [0] - space, space), CornerPoints.Bottom_Left_Corner: (space, camdim [1] - space), CornerPoints.Bottom_Right_Corner: (camdim [0] - space, camdim [1] - space)} cv.rectangle (image, FindingZonedim [CornerPoints.Top_Left_Corner], FindingZonedim [CornerPoints.Bottom_Right_Corner], color, self.linethikness) return FindingZonedim # Put text with a background def PutText (image: np.ndarray, txt: str, loc: tuple [int, int], font = cv.FONT_HERSHEY_COMPLEX, fontscale: int = 1, FontColor: tuple [int, int, int] = (255, 255, 255), BGColor: tuple [int, int, int] = (0, 0, 0), BorderColor: tuple [int, int, int] = (0, 0, 255), FontThikness: int = 2, BorderThikness: int = 2, BoardWidth: int = 200, BoardHeight: int = 55) -> None: # Rectangle dimentions rectdim = {CornerPoints.Top_Left_Corner: (loc [0], loc [1]), CornerPoints.Top_Right_Corner: (loc [0] + BoardWidth, loc [1]), CornerPoints.Bottom_Left_Corner: (loc [0], loc [1] + BoardHeight), CornerPoints.Bottom_Right_Corner: (loc [0] + BoardWidth, loc [1] + BoardHeight)} # Rectangle cv.rectangle (image, (rectdim [CornerPoints.Top_Left_Corner][0], rectdim [CornerPoints.Top_Left_Corner][1]), (rectdim [CornerPoints.Bottom_Right_Corner][0], rectdim [CornerPoints.Bottom_Right_Corner][1]), BGColor, cv.FILLED) # Border cv.rectangle (image, (rectdim [CornerPoints.Top_Left_Corner][0], rectdim [CornerPoints.Top_Left_Corner][1]), (rectdim [CornerPoints.Bottom_Right_Corner][0], rectdim [CornerPoints.Bottom_Right_Corner][1]), BorderColor, BorderThikness) # Text cv.putText (image, txt, (loc [0] + 12, loc [1] + 37), font, fontscale, FontColor, FontThikness) # Draw volume colomn def DrawVolColomn (image: np.ndarray, cord: tuple [int, int], volume_level: int, gap: int = False, width: int = 50, camdim: tuple [int, int] = (640, 480), thikness: int = 2, bdcol: tuple [int, int, int] = (0, 0, 0), bgcol: tuple [int, int, int] = (255, 255, 255), volume_color_nrml: tuple [int, int, int] = (0, 255, 0), volume_color_abnrml: tuple [int, int, int] = (0, 136, 255)) -> int: # Volume bar dimentions VolColDim = {CornerPoints.Top_Left_Corner: cord, CornerPoints.Top_Right_Corner: (cord [0] + width, cord [1]), CornerPoints.Bottom_Left_Corner: (cord [0], camdim [1] - gap), CornerPoints.Bottom_Right_Corner: (cord [0] + width, camdim [1] - gap)} if not gap: gap = cord [1] if volume_level <= 100: volume_color = volume_color_nrml if volume_level > 100 and volume_level <= 150: volume_color = volume_color_abnrml volume_level_cord = (cord [0], np.interp (volume_level, (0, 150), (VolColDim [CornerPoints.Top_Left_Corner][1], VolColDim [CornerPoints.Bottom_Left_Corner][1]))) LabelCord = (cord [0], VolColDim [CornerPoints.Top_Left_Corner][1] - VolColDim [CornerPoints.Bottom_Left_Corner][1]) # Volume bar cv.rectangle (image, VolColDim [CornerPoints.Top_Left_Corner], VolColDim [CornerPoints.Bottom_Right_Corner], bgcol, cv.FILLED) # volume level cv.rectangle (image, VolColDim [CornerPoints.Bottom_Right_Corner], volume_level_cord, volume_color, cv.FILLED) # Volume bar border cv.rectangle (image, VolColDim [CornerPoints.Top_Left_Corner], VolColDim [CornerPoints.Bottom_Right_Corner], bdcol, thikness) # Volume percentage cv.putText (image, f"{volume_level}%", LabelCord, cv.FONT_HERSHEY_COMPLEX, 1, bgcol, 2) return volume_level # main def main (): ptime = 0 cam = cv.VideoCapture (0) detector = HandDetector () while True: try: success, img = cam.read () img = detector.FindHands (img) loc, hbox = detector.FindLocation (img) if len (loc) != 0: detector.DrawLandmarks (img) ctime = tm.time () fps = 1/(ctime - ptime) ptime = ctime PutText (img, f"FPS: {round (fps, 2)}", loc = (20, 40)) cv.imshow ("Webcam", img) cv.waitKey (1) except KeyboardInterrupt: print ('') exit () if __name__ == "__main__": main () # THE END
[ "cv2.rectangle", "cv2.line", "cv2.putText", "cv2.imshow", "cv2.circle", "cv2.waitKey", "cv2.VideoCapture", "cv2.cvtColor", "mediapipe.python.solutions.hands.Hands", "numpy.interp", "math.hypot", "time.time" ]
[((16800, 17033), 'cv2.rectangle', 'cv.rectangle', (['image', '(rectdim[CornerPoints.Top_Left_Corner][0], rectdim[CornerPoints.\n Top_Left_Corner][1])', '(rectdim[CornerPoints.Bottom_Right_Corner][0], rectdim[CornerPoints.\n Bottom_Right_Corner][1])', 'BGColor', 'cv.FILLED'], {}), '(image, (rectdim[CornerPoints.Top_Left_Corner][0], rectdim[\n CornerPoints.Top_Left_Corner][1]), (rectdim[CornerPoints.\n Bottom_Right_Corner][0], rectdim[CornerPoints.Bottom_Right_Corner][1]),\n BGColor, cv.FILLED)\n', (16812, 17033), True, 'import cv2 as cv\n'), ((17043, 17285), 'cv2.rectangle', 'cv.rectangle', (['image', '(rectdim[CornerPoints.Top_Left_Corner][0], rectdim[CornerPoints.\n Top_Left_Corner][1])', '(rectdim[CornerPoints.Bottom_Right_Corner][0], rectdim[CornerPoints.\n Bottom_Right_Corner][1])', 'BorderColor', 'BorderThikness'], {}), '(image, (rectdim[CornerPoints.Top_Left_Corner][0], rectdim[\n CornerPoints.Top_Left_Corner][1]), (rectdim[CornerPoints.\n Bottom_Right_Corner][0], rectdim[CornerPoints.Bottom_Right_Corner][1]),\n BorderColor, BorderThikness)\n', (17055, 17285), True, 'import cv2 as cv\n'), ((17293, 17389), 'cv2.putText', 'cv.putText', (['image', 'txt', '(loc[0] + 12, loc[1] + 37)', 'font', 'fontscale', 'FontColor', 'FontThikness'], {}), '(image, txt, (loc[0] + 12, loc[1] + 37), font, fontscale,\n FontColor, FontThikness)\n', (17303, 17389), True, 'import cv2 as cv\n'), ((18647, 18775), 'cv2.rectangle', 'cv.rectangle', (['image', 'VolColDim[CornerPoints.Top_Left_Corner]', 'VolColDim[CornerPoints.Bottom_Right_Corner]', 'bgcol', 'cv.FILLED'], {}), '(image, VolColDim[CornerPoints.Top_Left_Corner], VolColDim[\n CornerPoints.Bottom_Right_Corner], bgcol, cv.FILLED)\n', (18659, 18775), True, 'import cv2 as cv\n'), ((18798, 18910), 'cv2.rectangle', 'cv.rectangle', (['image', 'VolColDim[CornerPoints.Bottom_Right_Corner]', 'volume_level_cord', 'volume_color', 'cv.FILLED'], {}), '(image, VolColDim[CornerPoints.Bottom_Right_Corner],\n volume_level_cord, volume_color, cv.FILLED)\n', (18810, 18910), True, 'import cv2 as cv\n'), ((18938, 19065), 'cv2.rectangle', 'cv.rectangle', (['image', 'VolColDim[CornerPoints.Top_Left_Corner]', 'VolColDim[CornerPoints.Bottom_Right_Corner]', 'bdcol', 'thikness'], {}), '(image, VolColDim[CornerPoints.Top_Left_Corner], VolColDim[\n CornerPoints.Bottom_Right_Corner], bdcol, thikness)\n', (18950, 19065), True, 'import cv2 as cv\n'), ((19093, 19183), 'cv2.putText', 'cv.putText', (['image', 'f"""{volume_level}%"""', 'LabelCord', 'cv.FONT_HERSHEY_COMPLEX', '(1)', 'bgcol', '(2)'], {}), "(image, f'{volume_level}%', LabelCord, cv.FONT_HERSHEY_COMPLEX, 1,\n bgcol, 2)\n", (19103, 19183), True, 'import cv2 as cv\n'), ((19252, 19270), 'cv2.VideoCapture', 'cv.VideoCapture', (['(0)'], {}), '(0)\n', (19267, 19270), True, 'import cv2 as cv\n'), ((4423, 4516), 'mediapipe.python.solutions.hands.Hands', 'mphands.Hands', (['self.mode', 'self.MaxHands', 'self.complexity', 'self.detectconf', 'self.trackconf'], {}), '(self.mode, self.MaxHands, self.complexity, self.detectconf,\n self.trackconf)\n', (4436, 4516), True, 'import mediapipe.python.solutions.hands as mphands\n'), ((4695, 4731), 'cv2.cvtColor', 'cv.cvtColor', (['image', 'cv.COLOR_BGR2RGB'], {}), '(image, cv.COLOR_BGR2RGB)\n', (4706, 4731), True, 'import cv2 as cv\n'), ((9562, 9655), 'cv2.circle', 'cv.circle', (['image', '(loclist[index][0], loclist[index][1])', 'self.radius', 'color', 'self.filled'], {}), '(image, (loclist[index][0], loclist[index][1]), self.radius, color,\n self.filled)\n', (9571, 9655), True, 'import cv2 as cv\n'), ((14818, 14867), 'math.hypot', 'hpt', (['(point1[0] - point3[0])', '(point1[1] - point3[1])'], {}), '(point1[0] - point3[0], point1[1] - point3[1])\n', (14821, 14867), True, 'from math import hypot as hpt\n'), ((15854, 15999), 'cv2.rectangle', 'cv.rectangle', (['image', 'FindingZonedim[CornerPoints.Top_Left_Corner]', 'FindingZonedim[CornerPoints.Bottom_Right_Corner]', 'color', 'self.linethikness'], {}), '(image, FindingZonedim[CornerPoints.Top_Left_Corner],\n FindingZonedim[CornerPoints.Bottom_Right_Corner], color, self.linethikness)\n', (15866, 15999), True, 'import cv2 as cv\n'), ((18373, 18504), 'numpy.interp', 'np.interp', (['volume_level', '(0, 150)', '(VolColDim[CornerPoints.Top_Left_Corner][1], VolColDim[CornerPoints.\n Bottom_Left_Corner][1])'], {}), '(volume_level, (0, 150), (VolColDim[CornerPoints.Top_Left_Corner][\n 1], VolColDim[CornerPoints.Bottom_Left_Corner][1]))\n', (18382, 18504), True, 'import numpy as np\n'), ((4981, 5050), 'cv2.line', 'cv.line', (['image', 'lmloc[0]', 'lmloc[5]', 'self.linecolor', 'self.linethikness'], {}), '(image, lmloc[0], lmloc[5], self.linecolor, self.linethikness)\n', (4988, 5050), True, 'import cv2 as cv\n'), ((5066, 5135), 'cv2.line', 'cv.line', (['image', 'lmloc[0]', 'lmloc[9]', 'self.linecolor', 'self.linethikness'], {}), '(image, lmloc[0], lmloc[9], self.linecolor, self.linethikness)\n', (5073, 5135), True, 'import cv2 as cv\n'), ((5151, 5221), 'cv2.line', 'cv.line', (['image', 'lmloc[0]', 'lmloc[13]', 'self.linecolor', 'self.linethikness'], {}), '(image, lmloc[0], lmloc[13], self.linecolor, self.linethikness)\n', (5158, 5221), True, 'import cv2 as cv\n'), ((5237, 5307), 'cv2.line', 'cv.line', (['image', 'lmloc[0]', 'lmloc[17]', 'self.linecolor', 'self.linethikness'], {}), '(image, lmloc[0], lmloc[17], self.linecolor, self.linethikness)\n', (5244, 5307), True, 'import cv2 as cv\n'), ((5323, 5392), 'cv2.line', 'cv.line', (['image', 'lmloc[5]', 'lmloc[9]', 'self.linecolor', 'self.linethikness'], {}), '(image, lmloc[5], lmloc[9], self.linecolor, self.linethikness)\n', (5330, 5392), True, 'import cv2 as cv\n'), ((5408, 5478), 'cv2.line', 'cv.line', (['image', 'lmloc[9]', 'lmloc[13]', 'self.linecolor', 'self.linethikness'], {}), '(image, lmloc[9], lmloc[13], self.linecolor, self.linethikness)\n', (5415, 5478), True, 'import cv2 as cv\n'), ((5494, 5565), 'cv2.line', 'cv.line', (['image', 'lmloc[13]', 'lmloc[17]', 'self.linecolor', 'self.linethikness'], {}), '(image, lmloc[13], lmloc[17], self.linecolor, self.linethikness)\n', (5501, 5565), True, 'import cv2 as cv\n'), ((5602, 5671), 'cv2.line', 'cv.line', (['image', 'lmloc[0]', 'lmloc[1]', 'self.linecolor', 'self.linethikness'], {}), '(image, lmloc[0], lmloc[1], self.linecolor, self.linethikness)\n', (5609, 5671), True, 'import cv2 as cv\n'), ((5687, 5756), 'cv2.line', 'cv.line', (['image', 'lmloc[1]', 'lmloc[2]', 'self.linecolor', 'self.linethikness'], {}), '(image, lmloc[1], lmloc[2], self.linecolor, self.linethikness)\n', (5694, 5756), True, 'import cv2 as cv\n'), ((5772, 5841), 'cv2.line', 'cv.line', (['image', 'lmloc[2]', 'lmloc[3]', 'self.linecolor', 'self.linethikness'], {}), '(image, lmloc[2], lmloc[3], self.linecolor, self.linethikness)\n', (5779, 5841), True, 'import cv2 as cv\n'), ((5857, 5926), 'cv2.line', 'cv.line', (['image', 'lmloc[3]', 'lmloc[4]', 'self.linecolor', 'self.linethikness'], {}), '(image, lmloc[3], lmloc[4], self.linecolor, self.linethikness)\n', (5864, 5926), True, 'import cv2 as cv\n'), ((5970, 6039), 'cv2.line', 'cv.line', (['image', 'lmloc[5]', 'lmloc[6]', 'self.linecolor', 'self.linethikness'], {}), '(image, lmloc[5], lmloc[6], self.linecolor, self.linethikness)\n', (5977, 6039), True, 'import cv2 as cv\n'), ((6055, 6124), 'cv2.line', 'cv.line', (['image', 'lmloc[6]', 'lmloc[7]', 'self.linecolor', 'self.linethikness'], {}), '(image, lmloc[6], lmloc[7], self.linecolor, self.linethikness)\n', (6062, 6124), True, 'import cv2 as cv\n'), ((6140, 6209), 'cv2.line', 'cv.line', (['image', 'lmloc[7]', 'lmloc[8]', 'self.linecolor', 'self.linethikness'], {}), '(image, lmloc[7], lmloc[8], self.linecolor, self.linethikness)\n', (6147, 6209), True, 'import cv2 as cv\n'), ((6253, 6323), 'cv2.line', 'cv.line', (['image', 'lmloc[9]', 'lmloc[10]', 'self.linecolor', 'self.linethikness'], {}), '(image, lmloc[9], lmloc[10], self.linecolor, self.linethikness)\n', (6260, 6323), True, 'import cv2 as cv\n'), ((6339, 6410), 'cv2.line', 'cv.line', (['image', 'lmloc[10]', 'lmloc[11]', 'self.linecolor', 'self.linethikness'], {}), '(image, lmloc[10], lmloc[11], self.linecolor, self.linethikness)\n', (6346, 6410), True, 'import cv2 as cv\n'), ((6426, 6497), 'cv2.line', 'cv.line', (['image', 'lmloc[11]', 'lmloc[12]', 'self.linecolor', 'self.linethikness'], {}), '(image, lmloc[11], lmloc[12], self.linecolor, self.linethikness)\n', (6433, 6497), True, 'import cv2 as cv\n'), ((6541, 6612), 'cv2.line', 'cv.line', (['image', 'lmloc[13]', 'lmloc[14]', 'self.linecolor', 'self.linethikness'], {}), '(image, lmloc[13], lmloc[14], self.linecolor, self.linethikness)\n', (6548, 6612), True, 'import cv2 as cv\n'), ((6628, 6699), 'cv2.line', 'cv.line', (['image', 'lmloc[14]', 'lmloc[15]', 'self.linecolor', 'self.linethikness'], {}), '(image, lmloc[14], lmloc[15], self.linecolor, self.linethikness)\n', (6635, 6699), True, 'import cv2 as cv\n'), ((6715, 6786), 'cv2.line', 'cv.line', (['image', 'lmloc[15]', 'lmloc[16]', 'self.linecolor', 'self.linethikness'], {}), '(image, lmloc[15], lmloc[16], self.linecolor, self.linethikness)\n', (6722, 6786), True, 'import cv2 as cv\n'), ((6830, 6901), 'cv2.line', 'cv.line', (['image', 'lmloc[17]', 'lmloc[18]', 'self.linecolor', 'self.linethikness'], {}), '(image, lmloc[17], lmloc[18], self.linecolor, self.linethikness)\n', (6837, 6901), True, 'import cv2 as cv\n'), ((6917, 6988), 'cv2.line', 'cv.line', (['image', 'lmloc[18]', 'lmloc[19]', 'self.linecolor', 'self.linethikness'], {}), '(image, lmloc[18], lmloc[19], self.linecolor, self.linethikness)\n', (6924, 6988), True, 'import cv2 as cv\n'), ((7004, 7075), 'cv2.line', 'cv.line', (['image', 'lmloc[19]', 'lmloc[20]', 'self.linecolor', 'self.linethikness'], {}), '(image, lmloc[19], lmloc[20], self.linecolor, self.linethikness)\n', (7011, 7075), True, 'import cv2 as cv\n'), ((8999, 9247), 'cv2.rectangle', 'cv.rectangle', (['image', '(handloc[CornerPoints.Top_Left_Corner][0], handloc[CornerPoints.\n Top_Left_Corner][1])', '(handloc[CornerPoints.Bottom_Right_Corner][0], handloc[CornerPoints.\n Bottom_Right_Corner][1])', 'self.linecolor', 'self.linethikness'], {}), '(image, (handloc[CornerPoints.Top_Left_Corner][0], handloc[\n CornerPoints.Top_Left_Corner][1]), (handloc[CornerPoints.\n Bottom_Right_Corner][0], handloc[CornerPoints.Bottom_Right_Corner][1]),\n self.linecolor, self.linethikness)\n', (9011, 9247), True, 'import cv2 as cv\n'), ((14990, 15045), 'cv2.line', 'cv.line', (['image', 'point1', 'point3', 'col1', 'self.linethikness'], {}), '(image, point1, point3, col1, self.linethikness)\n', (14997, 15045), True, 'import cv2 as cv\n'), ((15060, 15116), 'cv2.circle', 'cv.circle', (['image', 'point1', 'self.radius', 'col1', 'self.filled'], {}), '(image, point1, self.radius, col1, self.filled)\n', (15069, 15116), True, 'import cv2 as cv\n'), ((15130, 15186), 'cv2.circle', 'cv.circle', (['image', 'point2', 'self.radius', 'col2', 'self.filled'], {}), '(image, point2, self.radius, col2, self.filled)\n', (15139, 15186), True, 'import cv2 as cv\n'), ((15200, 15256), 'cv2.circle', 'cv.circle', (['image', 'point3', 'self.radius', 'col1', 'self.filled'], {}), '(image, point3, self.radius, col1, self.filled)\n', (15209, 15256), True, 'import cv2 as cv\n'), ((19565, 19574), 'time.time', 'tm.time', ([], {}), '()\n', (19572, 19574), True, 'import time as tm\n'), ((19720, 19744), 'cv2.imshow', 'cv.imshow', (['"""Webcam"""', 'img'], {}), "('Webcam', img)\n", (19729, 19744), True, 'import cv2 as cv\n'), ((19758, 19771), 'cv2.waitKey', 'cv.waitKey', (['(1)'], {}), '(1)\n', (19768, 19771), True, 'import cv2 as cv\n'), ((7153, 7208), 'cv2.circle', 'cv.circle', (['image', 'lmloc[i]', '(4)', '(0, 0, 255)', 'self.filled'], {}), '(image, lmloc[i], 4, (0, 0, 255), self.filled)\n', (7162, 7208), True, 'import cv2 as cv\n'), ((7227, 7276), 'cv2.circle', 'cv.circle', (['image', 'lmloc[i]', '(6)', '(255, 255, 255)', '(1)'], {}), '(image, lmloc[i], 6, (255, 255, 255), 1)\n', (7236, 7276), True, 'import cv2 as cv\n'), ((9730, 9816), 'cv2.circle', 'cv.circle', (['image', '(loclist[i][0], loclist[i][1])', 'self.radius', 'color', 'self.filled'], {}), '(image, (loclist[i][0], loclist[i][1]), self.radius, color, self.\n filled)\n', (9739, 9816), True, 'import cv2 as cv\n')]
import numpy as np import matplotlib.pyplot as plt import matplotlib.cm as cm import pickle import gzip np.set_printoptions(threshold=np.inf) f = open('data/ACML_Movies.csv', 'r') movie_strngs = f.read() movie_strngs = movie_strngs.split('\n') movie_strngs = movie_strngs[1:] movie_strngs = movie_strngs[:-1] ratings = [] for strng in movie_strngs: split_strng = strng.split(',') rate = np.array([int(d) for d in split_strng]) ratings.append(rate) ratings = np.array(ratings) ratings = ratings[:, 1:] test_ratings = np.copy(ratings[-11:]) ratings = ratings[:-11] weights = np.random.uniform(-0.3, 0.3, (20,35*5)) learn_rate = 0.01 epochs = 400 def sigmoid(x): out = np.zeros(x.shape) for i in range(out.shape[0]): if x[i] >= 0: out[i] = 1/(1+np.exp(-x[i])) else: out[i] = np.exp(x[i])/(1+np.exp(x[i])) return out #return np.where(x >= 0, 1/(1+np.exp(-x)), np.exp(x)/(1+np.exp(x))) def softmax(x): return np.exp(x-np.max(x))/np.sum(np.exp(x-np.max(x)), axis=0) #NOTE If we using batches we will need axis=1 loss = np.array([]) div_loss = np.array([]) for k in range(epochs): #print("Starting epoch: ", k) divergence = np.array([]) for v in ratings: rate_matrix = np.zeros((v.shape[0], 5)) for i in range(v.shape[0]): if v[i] != -1: rate_matrix[i, v[i]-1] = 1 v_in = rate_matrix.reshape(35*5,) h = np.random.binomial(1,sigmoid(np.dot(weights, v_in))) pos_grad = np.dot(h.reshape(20,1), v_in.reshape(1,175)) v_prime = np.zeros((v.shape[0], 5)) vis_active = np.dot(h, weights) vis_active_matrix = vis_active.reshape(v.shape[0], 5) for movie_index in range(len(vis_active_matrix)): v_prime[movie_index] = np.random.binomial(1, softmax(vis_active_matrix[movie_index])) #v_prime = np.random.binomial(1, sigmoid(np.dot(h, weights))) for i in range(len(v)): if v[i] == -1: v_prime[i] = np.zeros(5) h_prime = np.random.binomial(1, sigmoid(np.dot(weights, v_prime.reshape(35*5,)))) neg_grad = np.dot(h_prime.reshape(20,1), v_prime.reshape(1, 175)) delta_w = pos_grad - neg_grad weights = weights + (learn_rate * delta_w) divergence = np.append(divergence, delta_w) epoch_div = np.abs(np.mean(divergence)) div_loss = np.append(div_loss, epoch_div) new_ratings = np.array([]) for v in test_ratings: rate_matrix = np.zeros((v.shape[0], 5)) for i in range(v.shape[0]): if np.random.randint(0,100) > 3: rate_matrix[i, v[i]-1] = 1 v_in = rate_matrix.reshape(35*5,) h = np.random.binomial(1,sigmoid(np.dot(weights, v_in))) pos_grad = np.dot(h.reshape(20,1), v_in.reshape(1,175)) v_prime = np.zeros((v.shape[0], 5)) vis_active = np.dot(h, weights) vis_active_matrix = vis_active.reshape(v.shape[0], 5) for movie_index in range(len(vis_active_matrix)): v_prime[movie_index] = np.random.binomial(1, softmax(vis_active_matrix[movie_index])) new_entry = np.argmax(v_prime, axis=1) new_ratings = np.append(new_ratings, new_entry + 1) new_ratings = new_ratings.reshape(11, 35) new_loss = np.mean(np.power(new_ratings - test_ratings, 2)) loss = np.append(loss, new_loss) print("Epoch ", k, " Loss: ", new_loss) plt.figure() plt.plot(loss) plt.xlabel('Epoch') plt.ylabel('Loss') plt.savefig("Movies_loss.png") plt.figure() plt.plot(div_loss) plt.xlabel('Epoch') plt.ylabel('CD Loss') plt.savefig("Movies_cd_loss.png") new_ratings = np.array([]) for v in ratings: rate_matrix = np.zeros((v.shape[0], 5)) for i in range(v.shape[0]): if v[i] != -1: rate_matrix[i, v[i]-1] = 1 v_in = rate_matrix.reshape(35*5,) h = np.random.binomial(1,sigmoid(np.dot(weights, v_in))) pos_grad = np.dot(h.reshape(20,1), v_in.reshape(1,175)) v_prime = np.zeros((v.shape[0], 5)) vis_active = np.dot(h, weights) vis_active_matrix = vis_active.reshape(v.shape[0], 5) for movie_index in range(len(vis_active_matrix)): v_prime[movie_index] = np.random.binomial(1, softmax(vis_active_matrix[movie_index])) new_entry = np.argmax(v_prime, axis=1) new_ratings = np.append(new_ratings, new_entry) new_ratings = new_ratings + 1 new_ratings = new_ratings.reshape(ratings.shape) np.savetxt("new_ratings.csv", new_ratings.astype(np.int16), delimiter=",")
[ "numpy.copy", "numpy.mean", "matplotlib.pyplot.savefig", "matplotlib.pyplot.ylabel", "numpy.power", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.plot", "numpy.argmax", "numpy.max", "numpy.append", "numpy.array", "matplotlib.pyplot.figure", "numpy.zeros", "numpy.dot", "numpy.exp", "nu...
[((105, 142), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'threshold': 'np.inf'}), '(threshold=np.inf)\n', (124, 142), True, 'import numpy as np\n'), ((485, 502), 'numpy.array', 'np.array', (['ratings'], {}), '(ratings)\n', (493, 502), True, 'import numpy as np\n'), ((544, 566), 'numpy.copy', 'np.copy', (['ratings[-11:]'], {}), '(ratings[-11:])\n', (551, 566), True, 'import numpy as np\n'), ((602, 644), 'numpy.random.uniform', 'np.random.uniform', (['(-0.3)', '(0.3)', '(20, 35 * 5)'], {}), '(-0.3, 0.3, (20, 35 * 5))\n', (619, 644), True, 'import numpy as np\n'), ((1062, 1074), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (1070, 1074), True, 'import numpy as np\n'), ((1086, 1098), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (1094, 1098), True, 'import numpy as np\n'), ((3588, 3600), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (3598, 3600), True, 'import matplotlib.pyplot as plt\n'), ((3601, 3615), 'matplotlib.pyplot.plot', 'plt.plot', (['loss'], {}), '(loss)\n', (3609, 3615), True, 'import matplotlib.pyplot as plt\n'), ((3616, 3635), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Epoch"""'], {}), "('Epoch')\n", (3626, 3635), True, 'import matplotlib.pyplot as plt\n'), ((3636, 3654), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Loss"""'], {}), "('Loss')\n", (3646, 3654), True, 'import matplotlib.pyplot as plt\n'), ((3655, 3685), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""Movies_loss.png"""'], {}), "('Movies_loss.png')\n", (3666, 3685), True, 'import matplotlib.pyplot as plt\n'), ((3687, 3699), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (3697, 3699), True, 'import matplotlib.pyplot as plt\n'), ((3700, 3718), 'matplotlib.pyplot.plot', 'plt.plot', (['div_loss'], {}), '(div_loss)\n', (3708, 3718), True, 'import matplotlib.pyplot as plt\n'), ((3719, 3738), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Epoch"""'], {}), "('Epoch')\n", (3729, 3738), True, 'import matplotlib.pyplot as plt\n'), ((3739, 3760), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""CD Loss"""'], {}), "('CD Loss')\n", (3749, 3760), True, 'import matplotlib.pyplot as plt\n'), ((3761, 3794), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""Movies_cd_loss.png"""'], {}), "('Movies_cd_loss.png')\n", (3772, 3794), True, 'import matplotlib.pyplot as plt\n'), ((3810, 3822), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (3818, 3822), True, 'import numpy as np\n'), ((698, 715), 'numpy.zeros', 'np.zeros', (['x.shape'], {}), '(x.shape)\n', (706, 715), True, 'import numpy as np\n'), ((1182, 1194), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (1190, 1194), True, 'import numpy as np\n'), ((2474, 2504), 'numpy.append', 'np.append', (['div_loss', 'epoch_div'], {}), '(div_loss, epoch_div)\n', (2483, 2504), True, 'import numpy as np\n'), ((2528, 2540), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (2536, 2540), True, 'import numpy as np\n'), ((3513, 3538), 'numpy.append', 'np.append', (['loss', 'new_loss'], {}), '(loss, new_loss)\n', (3522, 3538), True, 'import numpy as np\n'), ((3856, 3881), 'numpy.zeros', 'np.zeros', (['(v.shape[0], 5)'], {}), '((v.shape[0], 5))\n', (3864, 3881), True, 'import numpy as np\n'), ((4119, 4144), 'numpy.zeros', 'np.zeros', (['(v.shape[0], 5)'], {}), '((v.shape[0], 5))\n', (4127, 4144), True, 'import numpy as np\n'), ((4159, 4177), 'numpy.dot', 'np.dot', (['h', 'weights'], {}), '(h, weights)\n', (4165, 4177), True, 'import numpy as np\n'), ((4385, 4411), 'numpy.argmax', 'np.argmax', (['v_prime'], {'axis': '(1)'}), '(v_prime, axis=1)\n', (4394, 4411), True, 'import numpy as np\n'), ((4427, 4460), 'numpy.append', 'np.append', (['new_ratings', 'new_entry'], {}), '(new_ratings, new_entry)\n', (4436, 4460), True, 'import numpy as np\n'), ((1247, 1272), 'numpy.zeros', 'np.zeros', (['(v.shape[0], 5)'], {}), '((v.shape[0], 5))\n', (1255, 1272), True, 'import numpy as np\n'), ((1596, 1621), 'numpy.zeros', 'np.zeros', (['(v.shape[0], 5)'], {}), '((v.shape[0], 5))\n', (1604, 1621), True, 'import numpy as np\n'), ((1647, 1665), 'numpy.dot', 'np.dot', (['h', 'weights'], {}), '(h, weights)\n', (1653, 1665), True, 'import numpy as np\n'), ((2376, 2406), 'numpy.append', 'np.append', (['divergence', 'delta_w'], {}), '(divergence, delta_w)\n', (2385, 2406), True, 'import numpy as np\n'), ((2434, 2453), 'numpy.mean', 'np.mean', (['divergence'], {}), '(divergence)\n', (2441, 2453), True, 'import numpy as np\n'), ((2598, 2623), 'numpy.zeros', 'np.zeros', (['(v.shape[0], 5)'], {}), '((v.shape[0], 5))\n', (2606, 2623), True, 'import numpy as np\n'), ((2965, 2990), 'numpy.zeros', 'np.zeros', (['(v.shape[0], 5)'], {}), '((v.shape[0], 5))\n', (2973, 2990), True, 'import numpy as np\n'), ((3016, 3034), 'numpy.dot', 'np.dot', (['h', 'weights'], {}), '(h, weights)\n', (3022, 3034), True, 'import numpy as np\n'), ((3289, 3315), 'numpy.argmax', 'np.argmax', (['v_prime'], {'axis': '(1)'}), '(v_prime, axis=1)\n', (3298, 3315), True, 'import numpy as np\n'), ((3342, 3379), 'numpy.append', 'np.append', (['new_ratings', '(new_entry + 1)'], {}), '(new_ratings, new_entry + 1)\n', (3351, 3379), True, 'import numpy as np\n'), ((3457, 3496), 'numpy.power', 'np.power', (['(new_ratings - test_ratings)', '(2)'], {}), '(new_ratings - test_ratings, 2)\n', (3465, 3496), True, 'import numpy as np\n'), ((4027, 4048), 'numpy.dot', 'np.dot', (['weights', 'v_in'], {}), '(weights, v_in)\n', (4033, 4048), True, 'import numpy as np\n'), ((815, 827), 'numpy.exp', 'np.exp', (['x[i]'], {}), '(x[i])\n', (821, 827), True, 'import numpy as np\n'), ((960, 969), 'numpy.max', 'np.max', (['x'], {}), '(x)\n', (966, 969), True, 'import numpy as np\n'), ((1482, 1503), 'numpy.dot', 'np.dot', (['weights', 'v_in'], {}), '(weights, v_in)\n', (1488, 1503), True, 'import numpy as np\n'), ((2070, 2081), 'numpy.zeros', 'np.zeros', (['(5)'], {}), '(5)\n', (2078, 2081), True, 'import numpy as np\n'), ((2683, 2708), 'numpy.random.randint', 'np.random.randint', (['(0)', '(100)'], {}), '(0, 100)\n', (2700, 2708), True, 'import numpy as np\n'), ((2851, 2872), 'numpy.dot', 'np.dot', (['weights', 'v_in'], {}), '(weights, v_in)\n', (2857, 2872), True, 'import numpy as np\n'), ((780, 793), 'numpy.exp', 'np.exp', (['(-x[i])'], {}), '(-x[i])\n', (786, 793), True, 'import numpy as np\n'), ((831, 843), 'numpy.exp', 'np.exp', (['x[i]'], {}), '(x[i])\n', (837, 843), True, 'import numpy as np\n'), ((987, 996), 'numpy.max', 'np.max', (['x'], {}), '(x)\n', (993, 996), True, 'import numpy as np\n')]
""" Tests for exact diffuse initialization Notes ----- These tests are against four sources: - Koopman (1997) - The R package KFAS (v1.3.1): test_exact_diffuse_filtering.R - Stata: test_exact_diffuse_filtering_stata.do - Statsmodels state space models using approximate diffuse filtering Koopman (1997) provides analytic results for a few cases that we can test against. More comprehensive tests are available against the R package KFAS, which also uses the Durbin and Koopman (2012) univariate diffuse filtering method. However, there are apparently some bugs in the KFAS output (see notes below), so some tests are run against Stata. KFAS v1.3.1 appears to have the following bugs: - Incorrect filtered covariance matrix (in their syntax, kf$Ptt). These matrices are not even symmetric, so they are clearly wrong. - Loglikelihood computation appears to be incorrect for the diffuse part of the state. See the section with "Note: Apparent loglikelihood discrepancy" in the R file. It appears that KFAS does not include the constant term (-0.5 * log(2 pi)) for the diffuse observations, whereas the loglikelihood function as given in e.g. section 7.2.5 of Durbin and Koopman (2012) shows that it should be included. To confirm this, we also check against the loglikelihood value computed by Stata. Stata uses the DeJong diffuse filtering method, which gives almost identical results but does imply some numerical differences for output at the 6th or 7th decimal place. Finally, we have tests against the same model using approximate (rather than exact) diffuse filtering. These will by definition have some discrepancies in the diffuse observations. Author: <NAME> License: Simplified-BSD """ from __future__ import division, absolute_import, print_function import numpy as np import pandas as pd import pytest import os from statsmodels.tools.tools import Bunch from statsmodels import datasets from statsmodels.tsa.statespace.initialization import Initialization from statsmodels.tsa.statespace.kalman_smoother import KalmanSmoother from statsmodels.tsa.statespace.mlemodel import MLEModel from statsmodels.tsa.statespace.varmax import VARMAX from statsmodels.tsa.statespace.dynamic_factor import DynamicFactor from statsmodels.tsa.statespace.structural import UnobservedComponents from numpy.testing import assert_equal, assert_allclose import pytest from . import kfas_helpers current_path = os.path.dirname(os.path.abspath(__file__)) macrodata = datasets.macrodata.load_pandas().data macrodata.index = pd.PeriodIndex(start='1959Q1', end='2009Q3', freq='Q') # - Model definitions -------------------------------------------------------- def model_local_level(endog=None, params=None, direct=False): if endog is None: y1 = 10.2394 endog = np.r_[y1, [1] * 9] if params is None: params = [1.993, 8.253] sigma2_y, sigma2_mu = params if direct: mod = None # Construct the basic representation ssm = KalmanSmoother(k_endog=1, k_states=1, k_posdef=1) ssm.bind(endog) init = Initialization(ssm.k_states, initialization_type='diffuse') ssm.initialize(init) # ssm.filter_univariate = True # should not be required # Fill in the system matrices for a local level model ssm['design', :] = 1 ssm['obs_cov', :] = sigma2_y ssm['transition', :] = 1 ssm['selection', :] = 1 ssm['state_cov', :] = sigma2_mu else: mod = UnobservedComponents(endog, 'llevel') mod.update(params) ssm = mod.ssm ssm.initialize(Initialization(ssm.k_states, 'diffuse')) return mod, ssm def model_local_linear_trend(endog=None, params=None, direct=False): if endog is None: y1 = 10.2394 y2 = 4.2039 y3 = 6.123123 endog = np.r_[y1, y2, y3, [1] * 7] if params is None: params = [1.993, 8.253, 2.334] sigma2_y, sigma2_mu, sigma2_beta = params if direct: mod = None # Construct the basic representation ssm = KalmanSmoother(k_endog=1, k_states=2, k_posdef=2) ssm.bind(endog) init = Initialization(ssm.k_states, initialization_type='diffuse') ssm.initialize(init) # ssm.filter_univariate = True # should not be required # Fill in the system matrices for a local level model ssm['design', 0, 0] = 1 ssm['obs_cov', 0, 0] = sigma2_y ssm['transition'] = np.array([[1, 1], [0, 1]]) ssm['selection'] = np.eye(2) ssm['state_cov'] = np.diag([sigma2_mu, sigma2_beta]) else: mod = UnobservedComponents(endog, 'lltrend') mod.update(params) ssm = mod.ssm ssm.initialize(Initialization(ssm.k_states, 'diffuse')) return mod, ssm def model_common_level(endog=None, params=None, restricted=False): if endog is None: y11 = 10.2394 y21 = 8.2304 endog = np.column_stack([np.r_[y11, [1] * 9], np.r_[y21, [1] * 9]]) if params is None: params = [0.1111, 3.2324] theta, sigma2_mu = params # sigma2_1 = 1 # sigma_12 = 0 # sigma2_2 = 1 if not restricted: # Construct the basic representation ssm = KalmanSmoother(k_endog=2, k_states=2, k_posdef=1) ssm.bind(endog.T) init = Initialization(ssm.k_states, initialization_type='diffuse') ssm.initialize(init) # ssm.filter_univariate = True # should not be required # Fill in the system matrices for a common trend model ssm['design'] = np.array([[1, 0], [theta, 1]]) ssm['obs_cov'] = np.eye(2) ssm['transition'] = np.eye(2) ssm['selection', 0, 0] = 1 ssm['state_cov', 0, 0] = sigma2_mu else: # Construct the basic representation ssm = KalmanSmoother(k_endog=2, k_states=1, k_posdef=1) ssm.bind(endog.T) init = Initialization(ssm.k_states, initialization_type='diffuse') ssm.initialize(init) # ssm.filter_univariate = True # should not be required # Fill in the system matrices for a local level model ssm['design'] = np.array([[1, theta]]).T ssm['obs_cov'] = np.eye(2) ssm['transition', :] = 1 ssm['selection', :] = 1 ssm['state_cov', :] = sigma2_mu return ssm def model_var1(endog=None, params=None, measurement_error=False, init=None): if endog is None: endog = (np.log( macrodata[['realgdp','realcons']]).iloc[:21].diff().iloc[1:] * 400) if params is None: params = np.r_[0.5, 0.3, 0.2, 0.4, 2**0.5, 0, 3**0.5] if measurement_error: params = np.r_[params, 4, 5] # Model mod = VARMAX(endog, order=(1, 0), trend='nc', measurement_error=measurement_error) mod.update(params) ssm = mod.ssm if init is None: init = Initialization(ssm.k_states, 'diffuse') ssm.initialize(init) return mod, ssm def model_dfm(endog=None, params=None, factor_order=2): if endog is None: endog = (np.log( macrodata[['realgdp','realcons']]).iloc[:21].diff().iloc[1:] * 400) if params is None: params = np.r_[0.5, 1., 1.5, 2., 0.9, 0.1] # Model mod = DynamicFactor(endog, k_factors=1, factor_order=factor_order) mod.update(params) ssm = mod.ssm ssm.filter_univariate = True init = Initialization(ssm.k_states, 'diffuse') ssm.initialize(init) return mod, ssm # - Analytic tests (Koopman, 1997) ------------------------------------------- class TestLocalLevelAnalytic(object): @classmethod def setup_class(cls, **kwargs): cls.mod, cls.ssm = model_local_level(**kwargs) cls.res = cls.ssm.smooth() def test_results(self): ssm = self.ssm res = self.res y1 = ssm.endog[0, 0] sigma2_y = ssm['obs_cov', 0, 0] sigma2_mu = ssm['state_cov', 0, 0] # Basic initialization variables assert_allclose(res.predicted_state_cov[0, 0, 0], 0) assert_allclose(res.predicted_diffuse_state_cov[0, 0, 0], 1) # Output of the exact diffuse initialization, see Koopman (1997) assert_allclose(res.forecasts_error[0, 0], y1) assert_allclose(res.forecasts_error_cov[0, 0, 0], sigma2_y) assert_allclose(res.forecasts_error_diffuse_cov[0, 0, 0], 1) assert_allclose(res.kalman_gain[0, 0, 0], 1) assert_allclose(res.predicted_state[0, 1], y1) assert_allclose(res.predicted_state_cov[0, 0, 1], sigma2_y + sigma2_mu) assert_allclose(res.predicted_diffuse_state_cov[0, 0, 1], 0) # Miscellaneous assert_equal(res.nobs_diffuse, 1) class TestLocalLevelAnalyticDirect(TestLocalLevelAnalytic): @classmethod def setup_class(cls): super(TestLocalLevelAnalyticDirect, cls).setup_class(direct=True) class TestLocalLinearTrendAnalytic(object): @classmethod def setup_class(cls, **kwargs): cls.mod, cls.ssm = model_local_linear_trend(**kwargs) cls.res = cls.ssm.smooth() def test_results(self): ssm = self.ssm res = self.res y1, y2, y3 = ssm.endog[0, :3] sigma2_y = ssm['obs_cov', 0, 0] sigma2_mu, sigma2_beta = np.diagonal(ssm['state_cov']) # Basic initialization variables assert_allclose(res.predicted_state_cov[..., 0], np.zeros((2, 2))) assert_allclose(res.predicted_diffuse_state_cov[..., 0], np.eye(2)) # Output of the exact diffuse initialization, see Koopman (1997) q_mu = sigma2_mu / sigma2_y q_beta = sigma2_beta / sigma2_y assert_allclose(res.forecasts_error[0, 0], y1) assert_allclose(res.kalman_gain[:, 0, 0], [1, 0]) assert_allclose(res.predicted_state[:, 1], [y1, 0]) P2 = sigma2_y * np.array([[1 + q_mu, 0], [0, q_beta]]) assert_allclose(res.predicted_state_cov[:, :, 1], P2) assert_allclose(res.predicted_diffuse_state_cov[0, 0, 1], np.ones((2, 2))) # assert_allclose(res.kalman_gain[:, 0, 1], [2, 1]) assert_allclose(res.predicted_state[:, 2], [2 * y2 - y1, y2 - y1]) P3 = sigma2_y * np.array([[5 + 2 * q_mu + q_beta, 3 + q_mu + q_beta], [3 + q_mu + q_beta, 2 + q_mu + 2 * q_beta]]) assert_allclose(res.predicted_state_cov[:, :, 2], P3) assert_allclose(res.predicted_diffuse_state_cov[:, :, 2], np.zeros((2, 2))) # Miscellaneous assert_equal(res.nobs_diffuse, 2) class TestLocalLinearTrendAnalyticDirect(TestLocalLinearTrendAnalytic): @classmethod def setup_class(cls): super(TestLocalLinearTrendAnalyticDirect, cls).setup_class(direct=True) class TestLocalLinearTrendAnalyticMissing(TestLocalLinearTrendAnalytic): @classmethod def setup_class(cls): y1 = 10.2394 y2 = np.nan y3 = 6.123123 endog = np.r_[y1, y2, y3, [1] * 7] super(TestLocalLinearTrendAnalyticMissing, cls).setup_class( endog=endog) def test_results(self): ssm = self.ssm res = self.res y1, y2, y3 = ssm.endog[0, :3] sigma2_y = ssm['obs_cov', 0, 0] sigma2_mu, sigma2_beta = np.diagonal(ssm['state_cov']) # Test output q_mu = sigma2_mu / sigma2_y q_beta = sigma2_beta / sigma2_y a4 = [1.5 * y3 - 0.5 * y1, 0.5 * y3 - 0.5 * y1] assert_allclose(res.predicted_state[:, 3], a4) P4 = sigma2_y * np.array([ [2.5 + 1.5 * q_mu + 1.25 * q_beta, 1 + 0.5 * q_mu + 1.25 * q_beta], [1 + 0.5 * q_mu + 1.25 * q_beta, 0.5 + 0.5 * q_mu + 2.25 * q_beta]]) assert_allclose(res.predicted_state_cov[:, :, 3], P4) # Miscellaneous assert_equal(res.nobs_diffuse, 3) def test_common_level_analytic(): # Analytic test using results from Koopman (1997), section 5.3 mod = model_common_level() y11, y21 = mod.endog[:, 0] theta = mod['design', 1, 0] sigma2_mu = mod['state_cov', 0, 0] # Perform filtering res = mod.smooth() # Basic initialization variables assert_allclose(res.predicted_state_cov[..., 0], np.zeros((2, 2))) assert_allclose(res.predicted_diffuse_state_cov[..., 0], np.eye(2)) # Output of the exact diffuse initialization, see Koopman (1997) # Note: since Koopman (1997) did not apply the univariate method, # forecast errors and covariances, and the Kalman gain won't match # assert_allclose(res.forecasts_error[:, 0], [y11, y21]) # assert_allclose(res.forecasts_error_cov[:, :, 0], np.eye(2)) # F_inf1 = np.array([[1, theta], # [theta, 1 + theta**2]]) # assert_allclose(res.forecasts_error_diffuse_cov[:, :, 0], F_inf1) # K0 = np.array([[1, 0], # [-theta, 1]]) # assert_allclose(res.kalman_gain[..., 0], K0) assert_allclose(res.predicted_state[:, 1], [y11, y21 - theta * y11]) P2 = np.array([[1 + sigma2_mu, -theta], [-theta, 1 + theta**2]]) assert_allclose(res.predicted_state_cov[..., 1], P2) assert_allclose(res.predicted_diffuse_state_cov[..., 1], np.zeros((2, 2))) # Miscellaneous assert_equal(res.nobs_diffuse, 1) def test_common_level_restricted_analytic(): # Analytic test using results from Koopman (1997), section 5.3, # with the restriction mu_bar = 0 mod = model_common_level(restricted=True) y11, y21 = mod.endog[:, 0] theta = mod['design', 1, 0] sigma2_mu = mod['state_cov', 0, 0] # Perform filtering res = mod.smooth() # Basic initialization variables assert_allclose(res.predicted_state_cov[..., 0], 0) assert_allclose(res.predicted_diffuse_state_cov[..., 0], 1) # Output of the exact diffuse initialization, see Koopman (1997) phi = 1 / (1 + theta**2) # Note: since Koopman (1997) did not apply the univariate method, # forecast errors and covariances, and the Kalman gain won't match # assert_allclose(res.forecasts_error[:, 0], [y11, y21]) # assert_allclose(res.forecasts_error_cov[0, 0, 0], np.eye(2)) # F_inf1 = np.array([[1, theta], # [theta, theta**2]]) # assert_allclose(res.forecasts_error_diffuse_cov[0, 0, 0], F_inf1) # assert_allclose(res.kalman_gain[..., 0], phi * np.array([1, theta])) assert_allclose(res.predicted_state[:, 1], phi * (y11 + theta * y21)) # Note: Koopman (1997) actually has phi + sigma2_mu**0.5, but that appears # to be a typo assert_allclose(res.predicted_state_cov[..., 1], phi + sigma2_mu) assert_allclose(res.predicted_diffuse_state_cov[..., 1], 0) # Miscellaneous assert_equal(res.nobs_diffuse, 1) class CheckSSMResults(object): atol = 1e-14 rtol = 1e-07 atol_diffuse = 1e-7 rtol_diffuse = None def check_object(self, actual, desired, rtol_diffuse): # Short-circuit the test if desired is set to None (which allows us to # skip testing some objects where appropriate) if actual is None or desired is None: return # Optionally apply a different relative tolerance to the periods in the # diffuse observations. # This is especially useful when testing against approximate diffuse # initialization. By definition, the first few observations will be # quite different between the exact and approximate approach for many # quantities. # Note that the absolute tolerance is also pretty low (1e-7), mostly # for comparison against zero values in the approximate case d = None if rtol_diffuse is None: rtol_diffuse = self.rtol_diffuse if rtol_diffuse is not None: d = self.d if rtol_diffuse != np.inf: assert_allclose(actual.T[:d], desired.T[:d], rtol=rtol_diffuse, atol=self.atol_diffuse) assert_allclose(actual.T[d:], desired.T[d:], rtol=self.rtol, atol=self.atol) # - Filtered results tests ----------------------------------------------- def test_forecasts(self, rtol_diffuse=None): actual = self.results_a.forecasts desired = self.results_a.forecasts self.check_object(actual, desired, rtol_diffuse) def test_forecasts_error(self, rtol_diffuse=None): actual = self.results_a.forecasts_error desired = self.results_a.forecasts_error self.check_object(actual, desired, rtol_diffuse) def test_forecasts_error_cov(self, rtol_diffuse=None): actual = self.results_a.forecasts_error_cov desired = self.results_b.forecasts_error_cov self.check_object(actual, desired, rtol_diffuse) def test_filtered_state(self, rtol_diffuse=1e-5): # Note: we do want to check the diffuse values here, with a reduced # tolerance. See the note before the smoothed values for additional # details. actual = self.results_a.filtered_state desired = self.results_b.filtered_state self.check_object(actual, desired, rtol_diffuse) def test_filtered_state_cov(self, rtol_diffuse=None): actual = self.results_a.filtered_state_cov desired = self.results_b.filtered_state_cov self.check_object(actual, desired, rtol_diffuse) def test_predicted_state(self, rtol_diffuse=None): actual = self.results_a.predicted_state desired = self.results_b.predicted_state self.check_object(actual, desired, rtol_diffuse) def test_predicted_state_cov(self, rtol_diffuse=None): actual = self.results_a.predicted_state_cov desired = self.results_b.predicted_state_cov self.check_object(actual, desired, rtol_diffuse) def test_kalman_gain(self, rtol_diffuse=None): actual = self.results_a.kalman_gain desired = self.results_b.kalman_gain self.check_object(actual, desired, rtol_diffuse) def test_loglike(self, rtol_diffuse=None): if np.isscalar(self.results_b.llf_obs): actual = np.sum(self.results_a.llf_obs) desired = self.results_b.llf_obs assert_allclose(actual, desired) else: actual = self.results_a.llf_obs desired = self.results_b.llf_obs self.check_object(actual, desired, rtol_diffuse) # - Smoothed output tests ------------------------------------------------ # Note: for smoothed states, we do want to check some of the diffuse values # even in the approximate case, but with reduced precision. Note also that # there are cases that demonstrate the numerical error associated with the # approximate method, and so some specific tests are overridden in certain # cases, since they would not pass. def test_smoothed_state(self, rtol_diffuse=1e-5): actual = self.results_a.smoothed_state desired = self.results_b.smoothed_state self.check_object(actual, desired, rtol_diffuse) def test_smoothed_state_cov(self, rtol_diffuse=1e-5): actual = self.results_a.smoothed_state_cov desired = self.results_b.smoothed_state_cov self.check_object(actual, desired, rtol_diffuse) def test_smoothed_state_autocov(self, rtol_diffuse=None): actual = self.results_a.smoothed_state_autocov desired = self.results_b.smoothed_state_autocov self.check_object(actual, desired, rtol_diffuse) def test_smoothed_measurement_disturbance(self, rtol_diffuse=1e-5): actual = self.results_a.smoothed_measurement_disturbance desired = self.results_b.smoothed_measurement_disturbance self.check_object(actual, desired, rtol_diffuse) def test_smoothed_measurement_disturbance_cov(self, rtol_diffuse=1e-5): actual = self.results_a.smoothed_measurement_disturbance_cov desired = self.results_b.smoothed_measurement_disturbance_cov self.check_object(actual, desired, rtol_diffuse) def test_smoothed_state_disturbance(self, rtol_diffuse=1e-5): actual = self.results_a.smoothed_state_disturbance desired = self.results_b.smoothed_state_disturbance self.check_object(actual, desired, rtol_diffuse) def test_smoothed_state_disturbance_cov(self, rtol_diffuse=1e-5): actual = self.results_a.smoothed_state_disturbance_cov desired = self.results_b.smoothed_state_disturbance_cov self.check_object(actual, desired, rtol_diffuse) # - Smoothed intermediate tests ------------------------------------------ # This isn't computed in the univariate method or by KFAS # def test_smoothing_error(self, rtol_diffuse=None): # actual = self.results_a.smoothing_error # desired = self.results_b.smoothing_error # self.check_object(actual, desired, rtol_diffuse) def test_scaled_smoothed_estimator(self, rtol_diffuse=1e-5): actual = self.results_a.scaled_smoothed_estimator desired = self.results_b.scaled_smoothed_estimator self.check_object(actual, desired, rtol_diffuse) def test_scaled_smoothed_estimator_cov(self, rtol_diffuse=1e-5): actual = self.results_a.scaled_smoothed_estimator_cov desired = self.results_b.scaled_smoothed_estimator_cov self.check_object(actual, desired, rtol_diffuse) # - Diffuse objects tests ------------------------------------------------ # Note: these can't be checked against the approximate diffuse method. def test_forecasts_error_diffuse_cov(self, rtol_diffuse=None): actual = self.results_a.forecasts_error_diffuse_cov desired = self.results_b.forecasts_error_diffuse_cov self.check_object(actual, desired, rtol_diffuse) def test_predicted_diffuse_state_cov(self, rtol_diffuse=None): actual = self.results_a.predicted_diffuse_state_cov desired = self.results_b.predicted_diffuse_state_cov self.check_object(actual, desired, rtol_diffuse) # We don't currently store this array # def test_kalman_gain_diffuse(self, rtol_diffuse=None): # actual = self.results_a. # desired = self.results_b. # self.check_object(actual, desired, rtol_diffuse) def test_scaled_smoothed_diffuse_estimator(self, rtol_diffuse=None): actual = self.results_a.scaled_smoothed_diffuse_estimator desired = self.results_b.scaled_smoothed_diffuse_estimator self.check_object(actual, desired, rtol_diffuse) def test_scaled_smoothed_diffuse1_estimator_cov(self, rtol_diffuse=None): actual = self.results_a.scaled_smoothed_diffuse1_estimator_cov desired = self.results_b.scaled_smoothed_diffuse1_estimator_cov self.check_object(actual, desired, rtol_diffuse) def test_scaled_smoothed_diffuse2_estimator_cov(self, rtol_diffuse=None): actual = self.results_a.scaled_smoothed_diffuse2_estimator_cov desired = self.results_b.scaled_smoothed_diffuse2_estimator_cov self.check_object(actual, desired, rtol_diffuse) # - Simulation smoother results tests ------------------------------------ # def test_simulation_smoothed_state(self): # assert_allclose( # self.sim_a.simulated_state, # self.sim_a.simulated_state) # def test_simulation_smoothed_measurement_disturbance(self): # assert_allclose( # self.sim_a.simulated_measurement_disturbance, # self.sim_a.simulated_measurement_disturbance) # def test_simulation_smoothed_state_disturbance(self): # assert_allclose( # self.sim_a.simulated_state_disturbance, # self.sim_a.simulated_state_disturbance) class CheckApproximateDiffuseMixin(object): """ Test the exact diffuse initialization against the approximate diffuse initialization. By definition, the first few observations will be quite different between the exact and approximate approach for many quantities, so we do not test them here. """ approximate_diffuse_variance = 1e6 @classmethod def setup_class(cls, *args, **kwargs): init_approx = kwargs.pop('init_approx', None) super(CheckApproximateDiffuseMixin, cls).setup_class(*args, **kwargs) # Get the approximate diffuse results kappa = cls.approximate_diffuse_variance if init_approx is None: init_approx = Initialization(cls.ssm.k_states, 'approximate_diffuse', approximate_diffuse_variance=kappa) cls.ssm.initialize(init_approx) cls.results_b = cls.ssm.smooth() # Instruct the tests not to test against the first d values cls.rtol_diffuse = np.inf def test_initialization_approx(self): kappa = self.approximate_diffuse_variance assert_allclose(self.results_b.initial_state_cov, np.eye(self.ssm.k_states) * kappa) assert_equal(self.results_b.initial_diffuse_state_cov, None) class CheckKFASMixin(object): """ Test against values from KFAS """ @classmethod def setup_class(cls, *args, **kwargs): kwargs.setdefault('filter_univariate', True) super(CheckKFASMixin, cls).setup_class(*args, **kwargs) # Get the KFAS results objects cls.results_b = kfas_helpers.parse(cls.results_path, cls.ssm) # Set some attributes that KFAS does not compute cls.results_b.smoothed_state_autocov = None # Remove the Kalman gain matrix since KFAS computes it using the # non-univariate method cls.results_b.kalman_gain = None # Remove the filtered_state_cov since KFAS v1.3.1 has a bug for these # matrices (they are not even symmetric) cls.results_b.filtered_state_cov = None # KFAS v1.3.1 seems to compute the loglikelihood incorrectly, so we # correct for it here # (we need to add back in the constant term for all of the non-missing # diffuse observations for which Finf is nonsingular) Finf = cls.results_b.forecasts_error_diffuse_cov.T Finf_nonsingular_obs = np.c_[[np.diag(Finf_t) for Finf_t in Finf]] > 0 nonmissing = ~np.isnan(cls.ssm.endog).T constant = (-0.5 * np.log(2 * np.pi) * (Finf_nonsingular_obs * nonmissing).sum(axis=1)) cls.results_b.llf_obs += constant[:cls.results_a.nobs_diffuse].sum() # - VAR(1) ------------------------------------------------------------------- class CheckVAR1(CheckSSMResults): @classmethod def setup_class(cls, **kwargs): filter_univariate = kwargs.pop('filter_univariate', False) cls.mod, cls.ssm = model_var1(**kwargs) if filter_univariate: cls.ssm.filter_univariate = True cls.results_a = cls.ssm.smooth() cls.d = cls.results_a.nobs_diffuse def test_nobs_diffuse(self): assert_allclose(self.d, 1) def test_initialization(self): assert_allclose(self.results_a.initial_state_cov, 0) assert_allclose(self.results_a.initial_diffuse_state_cov, np.eye(2)) class TestVAR1_Approx(CheckApproximateDiffuseMixin, CheckVAR1): pass class TestVAR1_KFAS(CheckKFASMixin, CheckVAR1): results_path = os.path.join( current_path, 'results', 'results_exact_initial_var1_R.csv') # - VAR(1) + Measurement error ----------------------------------------------- class CheckVAR1MeasurementError(CheckVAR1): @classmethod def setup_class(cls, **kwargs): kwargs['measurement_error'] = True super(CheckVAR1MeasurementError, cls).setup_class(**kwargs) class TestVAR1MeasurementError_Approx(CheckApproximateDiffuseMixin, CheckVAR1MeasurementError): # Note: somewhat fragile, we need to increase the approximate variance to # 1e9 for the tests to pass at the appropriate level of precision, but # we can't increase too much more than this because then we start get # numerical errors (e.g. 1e10 is fine but 1e11 doesn't pass) approximate_diffuse_variance = 1e9 def test_smoothed_measurement_disturbance_cov(self, rtol_diffuse=None): # Note: this test would fail here with most rtol, because # this is an example where the numerical errors associated with the # approximate method result in noticeable errors # term: (x is the exact method, y is the approximate method) # x: array([[[3.355072, 0. ], # [0. , 4.221227]]]) # y: array([[[ 3.355072, -0.600856], # [-0.600856, 4.221227]]]) super(TestVAR1MeasurementError_Approx, self).test_smoothed_measurement_disturbance_cov( rtol_diffuse=rtol_diffuse) class TestVAR1MeasurementError_KFAS(CheckKFASMixin, CheckVAR1MeasurementError): results_path = os.path.join(current_path, 'results', 'results_exact_initial_var1_measurement_error_R.csv') # - VAR(1) + Missing data ---------------------------------------------------- class CheckVAR1Missing(CheckVAR1): @classmethod def setup_class(cls, **kwargs): endog = (np.log( macrodata[['realgdp','realcons']]).iloc[:21].diff().iloc[1:] * 400) endog.iloc[0:5, 0] = np.nan endog.iloc[8:12, :] = np.nan kwargs['endog'] = endog super(CheckVAR1Missing, cls).setup_class(**kwargs) def test_nobs_diffuse(self): assert_allclose(self.d, 2) class TestVAR1Missing_Approx(CheckApproximateDiffuseMixin, CheckVAR1Missing): # Note: somewhat fragile, we need to increase the approximate variance to # 1e10 for the tests to pass at the appropriate level of precision, but # we can't increase it any more than this because then we start get # numerical errors (e.g. 1e11 doesn't pass) approximate_diffuse_variance = 1e10 def test_smoothed_state_cov(self, rtol_diffuse=None): # Note: this test would fail here with essentially any rtol, because # this is an example where the numerical errors associated with the # approximate method result in extreme errors: here a negative variance # term: (x is the exact method, y is the approximate method) # x: array([[[ 5.601218e+01, 0.000000e+00], # [ 0.000000e+00, 0.000000e+00]], # ... # y: array([[[-12.083676, 0. ], # [ 0. , 0. ]], super(TestVAR1Missing_Approx, self).test_smoothed_state_cov( rtol_diffuse=rtol_diffuse) class TestVAR1Missing_KFAS(CheckKFASMixin, CheckVAR1Missing): results_path = os.path.join( current_path, 'results', 'results_exact_initial_var1_missing_R.csv') def test_forecasts_error_cov(self): # TODO: fails for the general version of forecasts_error_cov because # (1) the routines in kalman_filter.py fill in values for all variables # regardless of missing status and also it uses the multivariate # approach rather than the univariate approach, and (2) KFAS fills in # values for all variables regardless of missing status (but does use # the univariate method). # Here we remove the off-diagonal elements so that the test passes (but # note that this is **not** a general solution since it depends on # which variables are missing). bak = self.results_a.forecasts_error_cov[:] self.results_a.forecasts_error_cov[0, 1, :] = 0 self.results_a.forecasts_error_cov[1, 0, :] = 0 super(TestVAR1Missing_KFAS, self).test_forecasts_error_cov() self.results_a.forecasts_error_cov = bak # - VAR(1) + Mixed stationary / diffuse initialization ----------------------- class CheckVAR1Mixed(CheckVAR1): @classmethod def setup_class(cls, **kwargs): k_states = 2 init = Initialization(k_states) init.set(0, 'diffuse') init.set(1, 'stationary') if kwargs.pop('approx', False): init_approx = Initialization(k_states) init_approx.set(0, 'approximate_diffuse') init_approx.set(1, 'stationary') kwargs['init_approx'] = init_approx super(CheckVAR1Mixed, cls).setup_class(init=init, **kwargs) def test_nobs_diffuse(self): assert_allclose(self.d, 1) def test_initialization(self): stationary_init = 3.5714285714285716 assert_allclose(self.results_a.initial_state_cov, np.diag([0, stationary_init])) assert_allclose(self.results_a.initial_diffuse_state_cov, np.diag([1, 0])) class TestVAR1Mixed_Approx(CheckVAR1Mixed, CheckApproximateDiffuseMixin, CheckVAR1): @classmethod def setup_class(cls, **kwargs): kwargs['approx'] = True super(TestVAR1Mixed_Approx, cls).setup_class(**kwargs) def test_initialization_approx(self): stationary_init = 3.5714285714285716 kappa = self.approximate_diffuse_variance assert_allclose(self.results_b.initial_state_cov, np.diag([kappa, stationary_init])) assert_equal(self.results_b.initial_diffuse_state_cov, None) class TestVAR1Mixed_KFAS(CheckVAR1Mixed, CheckKFASMixin, CheckVAR1): # TODO: fails results_path = os.path.join( current_path, 'results', 'results_exact_initial_var1_mixed_R.csv') # TODO: KFAS disagrees for the diffuse observations for all of these # states, but it appears that they have a bug (e.g. since the approximate # diffuse case agrees with us), so we should double-check against a third # package (RATS?) def test_predicted_state(self): super(TestVAR1Mixed_KFAS, self).test_predicted_state( rtol_diffuse=np.inf) def test_filtered_state(self): super(TestVAR1Mixed_KFAS, self).test_filtered_state( rtol_diffuse=np.inf) def test_smoothed_state(self): super(TestVAR1Mixed_KFAS, self).test_smoothed_state( rtol_diffuse=np.inf) # - DFM ---------------------------------------------------------------------- class CheckDFM(CheckSSMResults): @classmethod def setup_class(cls, **kwargs): filter_univariate = kwargs.pop('filter_univariate', False) cls.mod, cls.ssm = model_dfm(**kwargs) if filter_univariate: cls.ssm.filter_univariate = True cls.results_a = cls.ssm.smooth() cls.d = cls.results_a.nobs_diffuse def test_nobs_diffuse(self): assert_allclose(self.d, 2) def test_initialization(self): assert_allclose(self.results_a.initial_state_cov, 0) assert_allclose(self.results_a.initial_diffuse_state_cov, np.eye(2)) class TestDFM_Approx(CheckApproximateDiffuseMixin, CheckDFM): # Note: somewhat fragile, we need to increase the approximate variance to # 5e10 for the tests to pass at the appropriate level of precision, but # we can't increase it too much more than this because then we start get # numerical errors (e.g. 1e11 works but 1e12 doesn't pass) approximate_diffuse_variance = 5e10 class TestDFM_KFAS(CheckKFASMixin, CheckDFM): results_path = os.path.join( current_path, 'results', 'results_exact_initial_dfm_R.csv') # TODO: KFAS disagrees for the diffuse observations for all of these # states, but it appears that they have a bug (e.g. since the approximate # diffuse case agrees with us), so we should double-check against a third # package (RATS?) def test_predicted_state(self): super(TestDFM_KFAS, self).test_predicted_state(rtol_diffuse=np.inf) def test_filtered_state(self): super(TestDFM_KFAS, self).test_filtered_state(rtol_diffuse=np.inf) def test_smoothed_state(self): super(TestDFM_KFAS, self).test_smoothed_state(rtol_diffuse=np.inf) # - DFM + Collapsed ---------------------------------------------------------- class CheckDFMCollapsed(CheckSSMResults): @classmethod def setup_class(cls, **kwargs): filter_univariate = kwargs.pop('filter_univariate', True) cls.mod, cls.ssm = model_dfm(factor_order=1, **kwargs) if filter_univariate: cls.ssm.filter_univariate = True cls.ssm.filter_collapsed = True cls.results_a = cls.ssm.smooth() cls.d = cls.results_a.nobs_diffuse def test_nobs_diffuse(self): assert_allclose(self.d, 1) def test_initialization(self): assert_allclose(self.results_a.initial_state_cov, 0) assert_allclose(self.results_a.initial_diffuse_state_cov, np.eye(1)) class TestDFMCollapsed_Approx(CheckApproximateDiffuseMixin, CheckDFMCollapsed): # Note: somewhat fragile, we need to increase the approximate variance to # 1e9 for the tests to pass at the appropriate level of precision, but # we can't increase it too much more than this because then we start get # numerical errors (e.g. 1e10 doesn't pass) approximate_diffuse_variance = 1e9 # Note: we cannot test against KFAS, since it doesn't support collapsed # filtering # class TestDFMCollapsed_KFAS(CheckKFASMixin, TestDFMCollapsed): # results_path = os.path.join( # current_path, 'results', '') # - TODO: additional tests --------------------------------------------------- # - Local level model, above # - Local linear trend model, above # - Common level model, above # - multivariate test with non-diagonal observation covariance matrix # - simulation smoother @pytest.mark.xfail def test_irrelevant_state(): # This test records a case in which exact diffuse initialization leads to # numerical problems, becuase the existence of an irrelevant state # initialized as diffuse means that there is never a transition to the # usual Kalman filter. endog = macrodata.infl spec = { 'freq_seasonal': [{'period':8, 'harmonics': 6}, {'period': 36, 'harmonics': 6}] } # Approximate diffuse version mod = UnobservedComponents(endog, 'llevel', **spec) mod.ssm.initialization = Initialization(mod.k_states,'approximate_diffuse') res = mod.smooth([3.4, 7.2, 0.01, 0.01]) # Exact diffuse version mod2 = UnobservedComponents(endog, 'llevel', **spec) mod2.ssm.filter_univariate = True mod2.ssm.initialization = Initialization(mod2.k_states, 'diffuse') res2 = mod2.smooth([3.4, 7.2, 0.01, 0.01]) # Check that e.g. the filtered state for the level is equal assert_allclose(res.filtered_state[0, 25:], res2.filtered_state[0, 25:], atol=1e-5)
[ "numpy.testing.assert_equal", "statsmodels.tsa.statespace.varmax.VARMAX", "numpy.log", "numpy.column_stack", "numpy.array", "statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother", "numpy.isscalar", "numpy.testing.assert_allclose", "numpy.diagonal", "numpy.eye", "statsmodels.tsa.statespace.d...
[((2534, 2588), 'pandas.PeriodIndex', 'pd.PeriodIndex', ([], {'start': '"""1959Q1"""', 'end': '"""2009Q3"""', 'freq': '"""Q"""'}), "(start='1959Q1', end='2009Q3', freq='Q')\n", (2548, 2588), True, 'import pandas as pd\n'), ((2439, 2464), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (2454, 2464), False, 'import os\n'), ((2478, 2510), 'statsmodels.datasets.macrodata.load_pandas', 'datasets.macrodata.load_pandas', ([], {}), '()\n', (2508, 2510), False, 'from statsmodels import datasets\n'), ((6786, 6862), 'statsmodels.tsa.statespace.varmax.VARMAX', 'VARMAX', (['endog'], {'order': '(1, 0)', 'trend': '"""nc"""', 'measurement_error': 'measurement_error'}), "(endog, order=(1, 0), trend='nc', measurement_error=measurement_error)\n", (6792, 6862), False, 'from statsmodels.tsa.statespace.varmax import VARMAX\n'), ((7325, 7385), 'statsmodels.tsa.statespace.dynamic_factor.DynamicFactor', 'DynamicFactor', (['endog'], {'k_factors': '(1)', 'factor_order': 'factor_order'}), '(endog, k_factors=1, factor_order=factor_order)\n', (7338, 7385), False, 'from statsmodels.tsa.statespace.dynamic_factor import DynamicFactor\n'), ((7471, 7510), 'statsmodels.tsa.statespace.initialization.Initialization', 'Initialization', (['ssm.k_states', '"""diffuse"""'], {}), "(ssm.k_states, 'diffuse')\n", (7485, 7510), False, 'from statsmodels.tsa.statespace.initialization import Initialization\n'), ((13050, 13118), 'numpy.testing.assert_allclose', 'assert_allclose', (['res.predicted_state[:, 1]', '[y11, y21 - theta * y11]'], {}), '(res.predicted_state[:, 1], [y11, y21 - theta * y11])\n', (13065, 13118), False, 'from numpy.testing import assert_equal, assert_allclose\n'), ((13128, 13189), 'numpy.array', 'np.array', (['[[1 + sigma2_mu, -theta], [-theta, 1 + theta ** 2]]'], {}), '([[1 + sigma2_mu, -theta], [-theta, 1 + theta ** 2]])\n', (13136, 13189), True, 'import numpy as np\n'), ((13211, 13263), 'numpy.testing.assert_allclose', 'assert_allclose', (['res.predicted_state_cov[..., 1]', 'P2'], {}), '(res.predicted_state_cov[..., 1], P2)\n', (13226, 13263), False, 'from numpy.testing import assert_equal, assert_allclose\n'), ((13368, 13401), 'numpy.testing.assert_equal', 'assert_equal', (['res.nobs_diffuse', '(1)'], {}), '(res.nobs_diffuse, 1)\n', (13380, 13401), False, 'from numpy.testing import assert_equal, assert_allclose\n'), ((13793, 13844), 'numpy.testing.assert_allclose', 'assert_allclose', (['res.predicted_state_cov[..., 0]', '(0)'], {}), '(res.predicted_state_cov[..., 0], 0)\n', (13808, 13844), False, 'from numpy.testing import assert_equal, assert_allclose\n'), ((13849, 13908), 'numpy.testing.assert_allclose', 'assert_allclose', (['res.predicted_diffuse_state_cov[..., 0]', '(1)'], {}), '(res.predicted_diffuse_state_cov[..., 0], 1)\n', (13864, 13908), False, 'from numpy.testing import assert_equal, assert_allclose\n'), ((14510, 14579), 'numpy.testing.assert_allclose', 'assert_allclose', (['res.predicted_state[:, 1]', '(phi * (y11 + theta * y21))'], {}), '(res.predicted_state[:, 1], phi * (y11 + theta * y21))\n', (14525, 14579), False, 'from numpy.testing import assert_equal, assert_allclose\n'), ((14682, 14747), 'numpy.testing.assert_allclose', 'assert_allclose', (['res.predicted_state_cov[..., 1]', '(phi + sigma2_mu)'], {}), '(res.predicted_state_cov[..., 1], phi + sigma2_mu)\n', (14697, 14747), False, 'from numpy.testing import assert_equal, assert_allclose\n'), ((14752, 14811), 'numpy.testing.assert_allclose', 'assert_allclose', (['res.predicted_diffuse_state_cov[..., 1]', '(0)'], {}), '(res.predicted_diffuse_state_cov[..., 1], 0)\n', (14767, 14811), False, 'from numpy.testing import assert_equal, assert_allclose\n'), ((14837, 14870), 'numpy.testing.assert_equal', 'assert_equal', (['res.nobs_diffuse', '(1)'], {}), '(res.nobs_diffuse, 1)\n', (14849, 14870), False, 'from numpy.testing import assert_equal, assert_allclose\n'), ((27399, 27472), 'os.path.join', 'os.path.join', (['current_path', '"""results"""', '"""results_exact_initial_var1_R.csv"""'], {}), "(current_path, 'results', 'results_exact_initial_var1_R.csv')\n", (27411, 27472), False, 'import os\n'), ((29019, 29114), 'os.path.join', 'os.path.join', (['current_path', '"""results"""', '"""results_exact_initial_var1_measurement_error_R.csv"""'], {}), "(current_path, 'results',\n 'results_exact_initial_var1_measurement_error_R.csv')\n", (29031, 29114), False, 'import os\n'), ((30791, 30876), 'os.path.join', 'os.path.join', (['current_path', '"""results"""', '"""results_exact_initial_var1_missing_R.csv"""'], {}), "(current_path, 'results',\n 'results_exact_initial_var1_missing_R.csv')\n", (30803, 30876), False, 'import os\n'), ((33488, 33567), 'os.path.join', 'os.path.join', (['current_path', '"""results"""', '"""results_exact_initial_var1_mixed_R.csv"""'], {}), "(current_path, 'results', 'results_exact_initial_var1_mixed_R.csv')\n", (33500, 33567), False, 'import os\n'), ((35369, 35441), 'os.path.join', 'os.path.join', (['current_path', '"""results"""', '"""results_exact_initial_dfm_R.csv"""'], {}), "(current_path, 'results', 'results_exact_initial_dfm_R.csv')\n", (35381, 35441), False, 'import os\n'), ((38184, 38229), 'statsmodels.tsa.statespace.structural.UnobservedComponents', 'UnobservedComponents', (['endog', '"""llevel"""'], {}), "(endog, 'llevel', **spec)\n", (38204, 38229), False, 'from statsmodels.tsa.statespace.structural import UnobservedComponents\n'), ((38259, 38310), 'statsmodels.tsa.statespace.initialization.Initialization', 'Initialization', (['mod.k_states', '"""approximate_diffuse"""'], {}), "(mod.k_states, 'approximate_diffuse')\n", (38273, 38310), False, 'from statsmodels.tsa.statespace.initialization import Initialization\n'), ((38395, 38440), 'statsmodels.tsa.statespace.structural.UnobservedComponents', 'UnobservedComponents', (['endog', '"""llevel"""'], {}), "(endog, 'llevel', **spec)\n", (38415, 38440), False, 'from statsmodels.tsa.statespace.structural import UnobservedComponents\n'), ((38509, 38549), 'statsmodels.tsa.statespace.initialization.Initialization', 'Initialization', (['mod2.k_states', '"""diffuse"""'], {}), "(mod2.k_states, 'diffuse')\n", (38523, 38549), False, 'from statsmodels.tsa.statespace.initialization import Initialization\n'), ((38666, 38754), 'numpy.testing.assert_allclose', 'assert_allclose', (['res.filtered_state[0, 25:]', 'res2.filtered_state[0, 25:]'], {'atol': '(1e-05)'}), '(res.filtered_state[0, 25:], res2.filtered_state[0, 25:],\n atol=1e-05)\n', (38681, 38754), False, 'from numpy.testing import assert_equal, assert_allclose\n'), ((2993, 3042), 'statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother', 'KalmanSmoother', ([], {'k_endog': '(1)', 'k_states': '(1)', 'k_posdef': '(1)'}), '(k_endog=1, k_states=1, k_posdef=1)\n', (3007, 3042), False, 'from statsmodels.tsa.statespace.kalman_smoother import KalmanSmoother\n'), ((3082, 3141), 'statsmodels.tsa.statespace.initialization.Initialization', 'Initialization', (['ssm.k_states'], {'initialization_type': '"""diffuse"""'}), "(ssm.k_states, initialization_type='diffuse')\n", (3096, 3141), False, 'from statsmodels.tsa.statespace.initialization import Initialization\n'), ((3494, 3531), 'statsmodels.tsa.statespace.structural.UnobservedComponents', 'UnobservedComponents', (['endog', '"""llevel"""'], {}), "(endog, 'llevel')\n", (3514, 3531), False, 'from statsmodels.tsa.statespace.structural import UnobservedComponents\n'), ((4067, 4116), 'statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother', 'KalmanSmoother', ([], {'k_endog': '(1)', 'k_states': '(2)', 'k_posdef': '(2)'}), '(k_endog=1, k_states=2, k_posdef=2)\n', (4081, 4116), False, 'from statsmodels.tsa.statespace.kalman_smoother import KalmanSmoother\n'), ((4156, 4215), 'statsmodels.tsa.statespace.initialization.Initialization', 'Initialization', (['ssm.k_states'], {'initialization_type': '"""diffuse"""'}), "(ssm.k_states, initialization_type='diffuse')\n", (4170, 4215), False, 'from statsmodels.tsa.statespace.initialization import Initialization\n'), ((4473, 4499), 'numpy.array', 'np.array', (['[[1, 1], [0, 1]]'], {}), '([[1, 1], [0, 1]])\n', (4481, 4499), True, 'import numpy as np\n'), ((4565, 4574), 'numpy.eye', 'np.eye', (['(2)'], {}), '(2)\n', (4571, 4574), True, 'import numpy as np\n'), ((4602, 4635), 'numpy.diag', 'np.diag', (['[sigma2_mu, sigma2_beta]'], {}), '([sigma2_mu, sigma2_beta])\n', (4609, 4635), True, 'import numpy as np\n'), ((4660, 4698), 'statsmodels.tsa.statespace.structural.UnobservedComponents', 'UnobservedComponents', (['endog', '"""lltrend"""'], {}), "(endog, 'lltrend')\n", (4680, 4698), False, 'from statsmodels.tsa.statespace.structural import UnobservedComponents\n'), ((4983, 5042), 'numpy.column_stack', 'np.column_stack', (['[np.r_[y11, [1] * 9], np.r_[y21, [1] * 9]]'], {}), '([np.r_[y11, [1] * 9], np.r_[y21, [1] * 9]])\n', (4998, 5042), True, 'import numpy as np\n'), ((5270, 5319), 'statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother', 'KalmanSmoother', ([], {'k_endog': '(2)', 'k_states': '(2)', 'k_posdef': '(1)'}), '(k_endog=2, k_states=2, k_posdef=1)\n', (5284, 5319), False, 'from statsmodels.tsa.statespace.kalman_smoother import KalmanSmoother\n'), ((5361, 5420), 'statsmodels.tsa.statespace.initialization.Initialization', 'Initialization', (['ssm.k_states'], {'initialization_type': '"""diffuse"""'}), "(ssm.k_states, initialization_type='diffuse')\n", (5375, 5420), False, 'from statsmodels.tsa.statespace.initialization import Initialization\n'), ((5603, 5633), 'numpy.array', 'np.array', (['[[1, 0], [theta, 1]]'], {}), '([[1, 0], [theta, 1]])\n', (5611, 5633), True, 'import numpy as np\n'), ((5693, 5702), 'numpy.eye', 'np.eye', (['(2)'], {}), '(2)\n', (5699, 5702), True, 'import numpy as np\n'), ((5731, 5740), 'numpy.eye', 'np.eye', (['(2)'], {}), '(2)\n', (5737, 5740), True, 'import numpy as np\n'), ((5888, 5937), 'statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother', 'KalmanSmoother', ([], {'k_endog': '(2)', 'k_states': '(1)', 'k_posdef': '(1)'}), '(k_endog=2, k_states=1, k_posdef=1)\n', (5902, 5937), False, 'from statsmodels.tsa.statespace.kalman_smoother import KalmanSmoother\n'), ((5979, 6038), 'statsmodels.tsa.statespace.initialization.Initialization', 'Initialization', (['ssm.k_states'], {'initialization_type': '"""diffuse"""'}), "(ssm.k_states, initialization_type='diffuse')\n", (5993, 6038), False, 'from statsmodels.tsa.statespace.initialization import Initialization\n'), ((6270, 6279), 'numpy.eye', 'np.eye', (['(2)'], {}), '(2)\n', (6276, 6279), True, 'import numpy as np\n'), ((6957, 6996), 'statsmodels.tsa.statespace.initialization.Initialization', 'Initialization', (['ssm.k_states', '"""diffuse"""'], {}), "(ssm.k_states, 'diffuse')\n", (6971, 6996), False, 'from statsmodels.tsa.statespace.initialization import Initialization\n'), ((8059, 8111), 'numpy.testing.assert_allclose', 'assert_allclose', (['res.predicted_state_cov[0, 0, 0]', '(0)'], {}), '(res.predicted_state_cov[0, 0, 0], 0)\n', (8074, 8111), False, 'from numpy.testing import assert_equal, assert_allclose\n'), ((8120, 8180), 'numpy.testing.assert_allclose', 'assert_allclose', (['res.predicted_diffuse_state_cov[0, 0, 0]', '(1)'], {}), '(res.predicted_diffuse_state_cov[0, 0, 0], 1)\n', (8135, 8180), False, 'from numpy.testing import assert_equal, assert_allclose\n'), ((8263, 8309), 'numpy.testing.assert_allclose', 'assert_allclose', (['res.forecasts_error[0, 0]', 'y1'], {}), '(res.forecasts_error[0, 0], y1)\n', (8278, 8309), False, 'from numpy.testing import assert_equal, assert_allclose\n'), ((8318, 8377), 'numpy.testing.assert_allclose', 'assert_allclose', (['res.forecasts_error_cov[0, 0, 0]', 'sigma2_y'], {}), '(res.forecasts_error_cov[0, 0, 0], sigma2_y)\n', (8333, 8377), False, 'from numpy.testing import assert_equal, assert_allclose\n'), ((8386, 8446), 'numpy.testing.assert_allclose', 'assert_allclose', (['res.forecasts_error_diffuse_cov[0, 0, 0]', '(1)'], {}), '(res.forecasts_error_diffuse_cov[0, 0, 0], 1)\n', (8401, 8446), False, 'from numpy.testing import assert_equal, assert_allclose\n'), ((8455, 8499), 'numpy.testing.assert_allclose', 'assert_allclose', (['res.kalman_gain[0, 0, 0]', '(1)'], {}), '(res.kalman_gain[0, 0, 0], 1)\n', (8470, 8499), False, 'from numpy.testing import assert_equal, assert_allclose\n'), ((8508, 8554), 'numpy.testing.assert_allclose', 'assert_allclose', (['res.predicted_state[0, 1]', 'y1'], {}), '(res.predicted_state[0, 1], y1)\n', (8523, 8554), False, 'from numpy.testing import assert_equal, assert_allclose\n'), ((8563, 8634), 'numpy.testing.assert_allclose', 'assert_allclose', (['res.predicted_state_cov[0, 0, 1]', '(sigma2_y + sigma2_mu)'], {}), '(res.predicted_state_cov[0, 0, 1], sigma2_y + sigma2_mu)\n', (8578, 8634), False, 'from numpy.testing import assert_equal, assert_allclose\n'), ((8643, 8703), 'numpy.testing.assert_allclose', 'assert_allclose', (['res.predicted_diffuse_state_cov[0, 0, 1]', '(0)'], {}), '(res.predicted_diffuse_state_cov[0, 0, 1], 0)\n', (8658, 8703), False, 'from numpy.testing import assert_equal, assert_allclose\n'), ((8737, 8770), 'numpy.testing.assert_equal', 'assert_equal', (['res.nobs_diffuse', '(1)'], {}), '(res.nobs_diffuse, 1)\n', (8749, 8770), False, 'from numpy.testing import assert_equal, assert_allclose\n'), ((9333, 9362), 'numpy.diagonal', 'np.diagonal', (["ssm['state_cov']"], {}), "(ssm['state_cov'])\n", (9344, 9362), True, 'import numpy as np\n'), ((9714, 9760), 'numpy.testing.assert_allclose', 'assert_allclose', (['res.forecasts_error[0, 0]', 'y1'], {}), '(res.forecasts_error[0, 0], y1)\n', (9729, 9760), False, 'from numpy.testing import assert_equal, assert_allclose\n'), ((9769, 9818), 'numpy.testing.assert_allclose', 'assert_allclose', (['res.kalman_gain[:, 0, 0]', '[1, 0]'], {}), '(res.kalman_gain[:, 0, 0], [1, 0])\n', (9784, 9818), False, 'from numpy.testing import assert_equal, assert_allclose\n'), ((9827, 9878), 'numpy.testing.assert_allclose', 'assert_allclose', (['res.predicted_state[:, 1]', '[y1, 0]'], {}), '(res.predicted_state[:, 1], [y1, 0])\n', (9842, 9878), False, 'from numpy.testing import assert_equal, assert_allclose\n'), ((9984, 10037), 'numpy.testing.assert_allclose', 'assert_allclose', (['res.predicted_state_cov[:, :, 1]', 'P2'], {}), '(res.predicted_state_cov[:, :, 1], P2)\n', (9999, 10037), False, 'from numpy.testing import assert_equal, assert_allclose\n'), ((10214, 10280), 'numpy.testing.assert_allclose', 'assert_allclose', (['res.predicted_state[:, 2]', '[2 * y2 - y1, y2 - y1]'], {}), '(res.predicted_state[:, 2], [2 * y2 - y1, y2 - y1])\n', (10229, 10280), False, 'from numpy.testing import assert_equal, assert_allclose\n'), ((10446, 10499), 'numpy.testing.assert_allclose', 'assert_allclose', (['res.predicted_state_cov[:, :, 2]', 'P3'], {}), '(res.predicted_state_cov[:, :, 2], P3)\n', (10461, 10499), False, 'from numpy.testing import assert_equal, assert_allclose\n'), ((10641, 10674), 'numpy.testing.assert_equal', 'assert_equal', (['res.nobs_diffuse', '(2)'], {}), '(res.nobs_diffuse, 2)\n', (10653, 10674), False, 'from numpy.testing import assert_equal, assert_allclose\n'), ((11377, 11406), 'numpy.diagonal', 'np.diagonal', (["ssm['state_cov']"], {}), "(ssm['state_cov'])\n", (11388, 11406), True, 'import numpy as np\n'), ((11570, 11616), 'numpy.testing.assert_allclose', 'assert_allclose', (['res.predicted_state[:, 3]', 'a4'], {}), '(res.predicted_state[:, 3], a4)\n', (11585, 11616), False, 'from numpy.testing import assert_equal, assert_allclose\n'), ((11847, 11900), 'numpy.testing.assert_allclose', 'assert_allclose', (['res.predicted_state_cov[:, :, 3]', 'P4'], {}), '(res.predicted_state_cov[:, :, 3], P4)\n', (11862, 11900), False, 'from numpy.testing import assert_equal, assert_allclose\n'), ((11934, 11967), 'numpy.testing.assert_equal', 'assert_equal', (['res.nobs_diffuse', '(3)'], {}), '(res.nobs_diffuse, 3)\n', (11946, 11967), False, 'from numpy.testing import assert_equal, assert_allclose\n'), ((12343, 12359), 'numpy.zeros', 'np.zeros', (['(2, 2)'], {}), '((2, 2))\n', (12351, 12359), True, 'import numpy as np\n'), ((12422, 12431), 'numpy.eye', 'np.eye', (['(2)'], {}), '(2)\n', (12428, 12431), True, 'import numpy as np\n'), ((13325, 13341), 'numpy.zeros', 'np.zeros', (['(2, 2)'], {}), '((2, 2))\n', (13333, 13341), True, 'import numpy as np\n'), ((16094, 16170), 'numpy.testing.assert_allclose', 'assert_allclose', (['actual.T[d:]', 'desired.T[d:]'], {'rtol': 'self.rtol', 'atol': 'self.atol'}), '(actual.T[d:], desired.T[d:], rtol=self.rtol, atol=self.atol)\n', (16109, 16170), False, 'from numpy.testing import assert_equal, assert_allclose\n'), ((18185, 18220), 'numpy.isscalar', 'np.isscalar', (['self.results_b.llf_obs'], {}), '(self.results_b.llf_obs)\n', (18196, 18220), True, 'import numpy as np\n'), ((25079, 25139), 'numpy.testing.assert_equal', 'assert_equal', (['self.results_b.initial_diffuse_state_cov', 'None'], {}), '(self.results_b.initial_diffuse_state_cov, None)\n', (25091, 25139), False, 'from numpy.testing import assert_equal, assert_allclose\n'), ((27054, 27080), 'numpy.testing.assert_allclose', 'assert_allclose', (['self.d', '(1)'], {}), '(self.d, 1)\n', (27069, 27080), False, 'from numpy.testing import assert_equal, assert_allclose\n'), ((27125, 27177), 'numpy.testing.assert_allclose', 'assert_allclose', (['self.results_a.initial_state_cov', '(0)'], {}), '(self.results_a.initial_state_cov, 0)\n', (27140, 27177), False, 'from numpy.testing import assert_equal, assert_allclose\n'), ((29602, 29628), 'numpy.testing.assert_allclose', 'assert_allclose', (['self.d', '(2)'], {}), '(self.d, 2)\n', (29617, 29628), False, 'from numpy.testing import assert_equal, assert_allclose\n'), ((32026, 32050), 'statsmodels.tsa.statespace.initialization.Initialization', 'Initialization', (['k_states'], {}), '(k_states)\n', (32040, 32050), False, 'from statsmodels.tsa.statespace.initialization import Initialization\n'), ((32466, 32492), 'numpy.testing.assert_allclose', 'assert_allclose', (['self.d', '(1)'], {}), '(self.d, 1)\n', (32481, 32492), False, 'from numpy.testing import assert_equal, assert_allclose\n'), ((33319, 33379), 'numpy.testing.assert_equal', 'assert_equal', (['self.results_b.initial_diffuse_state_cov', 'None'], {}), '(self.results_b.initial_diffuse_state_cov, None)\n', (33331, 33379), False, 'from numpy.testing import assert_equal, assert_allclose\n'), ((34703, 34729), 'numpy.testing.assert_allclose', 'assert_allclose', (['self.d', '(2)'], {}), '(self.d, 2)\n', (34718, 34729), False, 'from numpy.testing import assert_equal, assert_allclose\n'), ((34774, 34826), 'numpy.testing.assert_allclose', 'assert_allclose', (['self.results_a.initial_state_cov', '(0)'], {}), '(self.results_a.initial_state_cov, 0)\n', (34789, 34826), False, 'from numpy.testing import assert_equal, assert_allclose\n'), ((36584, 36610), 'numpy.testing.assert_allclose', 'assert_allclose', (['self.d', '(1)'], {}), '(self.d, 1)\n', (36599, 36610), False, 'from numpy.testing import assert_equal, assert_allclose\n'), ((36655, 36707), 'numpy.testing.assert_allclose', 'assert_allclose', (['self.results_a.initial_state_cov', '(0)'], {}), '(self.results_a.initial_state_cov, 0)\n', (36670, 36707), False, 'from numpy.testing import assert_equal, assert_allclose\n'), ((3604, 3643), 'statsmodels.tsa.statespace.initialization.Initialization', 'Initialization', (['ssm.k_states', '"""diffuse"""'], {}), "(ssm.k_states, 'diffuse')\n", (3618, 3643), False, 'from statsmodels.tsa.statespace.initialization import Initialization\n'), ((4771, 4810), 'statsmodels.tsa.statespace.initialization.Initialization', 'Initialization', (['ssm.k_states', '"""diffuse"""'], {}), "(ssm.k_states, 'diffuse')\n", (4785, 4810), False, 'from statsmodels.tsa.statespace.initialization import Initialization\n'), ((6220, 6242), 'numpy.array', 'np.array', (['[[1, theta]]'], {}), '([[1, theta]])\n', (6228, 6242), True, 'import numpy as np\n'), ((9462, 9478), 'numpy.zeros', 'np.zeros', (['(2, 2)'], {}), '((2, 2))\n', (9470, 9478), True, 'import numpy as np\n'), ((9545, 9554), 'numpy.eye', 'np.eye', (['(2)'], {}), '(2)\n', (9551, 9554), True, 'import numpy as np\n'), ((9903, 9941), 'numpy.array', 'np.array', (['[[1 + q_mu, 0], [0, q_beta]]'], {}), '([[1 + q_mu, 0], [0, q_beta]])\n', (9911, 9941), True, 'import numpy as np\n'), ((10128, 10143), 'numpy.ones', 'np.ones', (['(2, 2)'], {}), '((2, 2))\n', (10135, 10143), True, 'import numpy as np\n'), ((10305, 10407), 'numpy.array', 'np.array', (['[[5 + 2 * q_mu + q_beta, 3 + q_mu + q_beta], [3 + q_mu + q_beta, 2 + q_mu +\n 2 * q_beta]]'], {}), '([[5 + 2 * q_mu + q_beta, 3 + q_mu + q_beta], [3 + q_mu + q_beta, 2 +\n q_mu + 2 * q_beta]])\n', (10313, 10407), True, 'import numpy as np\n'), ((10590, 10606), 'numpy.zeros', 'np.zeros', (['(2, 2)'], {}), '((2, 2))\n', (10598, 10606), True, 'import numpy as np\n'), ((11641, 11792), 'numpy.array', 'np.array', (['[[2.5 + 1.5 * q_mu + 1.25 * q_beta, 1 + 0.5 * q_mu + 1.25 * q_beta], [1 + \n 0.5 * q_mu + 1.25 * q_beta, 0.5 + 0.5 * q_mu + 2.25 * q_beta]]'], {}), '([[2.5 + 1.5 * q_mu + 1.25 * q_beta, 1 + 0.5 * q_mu + 1.25 * q_beta\n ], [1 + 0.5 * q_mu + 1.25 * q_beta, 0.5 + 0.5 * q_mu + 2.25 * q_beta]])\n', (11649, 11792), True, 'import numpy as np\n'), ((18243, 18273), 'numpy.sum', 'np.sum', (['self.results_a.llf_obs'], {}), '(self.results_a.llf_obs)\n', (18249, 18273), True, 'import numpy as np\n'), ((18331, 18363), 'numpy.testing.assert_allclose', 'assert_allclose', (['actual', 'desired'], {}), '(actual, desired)\n', (18346, 18363), False, 'from numpy.testing import assert_equal, assert_allclose\n'), ((24569, 24664), 'statsmodels.tsa.statespace.initialization.Initialization', 'Initialization', (['cls.ssm.k_states', '"""approximate_diffuse"""'], {'approximate_diffuse_variance': 'kappa'}), "(cls.ssm.k_states, 'approximate_diffuse',\n approximate_diffuse_variance=kappa)\n", (24583, 24664), False, 'from statsmodels.tsa.statespace.initialization import Initialization\n'), ((27244, 27253), 'numpy.eye', 'np.eye', (['(2)'], {}), '(2)\n', (27250, 27253), True, 'import numpy as np\n'), ((32183, 32207), 'statsmodels.tsa.statespace.initialization.Initialization', 'Initialization', (['k_states'], {}), '(k_states)\n', (32197, 32207), False, 'from statsmodels.tsa.statespace.initialization import Initialization\n'), ((32656, 32685), 'numpy.diag', 'np.diag', (['[0, stationary_init]'], {}), '([0, stationary_init])\n', (32663, 32685), True, 'import numpy as np\n'), ((32777, 32792), 'numpy.diag', 'np.diag', (['[1, 0]'], {}), '([1, 0])\n', (32784, 32792), True, 'import numpy as np\n'), ((33276, 33309), 'numpy.diag', 'np.diag', (['[kappa, stationary_init]'], {}), '([kappa, stationary_init])\n', (33283, 33309), True, 'import numpy as np\n'), ((34893, 34902), 'numpy.eye', 'np.eye', (['(2)'], {}), '(2)\n', (34899, 34902), True, 'import numpy as np\n'), ((36774, 36783), 'numpy.eye', 'np.eye', (['(1)'], {}), '(1)\n', (36780, 36783), True, 'import numpy as np\n'), ((15966, 16058), 'numpy.testing.assert_allclose', 'assert_allclose', (['actual.T[:d]', 'desired.T[:d]'], {'rtol': 'rtol_diffuse', 'atol': 'self.atol_diffuse'}), '(actual.T[:d], desired.T[:d], rtol=rtol_diffuse, atol=self.\n atol_diffuse)\n', (15981, 16058), False, 'from numpy.testing import assert_equal, assert_allclose\n'), ((25036, 25061), 'numpy.eye', 'np.eye', (['self.ssm.k_states'], {}), '(self.ssm.k_states)\n', (25042, 25061), True, 'import numpy as np\n'), ((26350, 26373), 'numpy.isnan', 'np.isnan', (['cls.ssm.endog'], {}), '(cls.ssm.endog)\n', (26358, 26373), True, 'import numpy as np\n'), ((26403, 26420), 'numpy.log', 'np.log', (['(2 * np.pi)'], {}), '(2 * np.pi)\n', (26409, 26420), True, 'import numpy as np\n'), ((26287, 26302), 'numpy.diag', 'np.diag', (['Finf_t'], {}), '(Finf_t)\n', (26294, 26302), True, 'import numpy as np\n'), ((6519, 6561), 'numpy.log', 'np.log', (["macrodata[['realgdp', 'realcons']]"], {}), "(macrodata[['realgdp', 'realcons']])\n", (6525, 6561), True, 'import numpy as np\n'), ((7140, 7182), 'numpy.log', 'np.log', (["macrodata[['realgdp', 'realcons']]"], {}), "(macrodata[['realgdp', 'realcons']])\n", (7146, 7182), True, 'import numpy as np\n'), ((29307, 29349), 'numpy.log', 'np.log', (["macrodata[['realgdp', 'realcons']]"], {}), "(macrodata[['realgdp', 'realcons']])\n", (29313, 29349), True, 'import numpy as np\n')]
import numpy as np import pandas as pd import math import scipy.linalg as la import matplotlib.pyplot as plt import seaborn as sns from scipy.spatial import distance import numba from numba import jit, int32, int64, float32, float64 import pstats @jit(nopython = True) def p_ij(d_matrix, perplexity = 40.0, tol = 1e-6): ''' Finds P_ij matrix using binary search to find value of sigma_i Inputs: d_matrix- np.array of pairwise distance matrix, with a fixed perplexity perplexity: float chosen by user tolerance: float chosen by user Output: P-ij matrix of pairwise similarities in the high dimensional space ''' (n, d) = d_matrix.shape P = np.zeros((n, d), dtype=np.float64) prec_sum = 0.0 # precision = 1/2sigma^2 for i in range(n): prec_min = -np.inf prec_max = np.inf prec = 1.0 # implement binary search for optimal sigmas for j in range(10): # 10 binary search steps sum_p = 0.0 for k in range(d): if k != i: P[i, k] = np.exp(-d_matrix[i, k] * prec) sum_p += P[i, k] sum_p_distribution = 0.0 for k in range(d): P[i, k] /= (sum_p + 1e-8) sum_p_distribution += d_matrix[i, k] * P[i, k] # Calculate entropy, H matrix H = np.log(sum_p) + prec * sum_p_distribution H_diff = H - np.log(perplexity) # check if entropy is within tolerance if np.fabs(H_diff) <= tol: break if H_diff > 0.0: prec_min = prec if prec_max == np.inf: prec *= 2.0 else: prec = (prec + prec_max) / 2.0 else: prec_max = prec if prec_min == -np.inf: prec /= 2.0 else: prec = (prec + prec_min) / 2.0 prec_sum += prec return P @jit(nopython = True) def squared_euc_dist(X): ''' Calculates squared euclidean distance for all pairs in a data matrix X with d dimensions and n rows. Input: Matrix X Output is a pairwise distance matrix D that is nxn. ''' n = X.shape[0] d = X.shape[1] D = np.empty((n, n), dtype=np.float64) for i in range(n): for j in range(n): dist = 0.0 for k in range(d): diff = X[i, k] - X[j, k] dist += diff * diff D[i, j] = dist return np.asarray(D) @jit(nopython = True) def q_ij(Y): ''' Calculate joint probabilities over all points given Y, the low-dimensional map of data points. (pg. 2585) Input: Matrix Y Output: Q, a matrix of pairwise similarities in the low-dimensional map ''' numerator = np.power(1. + (squared_euc_dist(Y)), -1) Q = numerator / np.sum(numerator) # q_i|i = 0 np.fill_diagonal(Q, 0.) return Q @jit(nopython = True) def grad_C(P, Q, Y): ''' Estimate the gradient of t-SNE cost with respect to Y. Input: P: P-ij matrix of pairwise similarities in the high dimensional space Q: Q-ij, a matrix of pairwise similarities in the low-dimensional map Y: low-dimensional representation of data matrix Output: grad, gradient of t-SNE ''' pq_diff = np.expand_dims((P - Q), 2) y_diff = np.expand_dims(Y, 1) - np.expand_dims(Y, 0) y_dist = np.expand_dims(np.power(1 + squared_euc_dist(Y), -1), 2) grad = 4. * (pq_diff * y_diff * y_dist).sum(axis = 1) return grad @jit(nopython = True) def TSNE(X, num_iters = 1000, perplexity = 40, alpha = 100, momentum = 0.8): ''' Calculates Y, the optimal low-dimensional representation of data matrix X using optimized TSNE. Inputs: X: data matrix num_iters: number of iterations perplexity: target perplexity for calculating optimal sigmas for P probability matrix alpha: learning rate momentum: momentum to speed up gradient descent algorithm Output: Y, low-dimensional representation of data found using t-SNE algorithm ''' # Initialize Y np.random.seed(0) Y = np.random.normal(0, 0.0001, size=(X.shape[0], 2)) D = squared_euc_dist(X) P = p_ij(D) P = P + np.transpose(P) P = P / np.sum(P) # Initialise past y_t-1 and y_t-2 values (used for momentum) Y_tmin2 = Y Y_tmin1 = Y # gradient descent with momentum for i in range(num_iters): Q = q_ij(Y) grad = grad_C(P, Q, Y) # Update Y using momentum (pg. 2587) Y = (Y - (alpha * grad)) + (momentum * (Y_tmin1 - Y_tmin2)) # update values of y_t-1 and y_t-2 Y_tmin2 = Y_tmin1 Y_tmin1 = Y return Y def TSNE_plot(Y, labels): ''' Plots visualization of TSNE output by label class Inputs: Y: two-dimensional matrix that's been passed through TSNE function labels: array of labels that correspond to the data X clusters ''' plt.figure(figsize=(9.6,7.2)) df = pd.DataFrame(data=np.c_[Y, labels], columns=("x", "y", "label")) l = len(set(labels)) if l <= 5: sns.scatterplot(data = df, x = "x", y = "y", hue = "label", palette = sns.color_palette("husl", l)).set(xlabel=None, ylabel=None) elif l <= 20: sns.scatterplot(data = df, x = "x", y = "y", hue = "label", palette = sns.color_palette("husl", l)).set(xlabel=None, ylabel=None) plt.legend(bbox_to_anchor=(1.03, 1), borderaxespad=0) else: sns.scatterplot(data = df, x = "x", y = "y", hue = "label", palette = sns.color_palette("husl", l)).set(xlabel=None, ylabel=None) plt.legend(bbox_to_anchor=(1.03, 1), borderaxespad=0, ncol=2) plt.show()
[ "numpy.random.normal", "numpy.fabs", "seaborn.color_palette", "numpy.log", "numpy.asarray", "numpy.fill_diagonal", "numpy.exp", "numpy.sum", "numpy.zeros", "numba.jit", "numpy.empty", "numpy.random.seed", "numpy.expand_dims", "matplotlib.pyplot.figure", "pandas.DataFrame", "numpy.trans...
[((249, 267), 'numba.jit', 'jit', ([], {'nopython': '(True)'}), '(nopython=True)\n', (252, 267), False, 'from numba import jit, int32, int64, float32, float64\n'), ((2063, 2081), 'numba.jit', 'jit', ([], {'nopython': '(True)'}), '(nopython=True)\n', (2066, 2081), False, 'from numba import jit, int32, int64, float32, float64\n'), ((2658, 2676), 'numba.jit', 'jit', ([], {'nopython': '(True)'}), '(nopython=True)\n', (2661, 2676), False, 'from numba import jit, int32, int64, float32, float64\n'), ((3094, 3112), 'numba.jit', 'jit', ([], {'nopython': '(True)'}), '(nopython=True)\n', (3097, 3112), False, 'from numba import jit, int32, int64, float32, float64\n'), ((3748, 3766), 'numba.jit', 'jit', ([], {'nopython': '(True)'}), '(nopython=True)\n', (3751, 3766), False, 'from numba import jit, int32, int64, float32, float64\n'), ((698, 732), 'numpy.zeros', 'np.zeros', (['(n, d)'], {'dtype': 'np.float64'}), '((n, d), dtype=np.float64)\n', (706, 732), True, 'import numpy as np\n'), ((2371, 2405), 'numpy.empty', 'np.empty', (['(n, n)'], {'dtype': 'np.float64'}), '((n, n), dtype=np.float64)\n', (2379, 2405), True, 'import numpy as np\n'), ((2639, 2652), 'numpy.asarray', 'np.asarray', (['D'], {}), '(D)\n', (2649, 2652), True, 'import numpy as np\n'), ((3050, 3074), 'numpy.fill_diagonal', 'np.fill_diagonal', (['Q', '(0.0)'], {}), '(Q, 0.0)\n', (3066, 3074), True, 'import numpy as np\n'), ((3501, 3525), 'numpy.expand_dims', 'np.expand_dims', (['(P - Q)', '(2)'], {}), '(P - Q, 2)\n', (3515, 3525), True, 'import numpy as np\n'), ((4347, 4364), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (4361, 4364), True, 'import numpy as np\n'), ((4373, 4422), 'numpy.random.normal', 'np.random.normal', (['(0)', '(0.0001)'], {'size': '(X.shape[0], 2)'}), '(0, 0.0001, size=(X.shape[0], 2))\n', (4389, 4422), True, 'import numpy as np\n'), ((5222, 5252), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(9.6, 7.2)'}), '(figsize=(9.6, 7.2))\n', (5232, 5252), True, 'import matplotlib.pyplot as plt\n'), ((5261, 5325), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': 'np.c_[Y, labels]', 'columns': "('x', 'y', 'label')"}), "(data=np.c_[Y, labels], columns=('x', 'y', 'label'))\n", (5273, 5325), True, 'import pandas as pd\n'), ((5960, 5970), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (5968, 5970), True, 'import matplotlib.pyplot as plt\n'), ((3007, 3024), 'numpy.sum', 'np.sum', (['numerator'], {}), '(numerator)\n', (3013, 3024), True, 'import numpy as np\n'), ((3546, 3566), 'numpy.expand_dims', 'np.expand_dims', (['Y', '(1)'], {}), '(Y, 1)\n', (3560, 3566), True, 'import numpy as np\n'), ((3569, 3589), 'numpy.expand_dims', 'np.expand_dims', (['Y', '(0)'], {}), '(Y, 0)\n', (3583, 3589), True, 'import numpy as np\n'), ((4479, 4494), 'numpy.transpose', 'np.transpose', (['P'], {}), '(P)\n', (4491, 4494), True, 'import numpy as np\n'), ((4507, 4516), 'numpy.sum', 'np.sum', (['P'], {}), '(P)\n', (4513, 4516), True, 'import numpy as np\n'), ((5678, 5731), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'bbox_to_anchor': '(1.03, 1)', 'borderaxespad': '(0)'}), '(bbox_to_anchor=(1.03, 1), borderaxespad=0)\n', (5688, 5731), True, 'import matplotlib.pyplot as plt\n'), ((5893, 5954), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'bbox_to_anchor': '(1.03, 1)', 'borderaxespad': '(0)', 'ncol': '(2)'}), '(bbox_to_anchor=(1.03, 1), borderaxespad=0, ncol=2)\n', (5903, 5954), True, 'import matplotlib.pyplot as plt\n'), ((1407, 1420), 'numpy.log', 'np.log', (['sum_p'], {}), '(sum_p)\n', (1413, 1420), True, 'import numpy as np\n'), ((1474, 1492), 'numpy.log', 'np.log', (['perplexity'], {}), '(perplexity)\n', (1480, 1492), True, 'import numpy as np\n'), ((1573, 1588), 'numpy.fabs', 'np.fabs', (['H_diff'], {}), '(H_diff)\n', (1580, 1588), True, 'import numpy as np\n'), ((1105, 1135), 'numpy.exp', 'np.exp', (['(-d_matrix[i, k] * prec)'], {}), '(-d_matrix[i, k] * prec)\n', (1111, 1135), True, 'import numpy as np\n'), ((5449, 5477), 'seaborn.color_palette', 'sns.color_palette', (['"""husl"""', 'l'], {}), "('husl', l)\n", (5466, 5477), True, 'import seaborn as sns\n'), ((5610, 5638), 'seaborn.color_palette', 'sns.color_palette', (['"""husl"""', 'l'], {}), "('husl', l)\n", (5627, 5638), True, 'import seaborn as sns\n'), ((5825, 5853), 'seaborn.color_palette', 'sns.color_palette', (['"""husl"""', 'l'], {}), "('husl', l)\n", (5842, 5853), True, 'import seaborn as sns\n')]
from __future__ import print_function, division from horoma.cfg import DEVICE import torch.nn as nn import torch.optim as optim import time import copy import numpy as np import torch from sklearn import warnings from horoma.experiments import HoromaExperiment from horoma.utils.data import HoromaDataset from torch.utils.data import DataLoader from torchvision import transforms class SqueezenetExperiment(HoromaExperiment): def squeezenet1_0(self, pretrained=False): """SqueezeNet model architecture from the `"SqueezeNet: AlexNet-level accuracy with 50x fewer parameters and <0.5MB model size" <https://arxiv.org/abs/1602.07360>`_ paper. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ if pretrained: self._embedding_model.load_state_dict(torch.load('/home/user5/horoma/models/squeezenet1_0-a815701f.pth')) def _train_embedding(self, train_train_loader, train_train_no_aug_loader, train_valid_loader, epochs, start_epoch, valid_train_loader, valid_valid_loader): """ Train and evaluate the model. Parameters ---------- train and validation sets: DataLoaders epochs: int Returns ------- Best _embedding_model after training """ train_loader = train_train_loader # Flag for feature extracting. When False, we finetune the whole model, # when True we only update the reshaped layer params feature_extract = False use_pretrained = True self.initialize_model(feature_extract, use_pretrained) self._embedding_model = self._embedding_model.to(DEVICE) params_to_update = self._embedding_model.parameters() print("Params to learn:") if feature_extract: params_to_update = [] for name, param in self._embedding_model.named_parameters(): if param.requires_grad: params_to_update.append(param) print("\t", name) else: for name, param in self._embedding_model.named_parameters(): if param.requires_grad: print("\t", name) optimizer = optim.SGD(params_to_update, lr=0.0001, momentum=0.9) print("=================") print("Training model...") since = time.time() val_acc_history = [] best_model_wts = copy.deepcopy(self._embedding_model.state_dict()) best_acc = 0.0 for epoch in range(epochs): print('Epoch {}/{}'.format(epoch, epochs - 1)) print('-' * 10) self._embedding_model.train() # Set model to training mode running_loss = 0.0 running_corrects = 0 # Iterate over data. for _, inputs in enumerate(train_loader): inputs = inputs.to(DEVICE) # zero the parameter gradients self._embedding_model.zero_grad() with torch.set_grad_enabled(True): # Get model outputs and calculate loss # Special case for inception because in training it has an auxiliary output. In train # mode we calculate the loss by summing the final output and the auxiliary output # but in testing we only consider the final output. outputs = self._embedding_model(inputs) outputs_copy = outputs.to('cpu') output_arr = outputs_copy.detach().numpy() if len(output_arr) < 2: arrtmp = {} arrtmp.append(int(outputs_copy.tolist()[0][0])) labels2 = (torch.tensor(arrtmp)).type(torch.LongTensor) labels = labels2.to(self.DEVICE) else: with warnings.catch_warnings(): warnings.simplefilter("ignore") labels2 = (torch.from_numpy(self._cluster_obj.fit(output_arr).predict(output_arr))).type(torch.LongTensor) labels = labels2.to(DEVICE) criterion = nn.CrossEntropyLoss() loss = criterion(outputs, labels) _, preds = torch.max(outputs, 1) loss.backward() optimizer.step() # statistics running_loss += loss.item() * inputs.size(0) running_corrects += torch.sum(preds == labels.data) epoch_loss = running_loss / len(train_loader.dataset) epoch_acc = running_corrects.double() / len(train_loader.dataset) print("Loader len: ", len(train_loader.dataset)) time_elapsed = time.time() - since print('Time: {:.0f}m Loss: {:.4f} Acc: {:.4f}'.format(time_elapsed // 60, epoch_loss, epoch_acc)) # deep copy the model if epoch_acc > best_acc: best_acc = epoch_acc best_model_wts = copy.deepcopy(self._embedding_model.state_dict()) val_acc_history.append(epoch_acc) print() time_elapsed = time.time() - since print('Training complete in {:.0f}m {:.0f}s'.format(time_elapsed // 60, time_elapsed % 60)) print('Best val Acc: {:4f}'.format(best_acc)) # load last model weights self._embedding_model.load_state_dict(best_model_wts) valid_dataset = HoromaDataset(split='valid', transform=transforms.ToTensor()) valid_loader = DataLoader(valid_dataset, batch_size=100, shuffle=False) print("=================") print("Evaluating model...") self.eval_model(self._embedding_model, valid_loader, optimizer) def set_parameter_requires_grad(self, feature_extracting): """ Gather the parameters to be optimized/updated in this run. If we are finetuning we will be updating all parameters. However, if we are doing feature extract method, we will only update the parameters that we have just initialized, i.e. the parameters with requires_grad is True. Parameters ---------- feature_extracting: boolean Returns ------- model parameters with requires_grad setup """ if feature_extracting: for param in self._embedding_model.parameters(): param.requires_grad = False def initialize_model(self, feature_extract, use_pretrained): """ Initialize the model Parameters ---------- feature_extract: boolean - Defines if the model parameters requires grad or not. For finetunning this parameter should be false. use_pretrained: boolean - Define if it will use a pre-trained model or not. Returns ------- Model initialized """ self.squeezenet1_0(pretrained=use_pretrained) self.set_parameter_requires_grad(feature_extract) self._embedding_model.classifier[1] = nn.Conv2d(512, self._cluster_obj.n_clusters, kernel_size=(1, 1), stride=(1, 1)) self._embedding_model.num_classes = self._cluster_obj.n_clusters def eval_model(self, model, valid_loader, optimizer): """ Evaluate the model Parameters ---------- Validation loader: Dataset - Validation dataset to evaluate the model. Returns ------- Validation set length: int Accuracy of the Validation set: int """ model.eval() # Set model to evaluation mode running_loss = 0.0 running_corrects = 0 # Iterate over data. for inputs, labels in valid_loader: inputs = inputs.to(DEVICE) labels = labels.to(DEVICE) # zero the parameter gradients optimizer.zero_grad() # forward # track history if only in train with torch.set_grad_enabled(False): # Get model outputs and calculate loss # Special case for inception because in training it has an auxiliary output. In train # mode we calculate the loss by summing the final output and the auxiliary output # but in testing we only consider the final output. outputs = model(inputs) labels_copy = labels.to('cpu') labels2 = labels_copy.detach().numpy() labels2 = list(np.squeeze(labels2.astype('int64'), axis=1)) labels = torch.from_numpy(np.asarray(labels2)) labels = labels.type(torch.LongTensor) labels = labels.to(DEVICE) criterion = nn.CrossEntropyLoss() loss = criterion(outputs, labels) _, preds = torch.max(outputs, 1) # statistics running_loss += loss.item() * inputs.size(0) running_corrects += torch.sum(preds == labels.data) epoch_acc = running_corrects.double() / len(valid_loader.dataset) print("Loader len: ", len(valid_loader.dataset)) print() print('Valid Acc: {:4f}'.format(epoch_acc))
[ "torch.optim.SGD", "torch.nn.CrossEntropyLoss", "torch.load", "torch.max", "numpy.asarray", "sklearn.warnings.catch_warnings", "torch.nn.Conv2d", "sklearn.warnings.simplefilter", "torch.tensor", "torch.sum", "torch.utils.data.DataLoader", "torch.set_grad_enabled", "torchvision.transforms.ToT...
[((2488, 2540), 'torch.optim.SGD', 'optim.SGD', (['params_to_update'], {'lr': '(0.0001)', 'momentum': '(0.9)'}), '(params_to_update, lr=0.0001, momentum=0.9)\n', (2497, 2540), True, 'import torch.optim as optim\n'), ((2632, 2643), 'time.time', 'time.time', ([], {}), '()\n', (2641, 2643), False, 'import time\n'), ((5960, 6016), 'torch.utils.data.DataLoader', 'DataLoader', (['valid_dataset'], {'batch_size': '(100)', 'shuffle': '(False)'}), '(valid_dataset, batch_size=100, shuffle=False)\n', (5970, 6016), False, 'from torch.utils.data import DataLoader\n'), ((7574, 7653), 'torch.nn.Conv2d', 'nn.Conv2d', (['(512)', 'self._cluster_obj.n_clusters'], {'kernel_size': '(1, 1)', 'stride': '(1, 1)'}), '(512, self._cluster_obj.n_clusters, kernel_size=(1, 1), stride=(1, 1))\n', (7583, 7653), True, 'import torch.nn as nn\n'), ((5571, 5582), 'time.time', 'time.time', ([], {}), '()\n', (5580, 5582), False, 'import time\n'), ((9575, 9606), 'torch.sum', 'torch.sum', (['(preds == labels.data)'], {}), '(preds == labels.data)\n', (9584, 9606), False, 'import torch\n'), ((876, 942), 'torch.load', 'torch.load', (['"""/home/user5/horoma/models/squeezenet1_0-a815701f.pth"""'], {}), "('/home/user5/horoma/models/squeezenet1_0-a815701f.pth')\n", (886, 942), False, 'import torch\n'), ((4877, 4908), 'torch.sum', 'torch.sum', (['(preds == labels.data)'], {}), '(preds == labels.data)\n', (4886, 4908), False, 'import torch\n'), ((5147, 5158), 'time.time', 'time.time', ([], {}), '()\n', (5156, 5158), False, 'import time\n'), ((5913, 5934), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (5932, 5934), False, 'from torchvision import transforms\n'), ((8554, 8583), 'torch.set_grad_enabled', 'torch.set_grad_enabled', (['(False)'], {}), '(False)\n', (8576, 8583), False, 'import torch\n'), ((9331, 9352), 'torch.nn.CrossEntropyLoss', 'nn.CrossEntropyLoss', ([], {}), '()\n', (9350, 9352), True, 'import torch.nn as nn\n'), ((9434, 9455), 'torch.max', 'torch.max', (['outputs', '(1)'], {}), '(outputs, 1)\n', (9443, 9455), False, 'import torch\n'), ((3311, 3339), 'torch.set_grad_enabled', 'torch.set_grad_enabled', (['(True)'], {}), '(True)\n', (3333, 3339), False, 'import torch\n'), ((4536, 4557), 'torch.nn.CrossEntropyLoss', 'nn.CrossEntropyLoss', ([], {}), '()\n', (4555, 4557), True, 'import torch.nn as nn\n'), ((4647, 4668), 'torch.max', 'torch.max', (['outputs', '(1)'], {}), '(outputs, 1)\n', (4656, 4668), False, 'import torch\n'), ((9181, 9200), 'numpy.asarray', 'np.asarray', (['labels2'], {}), '(labels2)\n', (9191, 9200), True, 'import numpy as np\n'), ((4220, 4245), 'sklearn.warnings.catch_warnings', 'warnings.catch_warnings', ([], {}), '()\n', (4243, 4245), False, 'from sklearn import warnings\n'), ((4276, 4307), 'sklearn.warnings.simplefilter', 'warnings.simplefilter', (['"""ignore"""'], {}), "('ignore')\n", (4297, 4307), False, 'from sklearn import warnings\n'), ((4060, 4080), 'torch.tensor', 'torch.tensor', (['arrtmp'], {}), '(arrtmp)\n', (4072, 4080), False, 'import torch\n')]
""" (C) 2017 <NAME> [London Machine Learning Study Group](http://www.meetup.com/London-Machine-Learning-Study-Group/members/) This work is licensed under the Creative Commons Attribution 4.0 International License. To view a copy of this license, visit http://creativecommons.org/licenses/by/4.0/. """ import numpy as np from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score from sklearn.metrics import confusion_matrix from math import sqrt from math import pi from math import exp def getPriors(labels): """ Get the class priors by calculating the class probability from the provided set. The prior is computed as (prior for class A) = (number of class A samples) / (total number of samples) Parameters ---------- labels : target class values Returns ------- priors : A dictionary with the class priors. E.g. { ClassA: prior, ClassB: prior, ...} """ priors = {} for className in labels: N = labels.size class_occurrence = (labels == className).sum() priors[className] = class_occurrence/N return priors def fit(features, labels): """ Fits coefficients for a Gaussian Naive Bayes. This method computes and returns the in-class mean and stadnard deviation for each feature in the training vectors. Parameters ---------- featires : training vectors labels : target class values Returns ------- priors : A dictionary with with the in-class mean/std for each attribute {ClassA: [(attribute1_mean, attribute1_std]), (attribute2_mean, attribute2_std],...) ClassB: [(attribute1_mean, attribute1_std]), (attribute2_mean, attribute2_std],... ...} """ # Get the unique classes from the sample uniqueClasses = np.unique(labels) coeffs = {} # Loop over the unique classes to compute the mean/std statistics for className in uniqueClasses: featuresInClass = features[labels == className] # Compute the mean/std for each input feature statsInClass = [(np.mean(feature), np.std(feature)) for feature in zip(*featuresInClass)] coeffs[className] = statsInClass return coeffs def getLikelihood(x, featureIndex, model, className): """ Computes the likelihood (i.e. the probability of the evidence given the model parameters) for a single value/class combination. The likelihood is computed using a Gaussian probability desnity function f(x|mu, sigma) = 1 / sqrt( 2 * pi * sigma^2 ) * exp ( - ( x-mu )^2 / (2 * sigma^2) ) Parameters ---------- x : observation value featureIndex : position of this attribute in the input vector. If the model was fitted against an N-dimenisonal input vector [x_0, x_1, ..., x_N], featureIndex should point to the position of x in the original vector (e.g. 0,1,...,N) model : a dictionary with with the in-class mean/std for each attribute. See the fit(features, labels) method className : class to asses the observation against Returns ------- f : the (x|className) likelihood based on the Guassian PDF """ classStats = model[className] mean = classStats[featureIndex][0] std = classStats[featureIndex][1] f = (1/(sqrt(2*pi*pow(std,2))) * exp(-pow((x-mean),2)/(2*pow(std,2)))) return f def getPosterior(x, model, priors): """ Computes the posterior using a Gaussian Naive Bayes. P(class|x = [x_1, x_2, ..., x_N]) = likelihood(x|class) * prior(class) We use the naive assumption of conditional independence between the features, which means that P([x_1, x_2, ..., x_N]|class) = P(x_1|class) * P(x_2|class) * ... * P(x_N|class) Parameters ---------- x : input vector model : a dictionary with with the in-class mean/std for each attribute. See the fit(features, labels) method priors : a dictionary with with the in-class mean/std for each attribute Returns ------- p : the posterior for all classes in priors given the input vector """ posteriors = {} # Loop over all observed classes for className in priors: # Compute p(x_1|class) * p(x_2|class) * ... * p(x_N|class) using the # likelihood function, then multiply by the prior to get # p(class|x = [x_1, x_2, ..., x_N]) p = 1 for featureIndex in range(x.size): p = p * (getLikelihood (x[featureIndex], featureIndex, model, className) * priors[className]) posteriors[className] = p return posteriors def classify(x, model, priors): """ This method uses Maximum a posteriori estimation (MAP) to make a class prediction on an unseen observation. Class_MAP = argmax_c posterior(c|x) = argmax_c likelihood(x|c) * prior (c) Parameters ---------- x : input vector model : a dictionary with with the in-class mean/std for each attribute. See the fit(features, labels) method priors : a dictionary with with the in-class mean/std for each attribute Returns ------- The name of the class that maximizes the posterior value """ posteriors = getPosterior(x, model, priors) return max(posteriors, key=lambda key: posteriors[key]) # Data from National Longitudinal Youth Survey, Bureau of Labor Statistics, # United States Department of Labor # http://www.bls.gov/nls/nlsy97.htm data = np.genfromtxt("gender_height_weight.csv", delimiter=",", skip_header=1) # Assign [height(inchs), weight(lbs)] to features and [gender] to labels features = data[:,[1,2]] labels = data[:,0] # Split the data into test/train subsets features_train, features_test, labels_train, labels_test = train_test_split(features, labels, test_size=0.1, random_state = 100) # Fit the model priors = getPriors(labels_train) model = fit(features_train, labels_train) # To see the likelihood for a certain attribute per class we can do: # x = np.array([69]) # getLikelihood(x, 0, model, 0) <- likelihood for class 0 : 0.1171193286800898 # getLikelihood(x, 0, model, 1) <- likelihood for class 1 : 0.04168934664951199 # Make predictions on the test data predictions = [classify(x, model, priors) for x in features_test] # Measure accuracy print("Prediction accuracy: %.2f\n" % accuracy_score(labels_test, predictions)) # Print confusion matrix print("Confusion matrix:\n") print(confusion_matrix(labels_test, predictions))
[ "numpy.mean", "numpy.unique", "sklearn.model_selection.train_test_split", "numpy.std", "numpy.genfromtxt", "sklearn.metrics.accuracy_score", "sklearn.metrics.confusion_matrix" ]
[((5842, 5913), 'numpy.genfromtxt', 'np.genfromtxt', (['"""gender_height_weight.csv"""'], {'delimiter': '""","""', 'skip_header': '(1)'}), "('gender_height_weight.csv', delimiter=',', skip_header=1)\n", (5855, 5913), True, 'import numpy as np\n'), ((6133, 6200), 'sklearn.model_selection.train_test_split', 'train_test_split', (['features', 'labels'], {'test_size': '(0.1)', 'random_state': '(100)'}), '(features, labels, test_size=0.1, random_state=100)\n', (6149, 6200), False, 'from sklearn.model_selection import train_test_split\n'), ((1902, 1919), 'numpy.unique', 'np.unique', (['labels'], {}), '(labels)\n', (1911, 1919), True, 'import numpy as np\n'), ((6962, 7004), 'sklearn.metrics.confusion_matrix', 'confusion_matrix', (['labels_test', 'predictions'], {}), '(labels_test, predictions)\n', (6978, 7004), False, 'from sklearn.metrics import confusion_matrix\n'), ((6859, 6899), 'sklearn.metrics.accuracy_score', 'accuracy_score', (['labels_test', 'predictions'], {}), '(labels_test, predictions)\n', (6873, 6899), False, 'from sklearn.metrics import accuracy_score\n'), ((2171, 2187), 'numpy.mean', 'np.mean', (['feature'], {}), '(feature)\n', (2178, 2187), True, 'import numpy as np\n'), ((2189, 2204), 'numpy.std', 'np.std', (['feature'], {}), '(feature)\n', (2195, 2204), True, 'import numpy as np\n')]
import numpy as np from q_learning.utils import Scalarize from coinrun import make from coinrun import setup_utils def testing(): setup_utils.setup_and_load() episodes = 10 env = Scalarize(make('standard', num_envs=1)) for i in range(episodes): env.reset() while True: env.render() action = np.random.randint(0, env.action_space.n) next_state, reward, done, info = env.step(action) if done or reward > 0: break def main(): testing() if __name__ == '__main__': main()
[ "numpy.random.randint", "coinrun.setup_utils.setup_and_load", "coinrun.make" ]
[((137, 165), 'coinrun.setup_utils.setup_and_load', 'setup_utils.setup_and_load', ([], {}), '()\n', (163, 165), False, 'from coinrun import setup_utils\n'), ((204, 232), 'coinrun.make', 'make', (['"""standard"""'], {'num_envs': '(1)'}), "('standard', num_envs=1)\n", (208, 232), False, 'from coinrun import make\n'), ((350, 390), 'numpy.random.randint', 'np.random.randint', (['(0)', 'env.action_space.n'], {}), '(0, env.action_space.n)\n', (367, 390), True, 'import numpy as np\n')]
from tfdlg.data import BlockDataset from tfdlg.dialog.data import DialogDataset from tfdlg.dialog.data import DialogClsDataset from tfdlg.models import PreLNDecoder from tfdlg.losses import PaddingLoss from tfdlg.tokenizers import SentencePieceTokenizer from tfdlg.dialog.tokenizers import encode_dialog from typing import List from tfdlg.generations import TopKTopPGenerator import tensorflow.keras as keras import numpy as np class LMTask: def __init__(self, config): self._config = config @property def model_cls(self): return PreLNDecoder @property def loss_fn(self): return PaddingLoss() def prepare_tokenizer(self, model_dir): self._tokenizer = SentencePieceTokenizer.load(model_dir=model_dir) return self._tokenizer def prepare_dataset(self, filename, encode_fn, batch_size, shuffle, buffer_size=10000): def gen(): return (t.strip("\n") for t in open(filename)) ds = BlockDataset.from_generator( generator=gen, encode_fn=encode_fn, block_size=self._config.context_size, batch_size=batch_size, buffer_size=buffer_size, shuffle=shuffle ) return ds def handle_request(self, model, context: List[str], response: str): # Parameters max_len = 20 # Prepare text to convert to ids ids = [] for item in context: ids += self._tokenizer.encode(item) if response: ids += self._tokenizer.encode(response) generator = TopKTopPGenerator(model=model, max_len=max_len) if len(ids) > 0: output_ids = generator.generate(np.array([ids], dtype=np.int32)) output_ids = output_ids[0][len(ids):] output_text = self._tokenizer.decode(output_ids.tolist()) print("Input context: ", context) print("Input response: ", response) print("Encode:", ids) print("Gen: ", output_ids) print("Response:", output_text) # [TODO] This will ignore the space which is needed after the given response. if response: output_text = response + output_text else: print("Respond empty string because of empty ids") output_text = "" return output_text class DialogTask(LMTask): def __init__(self, config): self._config = config @property def model_cls(self): return PreLNDecoder @property def loss_fn(self): return PaddingLoss() def prepare_tokenizer(self, model_dir): self._tokenizer = SentencePieceTokenizer.load(model_dir=model_dir) return self._tokenizer def prepare_dataset(self, filename, encode_fn, batch_size, shuffle, buffer_size=10000): def gen(): return (t.strip("\n").split("\t") for t in open(filename)) ds = DialogDataset.from_generator( generator=gen, context_encode_fn=lambda context: encode_dialog( encode_fn=encode_fn, sep_token_id=self._tokenizer.sep_token_id, context=context, response=None ), max_len=self._config.context_size, batch_size=batch_size, buffer_size=buffer_size, shuffle=shuffle ) return ds class DialogClsTask(LMTask): def __init__(self, config): self._config = config @property def model_cls(self): return PreLNDecoder @property def loss_fn(self): return (PaddingLoss(), keras.losses.BinaryCrossentropy(from_logits=True)) def prepare_tokenizer(self, model_dir): self._tokenizer = SentencePieceTokenizer.load(model_dir=model_dir) return self._tokenizer def prepare_dataset(self, filename, encode_fn, batch_size, shuffle, buffer_size=10000): def gen(): return (t.strip("\n").split("\t") for t in open(filename)) ds = DialogClsDataset.from_generator( generator=gen, encode_fn=encode_fn, max_len=self._config.context_size, sep_token_id=self._tokenizer.sep_token_id, batch_size=batch_size, buffer_size=buffer_size, shuffle=shuffle ) return ds
[ "tfdlg.dialog.data.DialogClsDataset.from_generator", "tfdlg.data.BlockDataset.from_generator", "tensorflow.keras.losses.BinaryCrossentropy", "tfdlg.dialog.tokenizers.encode_dialog", "tfdlg.tokenizers.SentencePieceTokenizer.load", "tfdlg.generations.TopKTopPGenerator", "numpy.array", "tfdlg.losses.Padd...
[((627, 640), 'tfdlg.losses.PaddingLoss', 'PaddingLoss', ([], {}), '()\n', (638, 640), False, 'from tfdlg.losses import PaddingLoss\n'), ((712, 760), 'tfdlg.tokenizers.SentencePieceTokenizer.load', 'SentencePieceTokenizer.load', ([], {'model_dir': 'model_dir'}), '(model_dir=model_dir)\n', (739, 760), False, 'from tfdlg.tokenizers import SentencePieceTokenizer\n'), ((1001, 1177), 'tfdlg.data.BlockDataset.from_generator', 'BlockDataset.from_generator', ([], {'generator': 'gen', 'encode_fn': 'encode_fn', 'block_size': 'self._config.context_size', 'batch_size': 'batch_size', 'buffer_size': 'buffer_size', 'shuffle': 'shuffle'}), '(generator=gen, encode_fn=encode_fn, block_size=\n self._config.context_size, batch_size=batch_size, buffer_size=\n buffer_size, shuffle=shuffle)\n', (1028, 1177), False, 'from tfdlg.data import BlockDataset\n'), ((1613, 1660), 'tfdlg.generations.TopKTopPGenerator', 'TopKTopPGenerator', ([], {'model': 'model', 'max_len': 'max_len'}), '(model=model, max_len=max_len)\n', (1630, 1660), False, 'from tfdlg.generations import TopKTopPGenerator\n'), ((2611, 2624), 'tfdlg.losses.PaddingLoss', 'PaddingLoss', ([], {}), '()\n', (2622, 2624), False, 'from tfdlg.losses import PaddingLoss\n'), ((2696, 2744), 'tfdlg.tokenizers.SentencePieceTokenizer.load', 'SentencePieceTokenizer.load', ([], {'model_dir': 'model_dir'}), '(model_dir=model_dir)\n', (2723, 2744), False, 'from tfdlg.tokenizers import SentencePieceTokenizer\n'), ((3816, 3864), 'tfdlg.tokenizers.SentencePieceTokenizer.load', 'SentencePieceTokenizer.load', ([], {'model_dir': 'model_dir'}), '(model_dir=model_dir)\n', (3843, 3864), False, 'from tfdlg.tokenizers import SentencePieceTokenizer\n'), ((4117, 4336), 'tfdlg.dialog.data.DialogClsDataset.from_generator', 'DialogClsDataset.from_generator', ([], {'generator': 'gen', 'encode_fn': 'encode_fn', 'max_len': 'self._config.context_size', 'sep_token_id': 'self._tokenizer.sep_token_id', 'batch_size': 'batch_size', 'buffer_size': 'buffer_size', 'shuffle': 'shuffle'}), '(generator=gen, encode_fn=encode_fn, max_len\n =self._config.context_size, sep_token_id=self._tokenizer.sep_token_id,\n batch_size=batch_size, buffer_size=buffer_size, shuffle=shuffle)\n', (4148, 4336), False, 'from tfdlg.dialog.data import DialogClsDataset\n'), ((3679, 3692), 'tfdlg.losses.PaddingLoss', 'PaddingLoss', ([], {}), '()\n', (3690, 3692), False, 'from tfdlg.losses import PaddingLoss\n'), ((3694, 3743), 'tensorflow.keras.losses.BinaryCrossentropy', 'keras.losses.BinaryCrossentropy', ([], {'from_logits': '(True)'}), '(from_logits=True)\n', (3725, 3743), True, 'import tensorflow.keras as keras\n'), ((1731, 1762), 'numpy.array', 'np.array', (['[ids]'], {'dtype': 'np.int32'}), '([ids], dtype=np.int32)\n', (1739, 1762), True, 'import numpy as np\n'), ((3100, 3214), 'tfdlg.dialog.tokenizers.encode_dialog', 'encode_dialog', ([], {'encode_fn': 'encode_fn', 'sep_token_id': 'self._tokenizer.sep_token_id', 'context': 'context', 'response': 'None'}), '(encode_fn=encode_fn, sep_token_id=self._tokenizer.\n sep_token_id, context=context, response=None)\n', (3113, 3214), False, 'from tfdlg.dialog.tokenizers import encode_dialog\n')]
import plotly.graph_objs as go import numpy as np def make_scatter(products_df, xcol, ycol, hovercol, tickprefix=''): f_scatter = go.FigureWidget([go.Scatter(x = products_df[xcol], y = products_df[ycol], mode = 'markers', text = [x[:30] for x in products_df[hovercol]], selected_marker_size=5, marker_size = 3, selected_marker_color='red', opacity=.8)]) scatter = f_scatter.data[0] N = len(products_df) scatter.x = scatter.x + np.random.rand(N)/100 *(products_df[xcol].max() - products_df[xcol].min()) scatter.y = scatter.y + np.random.rand(N)/100 *(products_df[ycol].max() - products_df[ycol].min()) scatter.selectedpoints = list(range(N)) f_scatter.update_layout( xaxis_title=xcol, yaxis_title=ycol, xaxis_tickprefix = tickprefix, plot_bgcolor="#FFFFFF", xaxis_linecolor="#BCCCDC", yaxis_linecolor="#BCCCDC", xaxis_fixedrange=True, yaxis_fixedrange=True, dragmode="select", clickmode="select" ) return f_scatter
[ "numpy.random.rand", "plotly.graph_objs.Scatter" ]
[((152, 356), 'plotly.graph_objs.Scatter', 'go.Scatter', ([], {'x': 'products_df[xcol]', 'y': 'products_df[ycol]', 'mode': '"""markers"""', 'text': '[x[:30] for x in products_df[hovercol]]', 'selected_marker_size': '(5)', 'marker_size': '(3)', 'selected_marker_color': '"""red"""', 'opacity': '(0.8)'}), "(x=products_df[xcol], y=products_df[ycol], mode='markers', text=[\n x[:30] for x in products_df[hovercol]], selected_marker_size=5,\n marker_size=3, selected_marker_color='red', opacity=0.8)\n", (162, 356), True, 'import plotly.graph_objs as go\n'), ((749, 766), 'numpy.random.rand', 'np.random.rand', (['N'], {}), '(N)\n', (763, 766), True, 'import numpy as np\n'), ((852, 869), 'numpy.random.rand', 'np.random.rand', (['N'], {}), '(N)\n', (866, 869), True, 'import numpy as np\n')]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Copyright 2022 <NAME> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from dataclasses import dataclass import numpy as np import pylab import ltv_mpc from ltv_mpc import solve_mpc gravity = 9.81 # [m] / [s]^2 @dataclass class HumanoidSteppingProblem: com_height: float = 0.8 dsp_duration: float = 0.1 end_pos: float = 0.3 foot_length: float = 0.1 horizon_duration: float = 2.5 nb_timesteps: int = 16 ssp_duration: float = 0.7 start_pos: float = 0.0 def build_mpc_problem(problem: HumanoidSteppingProblem): T = problem.horizon_duration / problem.nb_timesteps nb_init_dsp_steps = int(round(problem.dsp_duration / T)) nb_init_ssp_steps = int(round(problem.ssp_duration / T)) nb_dsp_steps = int(round(problem.dsp_duration / T)) state_matrix = np.array( [[1.0, T, T ** 2 / 2.0], [0.0, 1.0, T], [0.0, 0.0, 1.0]] ) input_matrix = np.array([T ** 3 / 6.0, T ** 2 / 2.0, T]) input_matrix = input_matrix.reshape((3, 1)) zmp_from_state = np.array([1.0, 0.0, -problem.com_height / gravity]) ineq_matrix = np.array([+zmp_from_state, -zmp_from_state]) cur_max = problem.start_pos + 0.5 * problem.foot_length cur_min = problem.start_pos - 0.5 * problem.foot_length next_max = problem.end_pos + 0.5 * problem.foot_length next_min = problem.end_pos - 0.5 * problem.foot_length ineq_vector = [ np.array([+1000.0, +1000.0]) if i < nb_init_dsp_steps else np.array([+cur_max, -cur_min]) if i - nb_init_dsp_steps <= nb_init_ssp_steps else np.array([+1000.0, +1000.0]) if i - nb_init_dsp_steps - nb_init_ssp_steps < nb_dsp_steps else np.array([+next_max, -next_min]) for i in range(problem.nb_timesteps) ] return ltv_mpc.Problem( transition_state_matrix=state_matrix, transition_input_matrix=input_matrix, ineq_state_matrix=ineq_matrix, ineq_input_matrix=None, ineq_vector=ineq_vector, initial_state=np.array([problem.start_pos, 0.0, 0.0]), goal_state=np.array([problem.end_pos, 0.0, 0.0]), nb_timesteps=problem.nb_timesteps, terminal_cost_weight=1.0, stage_state_cost_weight=None, stage_input_cost_weight=1e-3, ) def plot_mpc_solution(stepping_problem, mpc, solution): t = np.linspace( 0.0, stepping_problem.horizon_duration, stepping_problem.nb_timesteps + 1, ) X = solution.stacked_states zmp_from_state = np.array( [1.0, 0.0, -stepping_problem.com_height / gravity] ) zmp = X.dot(zmp_from_state) pos = X[:, 0] zmp_min = [x[0] if abs(x[0]) < 10 else None for x in mpc.ineq_vector] zmp_max = [-x[1] if abs(x[1]) < 10 else None for x in mpc.ineq_vector] zmp_min.append(zmp_min[-1]) zmp_max.append(zmp_max[-1]) pylab.ion() pylab.clf() pylab.plot(t, pos) pylab.plot(t, zmp, "r-") pylab.plot(t, zmp_min, "g:") pylab.plot(t, zmp_max, "b:") pylab.grid(True) if __name__ == "__main__": stepping_problem = HumanoidSteppingProblem() mpc_problem = build_mpc_problem(stepping_problem) solution = solve_mpc(mpc_problem) plot_mpc_solution(stepping_problem, mpc_problem, solution)
[ "ltv_mpc.solve_mpc", "pylab.ion", "pylab.plot", "pylab.grid", "numpy.array", "numpy.linspace", "pylab.clf" ]
[((1353, 1419), 'numpy.array', 'np.array', (['[[1.0, T, T ** 2 / 2.0], [0.0, 1.0, T], [0.0, 0.0, 1.0]]'], {}), '([[1.0, T, T ** 2 / 2.0], [0.0, 1.0, T], [0.0, 0.0, 1.0]])\n', (1361, 1419), True, 'import numpy as np\n'), ((1453, 1494), 'numpy.array', 'np.array', (['[T ** 3 / 6.0, T ** 2 / 2.0, T]'], {}), '([T ** 3 / 6.0, T ** 2 / 2.0, T])\n', (1461, 1494), True, 'import numpy as np\n'), ((1564, 1615), 'numpy.array', 'np.array', (['[1.0, 0.0, -problem.com_height / gravity]'], {}), '([1.0, 0.0, -problem.com_height / gravity])\n', (1572, 1615), True, 'import numpy as np\n'), ((1634, 1678), 'numpy.array', 'np.array', (['[+zmp_from_state, -zmp_from_state]'], {}), '([+zmp_from_state, -zmp_from_state])\n', (1642, 1678), True, 'import numpy as np\n'), ((2882, 2973), 'numpy.linspace', 'np.linspace', (['(0.0)', 'stepping_problem.horizon_duration', '(stepping_problem.nb_timesteps + 1)'], {}), '(0.0, stepping_problem.horizon_duration, stepping_problem.\n nb_timesteps + 1)\n', (2893, 2973), True, 'import numpy as np\n'), ((3053, 3113), 'numpy.array', 'np.array', (['[1.0, 0.0, -stepping_problem.com_height / gravity]'], {}), '([1.0, 0.0, -stepping_problem.com_height / gravity])\n', (3061, 3113), True, 'import numpy as np\n'), ((3395, 3406), 'pylab.ion', 'pylab.ion', ([], {}), '()\n', (3404, 3406), False, 'import pylab\n'), ((3411, 3422), 'pylab.clf', 'pylab.clf', ([], {}), '()\n', (3420, 3422), False, 'import pylab\n'), ((3427, 3445), 'pylab.plot', 'pylab.plot', (['t', 'pos'], {}), '(t, pos)\n', (3437, 3445), False, 'import pylab\n'), ((3450, 3474), 'pylab.plot', 'pylab.plot', (['t', 'zmp', '"""r-"""'], {}), "(t, zmp, 'r-')\n", (3460, 3474), False, 'import pylab\n'), ((3479, 3507), 'pylab.plot', 'pylab.plot', (['t', 'zmp_min', '"""g:"""'], {}), "(t, zmp_min, 'g:')\n", (3489, 3507), False, 'import pylab\n'), ((3512, 3540), 'pylab.plot', 'pylab.plot', (['t', 'zmp_max', '"""b:"""'], {}), "(t, zmp_max, 'b:')\n", (3522, 3540), False, 'import pylab\n'), ((3545, 3561), 'pylab.grid', 'pylab.grid', (['(True)'], {}), '(True)\n', (3555, 3561), False, 'import pylab\n'), ((3709, 3731), 'ltv_mpc.solve_mpc', 'solve_mpc', (['mpc_problem'], {}), '(mpc_problem)\n', (3718, 3731), False, 'from ltv_mpc import solve_mpc\n'), ((1945, 1973), 'numpy.array', 'np.array', (['[+1000.0, +1000.0]'], {}), '([+1000.0, +1000.0])\n', (1953, 1973), True, 'import numpy as np\n'), ((2558, 2597), 'numpy.array', 'np.array', (['[problem.start_pos, 0.0, 0.0]'], {}), '([problem.start_pos, 0.0, 0.0])\n', (2566, 2597), True, 'import numpy as np\n'), ((2618, 2655), 'numpy.array', 'np.array', (['[problem.end_pos, 0.0, 0.0]'], {}), '([problem.end_pos, 0.0, 0.0])\n', (2626, 2655), True, 'import numpy as np\n'), ((2020, 2050), 'numpy.array', 'np.array', (['[+cur_max, -cur_min]'], {}), '([+cur_max, -cur_min])\n', (2028, 2050), True, 'import numpy as np\n'), ((2118, 2146), 'numpy.array', 'np.array', (['[+1000.0, +1000.0]'], {}), '([+1000.0, +1000.0])\n', (2126, 2146), True, 'import numpy as np\n'), ((2228, 2260), 'numpy.array', 'np.array', (['[+next_max, -next_min]'], {}), '([+next_max, -next_min])\n', (2236, 2260), True, 'import numpy as np\n')]
import copy from matplotlib import cm import matplotlib.colors import numpy as np import hexrd.ui.constants from hexrd.ui.brightness_contrast_editor import BrightnessContrastEditor from hexrd.ui.hexrd_config import HexrdConfig from hexrd.ui.ui_loader import UiLoader from hexrd.ui.utils import block_signals class ColorMapEditor: def __init__(self, image_object, parent=None): # The image_object can be any object with the following functions: # 1. set_cmap: a function to set the cmap on the image # 2. set_norm: a function to set the norm on the image self.image_object = image_object loader = UiLoader() self.ui = loader.load_file('color_map_editor.ui', parent) self.bounds = (0, 16384) self._data = None self.bc_editor = None self.load_cmaps() self.setup_connections() @property def data(self): return self._data @data.setter def data(self, v): self._data = v self.update_bc_enable_state() if self.bc_editor: self.bc_editor.data = v self.update_bc_editor() def load_cmaps(self): cmaps = sorted(i[:-2] for i in dir(cm) if i.endswith('_r')) self.ui.color_map.addItems(cmaps) # Set the combobox to be the default self.ui.color_map.setCurrentText(hexrd.ui.constants.DEFAULT_CMAP) def setup_connections(self): self.ui.bc_editor_button.pressed.connect(self.bc_editor_button_pressed) self.ui.minimum.valueChanged.connect(self.range_edited) self.ui.maximum.valueChanged.connect(self.range_edited) self.ui.color_map.currentIndexChanged.connect(self.update_cmap) self.ui.reverse.toggled.connect(self.update_cmap) self.ui.show_under.toggled.connect(self.update_cmap) self.ui.show_over.toggled.connect(self.update_cmap) self.ui.log_scale.toggled.connect(self.update_norm) def range_edited(self): self.update_bc_editor() self.update_mins_and_maxes() self.update_norm() def update_bc_enable_state(self): has_data = self.data is not None self.ui.bc_editor_button.setEnabled(has_data) def bc_editor_button_pressed(self): if self.bc_editor: self.bc_editor.ui.reject() bc = self.bc_editor = BrightnessContrastEditor(self.ui) bc.data = self.data bc.edited.connect(self.bc_editor_modified) bc.reset.connect(self.reset_range) bc.ui.finished.connect(self.remove_bc_editor) # Hide overlays while the BC editor is open self._bc_previous_show_overlays = HexrdConfig().show_overlays if self._bc_previous_show_overlays: HexrdConfig().show_overlays = False HexrdConfig().active_material_modified.emit() self.update_bc_editor() self.bc_editor.ui.show() def update_bc_editor(self): if not self.bc_editor: return widgets = (self.ui.minimum, self.ui.maximum) new_range = [x.value() for x in widgets] with block_signals(self.bc_editor): self.bc_editor.ui_range = new_range def remove_bc_editor(self): self.bc_editor = None if self._bc_previous_show_overlays and not HexrdConfig().show_overlays: # Show the overlays again HexrdConfig().show_overlays = True HexrdConfig().active_material_modified.emit() def bc_editor_modified(self): with block_signals(self.ui.minimum, self.ui.maximum): self.ui.minimum.setValue(self.bc_editor.ui_min) self.ui.maximum.setValue(self.bc_editor.ui_max) self.range_edited() def update_mins_and_maxes(self): # We can't do this in PySide2 for some reason: # self.ui.maximum.valueChanged.connect(self.ui.minimum.setMaximum) # self.ui.minimum.valueChanged.connect(self.ui.maximum.setMinimum) self.ui.maximum.setMinimum(self.ui.minimum.value()) self.ui.minimum.setMaximum(self.ui.maximum.value()) def block_updates(self, blocked): self.updates_blocked = blocked def update_bounds(self, data): if hasattr(self, 'updates_blocked') and self.updates_blocked: # We don't want to adjust the bounds return bounds = self.percentile_range(data) self.ui.minimum.setValue(bounds[0]) self.ui.minimum.setToolTip('Min: ' + str(bounds[0])) self.ui.maximum.setValue(bounds[1]) self.ui.maximum.setToolTip('Max: ' + str(bounds[1])) self.bounds = bounds self.data = data @staticmethod def percentile_range(data, low=69.0, high=99.9): if isinstance(data, dict): values = data.values() elif not isinstance(data, (list, tuple)): values = [data] l = min([np.nanpercentile(v, low) for v in values]) h = min([np.nanpercentile(v, high) for v in values]) if h - l < 5: h = l + 5 return l, h def reset_range(self): if hasattr(self, 'updates_blocked') and self.updates_blocked: # We don't want to adjust the range return if self.ui.minimum.maximum() < self.bounds[0]: # Make sure we can actually set the value... self.ui.minimum.setMaximum(self.bounds[0]) self.ui.minimum.setValue(self.bounds[0]) self.ui.maximum.setValue(self.bounds[1]) def update_cmap(self): # Get the Colormap object from the name cmap = cm.get_cmap(self.ui.color_map.currentText()) if self.ui.reverse.isChecked(): cmap = cmap.reversed() # For set_under() and set_over(), we don't want to edit the # original color map, so make a copy cmap = copy.copy(cmap) if self.ui.show_under.isChecked(): cmap.set_under('b') if self.ui.show_over.isChecked(): cmap.set_over('r') self.image_object.set_cmap(cmap) def update_norm(self): min = self.ui.minimum.value() max = self.ui.maximum.value() if self.ui.log_scale.isChecked(): # The min cannot be 0 here, or this will raise an exception # For some reason, if it is less than 1.e-7, for some datasets, # matplotlib will round it to 0, and then raise an exception. # Thus, keep it at 1.e-7 for now. min = 1.e-7 if min < 1.e-7 else min norm = matplotlib.colors.LogNorm(vmin=min, vmax=max) else: norm = matplotlib.colors.Normalize(vmin=min, vmax=max) self.image_object.set_norm(norm)
[ "numpy.nanpercentile", "hexrd.ui.utils.block_signals", "hexrd.ui.ui_loader.UiLoader", "copy.copy", "hexrd.ui.brightness_contrast_editor.BrightnessContrastEditor", "hexrd.ui.hexrd_config.HexrdConfig" ]
[((648, 658), 'hexrd.ui.ui_loader.UiLoader', 'UiLoader', ([], {}), '()\n', (656, 658), False, 'from hexrd.ui.ui_loader import UiLoader\n'), ((2350, 2383), 'hexrd.ui.brightness_contrast_editor.BrightnessContrastEditor', 'BrightnessContrastEditor', (['self.ui'], {}), '(self.ui)\n', (2374, 2383), False, 'from hexrd.ui.brightness_contrast_editor import BrightnessContrastEditor\n'), ((5821, 5836), 'copy.copy', 'copy.copy', (['cmap'], {}), '(cmap)\n', (5830, 5836), False, 'import copy\n'), ((2655, 2668), 'hexrd.ui.hexrd_config.HexrdConfig', 'HexrdConfig', ([], {}), '()\n', (2666, 2668), False, 'from hexrd.ui.hexrd_config import HexrdConfig\n'), ((3099, 3128), 'hexrd.ui.utils.block_signals', 'block_signals', (['self.bc_editor'], {}), '(self.bc_editor)\n', (3112, 3128), False, 'from hexrd.ui.utils import block_signals\n'), ((3513, 3560), 'hexrd.ui.utils.block_signals', 'block_signals', (['self.ui.minimum', 'self.ui.maximum'], {}), '(self.ui.minimum, self.ui.maximum)\n', (3526, 3560), False, 'from hexrd.ui.utils import block_signals\n'), ((2739, 2752), 'hexrd.ui.hexrd_config.HexrdConfig', 'HexrdConfig', ([], {}), '()\n', (2750, 2752), False, 'from hexrd.ui.hexrd_config import HexrdConfig\n'), ((3372, 3385), 'hexrd.ui.hexrd_config.HexrdConfig', 'HexrdConfig', ([], {}), '()\n', (3383, 3385), False, 'from hexrd.ui.hexrd_config import HexrdConfig\n'), ((4878, 4902), 'numpy.nanpercentile', 'np.nanpercentile', (['v', 'low'], {}), '(v, low)\n', (4894, 4902), True, 'import numpy as np\n'), ((4938, 4963), 'numpy.nanpercentile', 'np.nanpercentile', (['v', 'high'], {}), '(v, high)\n', (4954, 4963), True, 'import numpy as np\n'), ((3293, 3306), 'hexrd.ui.hexrd_config.HexrdConfig', 'HexrdConfig', ([], {}), '()\n', (3304, 3306), False, 'from hexrd.ui.hexrd_config import HexrdConfig\n'), ((2787, 2800), 'hexrd.ui.hexrd_config.HexrdConfig', 'HexrdConfig', ([], {}), '()\n', (2798, 2800), False, 'from hexrd.ui.hexrd_config import HexrdConfig\n'), ((3419, 3432), 'hexrd.ui.hexrd_config.HexrdConfig', 'HexrdConfig', ([], {}), '()\n', (3430, 3432), False, 'from hexrd.ui.hexrd_config import HexrdConfig\n')]
import unittest import numpy import chainer from chainer import backend from chainer.backends import cuda from chainer import links from chainer import testing from chainer.testing import attr class TestInceptionBNBase(unittest.TestCase): in_channels = 3 out1, proj3, out3, proj33, out33, proj_pool = 3, 2, 3, 2, 3, 3 pooltype = 'max' stride = 1 batchsize = 10 insize = 10 def setup_data(self): dtype = chainer.get_dtype() self.x = numpy.random.uniform( -1, 1, (10, self.in_channels, 5, 5) ).astype(dtype) self.l = links.InceptionBN( self.in_channels, self.out1, self.proj3, self.out3, self.proj33, self.out33, self.pooltype, self.proj_pool, self.stride) def check_backward(self, x_data): xp = backend.get_array_module(x_data) x = chainer.Variable(x_data) y = self.l(x) y.grad = xp.random.randn(*y.data.shape).astype('f') y.backward() class TestInceptionBN(TestInceptionBNBase): def setUp(self): self.setup_data() def test_backward_cpu(self): self.check_backward(self.x) @attr.gpu def test_backward_gpu(self): self.l.to_gpu() self.check_backward(cuda.to_gpu(self.x)) class TestInceptionBN2(TestInceptionBN): pooltype = 'avg' class TestInceptionBN3(TestInceptionBN): out1 = 0 class TestInceptionBN4(TestInceptionBN): out1 = 0 pooltype = 'avg' class TestInceptionBN5(TestInceptionBN): out1 = 0 proj_pool = None class TestInceptionBN6(TestInceptionBN): out1 = 0 pooltype = 'avg' proj_pool = None class TestInceptionBN7(TestInceptionBN): out1 = 0 stride = 2 class TestInceptionBN8(TestInceptionBN): out1 = 0 stride = 2 proj_pool = None class TestInceptionBN9(TestInceptionBN): out1 = 0 stride = 2 pooltype = 'avg' class TestInceptionBN10(TestInceptionBN): out1 = 0 stride = 2 pooltype = 'avg' proj_pool = None class TestInceptionBNInvalidCall(TestInceptionBNBase): proj_pool = None def test_invalid_architecture(self): with self.assertRaises(AssertionError): self.setup_data() class TestInceptionBNInvalidCall2(TestInceptionBNInvalidCall): pooltype = 'avg' proj_pool = None class TestInceptionBNInvalidCall3(TestInceptionBNInvalidCall): stride = 2 class TestInceptionBNInvalidCall4(TestInceptionBNInvalidCall): stride = 2 pooltype = 'avg' class TestInceptionBNInvalidPoolType(TestInceptionBNBase): pooltype = 'invalid_pooltype' def test_invalid_pooltype(self): with self.assertRaises(NotImplementedError): self.setup_data() @testing.parameterize(*testing.product({ 'dtype': [numpy.float32, numpy.float16], })) class TestInceptionBnDtype(TestInceptionBNBase): def setUp(self): with chainer.using_config('dtype', self.dtype): self.setup_data() def test_dtype(self): link = self.l # Check the dtype of batch normalization layers. assert link.proj3n.beta.dtype == self.dtype assert link.conv3n.beta.dtype == self.dtype assert link.proj33n.beta.dtype == self.dtype assert link.conv33an.beta.dtype == self.dtype assert link.conv33bn.beta.dtype == self.dtype assert link.conv1n.beta.dtype == self.dtype assert link.poolpn.beta.dtype == self.dtype testing.run_module(__name__, __file__)
[ "chainer.Variable", "chainer.testing.run_module", "chainer.testing.product", "chainer.backend.get_array_module", "chainer.using_config", "numpy.random.uniform", "chainer.links.InceptionBN", "chainer.get_dtype", "chainer.backends.cuda.to_gpu" ]
[((3462, 3500), 'chainer.testing.run_module', 'testing.run_module', (['__name__', '__file__'], {}), '(__name__, __file__)\n', (3480, 3500), False, 'from chainer import testing\n'), ((445, 464), 'chainer.get_dtype', 'chainer.get_dtype', ([], {}), '()\n', (462, 464), False, 'import chainer\n'), ((593, 736), 'chainer.links.InceptionBN', 'links.InceptionBN', (['self.in_channels', 'self.out1', 'self.proj3', 'self.out3', 'self.proj33', 'self.out33', 'self.pooltype', 'self.proj_pool', 'self.stride'], {}), '(self.in_channels, self.out1, self.proj3, self.out3, self.\n proj33, self.out33, self.pooltype, self.proj_pool, self.stride)\n', (610, 736), False, 'from chainer import links\n'), ((821, 853), 'chainer.backend.get_array_module', 'backend.get_array_module', (['x_data'], {}), '(x_data)\n', (845, 853), False, 'from chainer import backend\n'), ((866, 890), 'chainer.Variable', 'chainer.Variable', (['x_data'], {}), '(x_data)\n', (882, 890), False, 'import chainer\n'), ((2761, 2819), 'chainer.testing.product', 'testing.product', (["{'dtype': [numpy.float32, numpy.float16]}"], {}), "({'dtype': [numpy.float32, numpy.float16]})\n", (2776, 2819), False, 'from chainer import testing\n'), ((1258, 1277), 'chainer.backends.cuda.to_gpu', 'cuda.to_gpu', (['self.x'], {}), '(self.x)\n', (1269, 1277), False, 'from chainer.backends import cuda\n'), ((2912, 2953), 'chainer.using_config', 'chainer.using_config', (['"""dtype"""', 'self.dtype'], {}), "('dtype', self.dtype)\n", (2932, 2953), False, 'import chainer\n'), ((482, 539), 'numpy.random.uniform', 'numpy.random.uniform', (['(-1)', '(1)', '(10, self.in_channels, 5, 5)'], {}), '(-1, 1, (10, self.in_channels, 5, 5))\n', (502, 539), False, 'import numpy\n')]
import os import gc import numpy as np import numpy.ma as ma import matplotlib matplotlib.use('TKAgg') import matplotlib.pyplot as plt ############################################################################### ############################################################################### ############################################################################### def plot_vband_image(v_band, gal_ID, IMAGE_DIR=None, IMAGE_FORMAT='eps', ax=None): ''' Creates a plot of the v-band flux map Parameters: =========== v_band : numpy array of shape (n,n) v_band flux map gal_ID : string MaNGA plate number - MaNGA fiberID number IMAGE_DIR : string Path of directory to store images IMAGE_FORMAT : string Format of saved image. Default is eps ax : matplotlib.pyplot axis object Axes handle on which to create plot ''' ########################################################################### # Dimensions of array #-------------------------------------------------------------------------- array_length = v_band.shape[0] # y-coordinate distance array_width = v_band.shape[1] # x-coordinate distance ########################################################################### ########################################################################### v_band_cbar_ticks = np.linspace( 0, v_band.max(), 7) for val, i in zip( v_band_cbar_ticks, range( len( v_band_cbar_ticks))): val = '%.3f' % val v_band_cbar_ticks[i] = val if ax is None: fig, ax = plt.subplots() ax.set_title( gal_ID + ' Visual Band') v_band_im = ax.imshow( v_band, origin='lower') cbar = plt.colorbar( v_band_im, ax=ax, ticks = np.linspace( 0, v_band.max(), 6)) cbar.ax.tick_params( direction='in', color='white') cbar.set_label('Visual Band Flux [$10^{-17}$ erg s$^{-1}$ cm$^{-2}$]') ax.set_xticks( np.arange( 0, array_width, 10)) ax.set_yticks( np.arange( 0, array_length, 10)) ax.tick_params( axis='both', direction='in', color='white') ax.yaxis.set_ticks_position('both') ax.xaxis.set_ticks_position('both') ax.set_xlabel('spaxel') ax.set_ylabel('spaxel') ########################################################################### ########################################################################### # Save figure #-------------------------------------------------------------------------- if IMAGE_DIR is not None: ####################################################################### # Create output directory if it does not already exist #---------------------------------------------------------------------- if not os.path.isdir( IMAGE_DIR + '/unmasked_v_band'): os.makedirs( IMAGE_DIR + '/unmasked_v_band') ####################################################################### plt.savefig( IMAGE_DIR + '/unmasked_v_band/' + gal_ID + '_v_band_raw.' + IMAGE_FORMAT, format=IMAGE_FORMAT) ####################################################################### # Figure cleanup #---------------------------------------------------------------------- #plt.show() plt.cla() plt.clf() plt.close() del cbar, v_band_im gc.collect() ####################################################################### ############################################################################### ############################################################################### ############################################################################### def plot_sMass_image(sMass, gal_ID, IMAGE_DIR=None, IMAGE_FORMAT='eps', ax=None): ''' Creates a plot of the stellar mass density map Parameters: =========== sMass : numpy array of shape (n,n) stellar mass density map gal_ID : string MaNGA plate number - MaNGA fiberID number IMAGE_DIR : string Path of directory to store images IMAGE_FORMAT : string Format of saved image. Default is eps ax : matplotlib.pyplot axis object Axes handle on which to create plot ''' ########################################################################### # Dimensions of array #-------------------------------------------------------------------------- array_length = sMass.shape[0] # y-coordinate distance array_width = sMass.shape[1] # x-coordinate distance ########################################################################### ########################################################################### sMass_max = ma.max(sMass) sMass_cbar_ticks = np.linspace( 0, sMass_max, 7) for val, i in zip( sMass_cbar_ticks, range( len( sMass_cbar_ticks))): val = '%.3f' % val sMass_cbar_ticks[i] = val if ax is None: fig, ax = plt.subplots() ax.set_title( gal_ID + ' stellar mass density') sMass_im = ax.imshow( sMass, origin='lower') cbar = plt.colorbar( sMass_im, ax=ax, ticks = sMass_cbar_ticks) cbar.ax.tick_params( direction='in', color='white') cbar.set_label(r'stellar mass density [log($M/M_\odot$)]') ax.set_xticks( np.arange( 0, array_width, 10)) ax.set_yticks( np.arange( 0, array_length, 10)) ax.tick_params( axis='both', direction='in', color='white') ax.yaxis.set_ticks_position('both') ax.xaxis.set_ticks_position('both') ax.set_xlabel('spaxel') ax.set_ylabel('spaxel') ########################################################################### ########################################################################### # Save figure #-------------------------------------------------------------------------- if IMAGE_DIR is not None: ####################################################################### # Create output directory if it does not already exist #---------------------------------------------------------------------- if not os.path.isdir( IMAGE_DIR + '/sMass'): os.makedirs( IMAGE_DIR + '/sMass') ####################################################################### plt.savefig(IMAGE_DIR + '/sMass/' + gal_ID + '_sMass.' + IMAGE_FORMAT, format=IMAGE_FORMAT) ####################################################################### # Figure cleanup #---------------------------------------------------------------------- #plt.show() plt.cla() plt.clf() plt.close() del cbar, sMass_im gc.collect() ####################################################################### ############################################################################### ############################################################################### ############################################################################### def plot_Ha_vel(Ha_vel, gal_ID, IMAGE_DIR=None, FOLDER_NAME=None, IMAGE_FORMAT='eps', FILENAME_SUFFIX=None, ax=None): ''' Creates a plot of the H-alpha velocity map. Parameters: =========== Ha_vel : numpy array of shape (n,n) H-alpha velocity map gal_ID : string MaNGA plate number - MaNGA fiberID number IMAGE_DIR : string Path of directory to store images FOLDER_NAME : string Name of folder in which to save image IMAGE_FORMAT : string Format of saved image. Default is eps FILENAME_SUFFIX : string Suffix to append to gal_ID to create image filename ax : matplotlib.pyplot figure axis object Axes handle on which to create plot ''' if ax is None: fig, ax = plt.subplots() ########################################################################### # Dimensions of array #-------------------------------------------------------------------------- array_length = Ha_vel.shape[0] # y-coordinate distance array_width = Ha_vel.shape[1] # x-coordinate distance ########################################################################### ########################################################################### minimum = np.min( Ha_vel) maximum = np.max( Ha_vel) if minimum > 0: vmax_bound = maximum vmin_bound = 0 else: vmax_bound = np.max( [np.abs(minimum), np.abs(maximum)]) vmin_bound = -vmax_bound cbar_ticks = np.linspace( vmin_bound, vmax_bound, 11, dtype='int') ax.set_title( gal_ID + r' H$\alpha$ Velocity') Ha_vel_im = ax.imshow( Ha_vel, cmap='bwr', origin='lower', vmin = vmin_bound, vmax = vmax_bound) cbar = plt.colorbar( Ha_vel_im, ax=ax, ticks = cbar_ticks) cbar.ax.tick_params( direction='in') cbar.set_label('$v_{rot}$ [km/s]') ax.set_xticks( np.arange( 0, array_width, 10)) ax.set_yticks( np.arange( 0, array_length, 10)) ax.tick_params( axis='both', direction='in') ax.yaxis.set_ticks_position('both') ax.xaxis.set_ticks_position('both') ax.set_xlabel('spaxel') ax.set_ylabel('spaxel') ########################################################################### ########################################################################### # Save figure #-------------------------------------------------------------------------- if IMAGE_DIR is not None: ########################################################################### # Create output directory if it does not already exist #-------------------------------------------------------------------------- if not os.path.isdir( IMAGE_DIR + FOLDER_NAME): os.makedirs( IMAGE_DIR + FOLDER_NAME) ########################################################################### plt.savefig( IMAGE_DIR + FOLDER_NAME + gal_ID + FILENAME_SUFFIX + IMAGE_FORMAT, format=IMAGE_FORMAT) ####################################################################### # Figure cleanup #---------------------------------------------------------------------- #plt.show() plt.cla() plt.clf() plt.close() del cbar, Ha_vel_im gc.collect() ####################################################################### ############################################################################### ############################################################################### ############################################################################### def plot_rot_curve(gal_ID, data_table, IMAGE_DIR=None, IMAGE_FORMAT=None, ax=None): ''' Plot galaxy rotation curves Parameters: =========== gal_ID : string MaNGA plate number - MaNGA fiberID number data_table : Astropy QTable Table containing measured rotational velocities at given deprojected radii IMAGE_DIR : string Path of directory to store images IMAGE_FORMAT : string Format of saved image ax : matplotlib.pyplot figure axis object Axes handle on which to create plot ''' if ax is None: fig, ax = plt.subplots( figsize=(5, 5)) ########################################################################### ax.set_title( gal_ID + ' Rotation Curves') ax.plot( data_table['deprojected_distance'], data_table['max_velocity'], 'rs', markersize=5, label='Total (pos)') ax.plot( data_table['deprojected_distance'], np.abs( data_table['min_velocity']), 'b^', markersize=5, label='Total (neg)') ax.plot( data_table['deprojected_distance'], data_table['rot_vel_avg'], 'gp', markersize=7, label='Total (avg)') ax.plot( data_table['deprojected_distance'], data_table['sVel_rot'], 'cD', markersize=4, label='Stellar mass') ax.plot( data_table['deprojected_distance'], data_table['dmVel_rot'], 'kX', markersize=7, label='Dark matter') ax.tick_params( axis='both', direction='in') ax.yaxis.set_ticks_position('both') ax.xaxis.set_ticks_position('both') ax.set_xlabel('Deprojected Radius [kpc/h]') ax.set_ylabel('Rotational Velocity [km/s]') ax.legend(loc='upper left') ########################################################################### ########################################################################### # Save figure #-------------------------------------------------------------------------- if IMAGE_DIR is not None: ####################################################################### # Create output directory if it does not already exist #---------------------------------------------------------------------- if not os.path.isdir( IMAGE_DIR + '/rot_curves'): os.makedirs( IMAGE_DIR + '/rot_curves') ####################################################################### plt.savefig( IMAGE_DIR + "/rot_curves/" + gal_ID + "_rot_curve." + IMAGE_FORMAT, format=IMAGE_FORMAT) ####################################################################### # Figure cleanup #---------------------------------------------------------------------- #plt.show() plt.cla() plt.clf() plt.close() gc.collect() ####################################################################### ############################################################################### ############################################################################### ############################################################################### def plot_mass_curve(IMAGE_DIR, IMAGE_FORMAT, gal_ID, data_table): ''' Plot the cumulative mass as a function of deprojected radius Parameters: =========== IMAGE_DIR : string Path of directory to store images IMAGE_FORMAT : string Format of saved image gal_ID : string MaNGA plate number - MaNGA fiberID number data_table : Astropy QTable Table containing measured rotational velocities at given deprojected radii ''' plt.figure( figsize=(5, 5)) plt.title( gal_ID + ' Mass Curves') plt.plot( data_table['deprojected_distance'], data_table['mass_interior'], 'gp', markersize=7, label='Total mass (avg)') plt.plot( data_table['deprojected_distance'], data_table['sMass_interior'], 'cD', markersize=4, label='Stellar mass') plt.plot( data_table['deprojected_distance'], data_table['dmMass_interior'], 'kX', markersize=7, label='Dark matter mass') plt.tick_params( axis='both', direction='in') #ax.yaxis.set_ticks_position('both') #ax.xaxis.set_ticks_position('both') plt.xlabel('Deprojected Radius [kpc/h]') plt.ylabel('Mass Interior [$M_{\odot}$]') plt.legend(loc='upper left') if IMAGE_DIR is not None: ######################################################################## # Create output directory if it does not already exist #----------------------------------------------------------------------- if not os.path.isdir( IMAGE_DIR + '/mass_curves'): os.makedirs( IMAGE_DIR + '/mass_curves') ######################################################################## ######################################################################## # Save figure #----------------------------------------------------------------------- plt.savefig( IMAGE_DIR + "/mass_curves/" + gal_ID + "_mass_curve." + IMAGE_FORMAT, format=IMAGE_FORMAT) ######################################################################## ######################################################################## # Clean up figure objects #----------------------------------------------------------------------- plt.cla() plt.clf() plt.close() gc.collect() ######################################################################## ############################################################################### ############################################################################### ############################################################################### def plot_diagnostic_panel( IMAGE_DIR, IMAGE_FORMAT, gal_ID, v_band, masked_Ha_vel, masked_vel_contour_plot, data_table): ''' Plot a two by two paneled image containging the entire v-band array, the masked H-alpha array, the masked H-alpha array containing ovals of the spaxels processed in the algorithm, and the averaged max and min rotation curves alongside the stellar mass rotation curve, Parameters: =========== IMAGE_DIR : string Path of directory to store images IMAGE_FORMAT : string Format of saved image gal_ID : string MaNGA plate number - MaNGA fiberID number v_band : numpy array of shape (n,n) v_band flux map masked_Ha_vel : numpy array of shape (n,n) Masked H-alpha velocity map masked_vel_contour_plot : numpy array of shape (n,n) Masked H-alpha velocity map showing only those spaxels within annuli data_table : Astropy QTable Table containing measured rotational velocities at given deprojected radii ''' # panel_fig, (( Ha_vel_panel, mHa_vel_panel), # ( contour_panel, rot_curve_panel)) = plt.subplots( 2, 2) panel_fig, (( v_band_panel, mHa_vel_panel), ( contour_panel, rot_curve_panel)) = plt.subplots( 2, 2) panel_fig.set_figheight( 10) panel_fig.set_figwidth( 10) plt.suptitle( gal_ID + " Diagnostic Panel", y=1.05, fontsize=16) plot_vband_image( v_band, gal_ID, ax=v_band_panel) plot_Ha_vel( masked_Ha_vel, gal_ID, ax=mHa_vel_panel) plot_Ha_vel( masked_vel_contour_plot, gal_ID, ax=contour_panel) plot_rot_curve( gal_ID, data_table, ax=rot_curve_panel) panel_fig.tight_layout() if IMAGE_DIR is not None: ######################################################################## # Create output directory if it does not already exist #----------------------------------------------------------------------- if not os.path.isdir( IMAGE_DIR + '/diagnostic_panels'): os.makedirs( IMAGE_DIR + '/diagnostic_panels') ######################################################################## ######################################################################## # Save figure #----------------------------------------------------------------------- plt.savefig( IMAGE_DIR + "/diagnostic_panels/" + gal_ID + "_diagnostic_panel." + IMAGE_FORMAT, format=IMAGE_FORMAT) ######################################################################## ######################################################################## # Figure cleanup #----------------------------------------------------------------------- plt.cla() plt.clf() plt.close( panel_fig) del panel_fig, v_band_panel, mHa_vel_panel, contour_panel, rot_curve_panel gc.collect() ########################################################################
[ "matplotlib.pyplot.ylabel", "numpy.arange", "numpy.ma.max", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.plot", "numpy.max", "matplotlib.pyplot.close", "numpy.linspace", "os.path.isdir", "numpy.min", "matplotlib.pyplot.cla", "numpy.abs", "matplotlib.pyplot.savefig", "matplotlib.use", "...
[((81, 104), 'matplotlib.use', 'matplotlib.use', (['"""TKAgg"""'], {}), "('TKAgg')\n", (95, 104), False, 'import matplotlib\n'), ((4845, 4858), 'numpy.ma.max', 'ma.max', (['sMass'], {}), '(sMass)\n', (4851, 4858), True, 'import numpy.ma as ma\n'), ((4882, 4910), 'numpy.linspace', 'np.linspace', (['(0)', 'sMass_max', '(7)'], {}), '(0, sMass_max, 7)\n', (4893, 4910), True, 'import numpy as np\n'), ((5216, 5269), 'matplotlib.pyplot.colorbar', 'plt.colorbar', (['sMass_im'], {'ax': 'ax', 'ticks': 'sMass_cbar_ticks'}), '(sMass_im, ax=ax, ticks=sMass_cbar_ticks)\n', (5228, 5269), True, 'import matplotlib.pyplot as plt\n'), ((8538, 8552), 'numpy.min', 'np.min', (['Ha_vel'], {}), '(Ha_vel)\n', (8544, 8552), True, 'import numpy as np\n'), ((8568, 8582), 'numpy.max', 'np.max', (['Ha_vel'], {}), '(Ha_vel)\n', (8574, 8582), True, 'import numpy as np\n'), ((8781, 8833), 'numpy.linspace', 'np.linspace', (['vmin_bound', 'vmax_bound', '(11)'], {'dtype': '"""int"""'}), "(vmin_bound, vmax_bound, 11, dtype='int')\n", (8792, 8833), True, 'import numpy as np\n'), ((9000, 9048), 'matplotlib.pyplot.colorbar', 'plt.colorbar', (['Ha_vel_im'], {'ax': 'ax', 'ticks': 'cbar_ticks'}), '(Ha_vel_im, ax=ax, ticks=cbar_ticks)\n', (9012, 9048), True, 'import matplotlib.pyplot as plt\n'), ((14532, 14558), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(5, 5)'}), '(figsize=(5, 5))\n', (14542, 14558), True, 'import matplotlib.pyplot as plt\n'), ((14565, 14599), 'matplotlib.pyplot.title', 'plt.title', (["(gal_ID + ' Mass Curves')"], {}), "(gal_ID + ' Mass Curves')\n", (14574, 14599), True, 'import matplotlib.pyplot as plt\n'), ((14605, 14728), 'matplotlib.pyplot.plot', 'plt.plot', (["data_table['deprojected_distance']", "data_table['mass_interior']", '"""gp"""'], {'markersize': '(7)', 'label': '"""Total mass (avg)"""'}), "(data_table['deprojected_distance'], data_table['mass_interior'],\n 'gp', markersize=7, label='Total mass (avg)')\n", (14613, 14728), True, 'import matplotlib.pyplot as plt\n'), ((14745, 14865), 'matplotlib.pyplot.plot', 'plt.plot', (["data_table['deprojected_distance']", "data_table['sMass_interior']", '"""cD"""'], {'markersize': '(4)', 'label': '"""Stellar mass"""'}), "(data_table['deprojected_distance'], data_table['sMass_interior'],\n 'cD', markersize=4, label='Stellar mass')\n", (14753, 14865), True, 'import matplotlib.pyplot as plt\n'), ((14882, 15007), 'matplotlib.pyplot.plot', 'plt.plot', (["data_table['deprojected_distance']", "data_table['dmMass_interior']", '"""kX"""'], {'markersize': '(7)', 'label': '"""Dark matter mass"""'}), "(data_table['deprojected_distance'], data_table['dmMass_interior'],\n 'kX', markersize=7, label='Dark matter mass')\n", (14890, 15007), True, 'import matplotlib.pyplot as plt\n'), ((15025, 15069), 'matplotlib.pyplot.tick_params', 'plt.tick_params', ([], {'axis': '"""both"""', 'direction': '"""in"""'}), "(axis='both', direction='in')\n", (15040, 15069), True, 'import matplotlib.pyplot as plt\n'), ((15157, 15197), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Deprojected Radius [kpc/h]"""'], {}), "('Deprojected Radius [kpc/h]')\n", (15167, 15197), True, 'import matplotlib.pyplot as plt\n'), ((15202, 15244), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Mass Interior [$M_{\\\\odot}$]"""'], {}), "('Mass Interior [$M_{\\\\odot}$]')\n", (15212, 15244), True, 'import matplotlib.pyplot as plt\n'), ((15248, 15276), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""upper left"""'}), "(loc='upper left')\n", (15258, 15276), True, 'import matplotlib.pyplot as plt\n'), ((18014, 18032), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(2)', '(2)'], {}), '(2, 2)\n', (18026, 18032), True, 'import matplotlib.pyplot as plt\n'), ((18103, 18166), 'matplotlib.pyplot.suptitle', 'plt.suptitle', (["(gal_ID + ' Diagnostic Panel')"], {'y': '(1.05)', 'fontsize': '(16)'}), "(gal_ID + ' Diagnostic Panel', y=1.05, fontsize=16)\n", (18115, 18166), True, 'import matplotlib.pyplot as plt\n'), ((1622, 1636), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (1634, 1636), True, 'import matplotlib.pyplot as plt\n'), ((1970, 1999), 'numpy.arange', 'np.arange', (['(0)', 'array_width', '(10)'], {}), '(0, array_width, 10)\n', (1979, 1999), True, 'import numpy as np\n'), ((2021, 2051), 'numpy.arange', 'np.arange', (['(0)', 'array_length', '(10)'], {}), '(0, array_length, 10)\n', (2030, 2051), True, 'import numpy as np\n'), ((2977, 3087), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(IMAGE_DIR + '/unmasked_v_band/' + gal_ID + '_v_band_raw.' + IMAGE_FORMAT)"], {'format': 'IMAGE_FORMAT'}), "(IMAGE_DIR + '/unmasked_v_band/' + gal_ID + '_v_band_raw.' +\n IMAGE_FORMAT, format=IMAGE_FORMAT)\n", (2988, 3087), True, 'import matplotlib.pyplot as plt\n'), ((3300, 3309), 'matplotlib.pyplot.cla', 'plt.cla', ([], {}), '()\n', (3307, 3309), True, 'import matplotlib.pyplot as plt\n'), ((3318, 3327), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (3325, 3327), True, 'import matplotlib.pyplot as plt\n'), ((3336, 3347), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (3345, 3347), True, 'import matplotlib.pyplot as plt\n'), ((3384, 3396), 'gc.collect', 'gc.collect', ([], {}), '()\n', (3394, 3396), False, 'import gc\n'), ((5087, 5101), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (5099, 5101), True, 'import matplotlib.pyplot as plt\n'), ((5412, 5441), 'numpy.arange', 'np.arange', (['(0)', 'array_width', '(10)'], {}), '(0, array_width, 10)\n', (5421, 5441), True, 'import numpy as np\n'), ((5463, 5493), 'numpy.arange', 'np.arange', (['(0)', 'array_length', '(10)'], {}), '(0, array_length, 10)\n', (5472, 5493), True, 'import numpy as np\n'), ((6399, 6494), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(IMAGE_DIR + '/sMass/' + gal_ID + '_sMass.' + IMAGE_FORMAT)"], {'format': 'IMAGE_FORMAT'}), "(IMAGE_DIR + '/sMass/' + gal_ID + '_sMass.' + IMAGE_FORMAT,\n format=IMAGE_FORMAT)\n", (6410, 6494), True, 'import matplotlib.pyplot as plt\n'), ((6727, 6736), 'matplotlib.pyplot.cla', 'plt.cla', ([], {}), '()\n', (6734, 6736), True, 'import matplotlib.pyplot as plt\n'), ((6745, 6754), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (6752, 6754), True, 'import matplotlib.pyplot as plt\n'), ((6763, 6774), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (6772, 6774), True, 'import matplotlib.pyplot as plt\n'), ((6810, 6822), 'gc.collect', 'gc.collect', ([], {}), '()\n', (6820, 6822), False, 'import gc\n'), ((8040, 8054), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (8052, 8054), True, 'import matplotlib.pyplot as plt\n'), ((9152, 9181), 'numpy.arange', 'np.arange', (['(0)', 'array_width', '(10)'], {}), '(0, array_width, 10)\n', (9161, 9181), True, 'import numpy as np\n'), ((9203, 9233), 'numpy.arange', 'np.arange', (['(0)', 'array_length', '(10)'], {}), '(0, array_length, 10)\n', (9212, 9233), True, 'import numpy as np\n'), ((10142, 10245), 'matplotlib.pyplot.savefig', 'plt.savefig', (['(IMAGE_DIR + FOLDER_NAME + gal_ID + FILENAME_SUFFIX + IMAGE_FORMAT)'], {'format': 'IMAGE_FORMAT'}), '(IMAGE_DIR + FOLDER_NAME + gal_ID + FILENAME_SUFFIX +\n IMAGE_FORMAT, format=IMAGE_FORMAT)\n', (10153, 10245), True, 'import matplotlib.pyplot as plt\n'), ((10458, 10467), 'matplotlib.pyplot.cla', 'plt.cla', ([], {}), '()\n', (10465, 10467), True, 'import matplotlib.pyplot as plt\n'), ((10476, 10485), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (10483, 10485), True, 'import matplotlib.pyplot as plt\n'), ((10494, 10505), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (10503, 10505), True, 'import matplotlib.pyplot as plt\n'), ((10542, 10554), 'gc.collect', 'gc.collect', ([], {}), '()\n', (10552, 10554), False, 'import gc\n'), ((11497, 11525), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(5, 5)'}), '(figsize=(5, 5))\n', (11509, 11525), True, 'import matplotlib.pyplot as plt\n'), ((11838, 11872), 'numpy.abs', 'np.abs', (["data_table['min_velocity']"], {}), "(data_table['min_velocity'])\n", (11844, 11872), True, 'import numpy as np\n'), ((13294, 13398), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(IMAGE_DIR + '/rot_curves/' + gal_ID + '_rot_curve.' + IMAGE_FORMAT)"], {'format': 'IMAGE_FORMAT'}), "(IMAGE_DIR + '/rot_curves/' + gal_ID + '_rot_curve.' +\n IMAGE_FORMAT, format=IMAGE_FORMAT)\n", (13305, 13398), True, 'import matplotlib.pyplot as plt\n'), ((13631, 13640), 'matplotlib.pyplot.cla', 'plt.cla', ([], {}), '()\n', (13638, 13640), True, 'import matplotlib.pyplot as plt\n'), ((13649, 13658), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (13656, 13658), True, 'import matplotlib.pyplot as plt\n'), ((13667, 13678), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (13676, 13678), True, 'import matplotlib.pyplot as plt\n'), ((13687, 13699), 'gc.collect', 'gc.collect', ([], {}), '()\n', (13697, 13699), False, 'import gc\n'), ((15919, 16025), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(IMAGE_DIR + '/mass_curves/' + gal_ID + '_mass_curve.' + IMAGE_FORMAT)"], {'format': 'IMAGE_FORMAT'}), "(IMAGE_DIR + '/mass_curves/' + gal_ID + '_mass_curve.' +\n IMAGE_FORMAT, format=IMAGE_FORMAT)\n", (15930, 16025), True, 'import matplotlib.pyplot as plt\n'), ((16329, 16338), 'matplotlib.pyplot.cla', 'plt.cla', ([], {}), '()\n', (16336, 16338), True, 'import matplotlib.pyplot as plt\n'), ((16347, 16356), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (16354, 16356), True, 'import matplotlib.pyplot as plt\n'), ((16365, 16376), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (16374, 16376), True, 'import matplotlib.pyplot as plt\n'), ((16385, 16397), 'gc.collect', 'gc.collect', ([], {}), '()\n', (16395, 16397), False, 'import gc\n'), ((19099, 19217), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(IMAGE_DIR + '/diagnostic_panels/' + gal_ID + '_diagnostic_panel.' +\n IMAGE_FORMAT)"], {'format': 'IMAGE_FORMAT'}), "(IMAGE_DIR + '/diagnostic_panels/' + gal_ID +\n '_diagnostic_panel.' + IMAGE_FORMAT, format=IMAGE_FORMAT)\n", (19110, 19217), True, 'import matplotlib.pyplot as plt\n'), ((19512, 19521), 'matplotlib.pyplot.cla', 'plt.cla', ([], {}), '()\n', (19519, 19521), True, 'import matplotlib.pyplot as plt\n'), ((19530, 19539), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (19537, 19539), True, 'import matplotlib.pyplot as plt\n'), ((19548, 19568), 'matplotlib.pyplot.close', 'plt.close', (['panel_fig'], {}), '(panel_fig)\n', (19557, 19568), True, 'import matplotlib.pyplot as plt\n'), ((19661, 19673), 'gc.collect', 'gc.collect', ([], {}), '()\n', (19671, 19673), False, 'import gc\n'), ((2782, 2827), 'os.path.isdir', 'os.path.isdir', (["(IMAGE_DIR + '/unmasked_v_band')"], {}), "(IMAGE_DIR + '/unmasked_v_band')\n", (2795, 2827), False, 'import os\n'), ((2842, 2885), 'os.makedirs', 'os.makedirs', (["(IMAGE_DIR + '/unmasked_v_band')"], {}), "(IMAGE_DIR + '/unmasked_v_band')\n", (2853, 2885), False, 'import os\n'), ((6224, 6259), 'os.path.isdir', 'os.path.isdir', (["(IMAGE_DIR + '/sMass')"], {}), "(IMAGE_DIR + '/sMass')\n", (6237, 6259), False, 'import os\n'), ((6274, 6307), 'os.makedirs', 'os.makedirs', (["(IMAGE_DIR + '/sMass')"], {}), "(IMAGE_DIR + '/sMass')\n", (6285, 6307), False, 'import os\n'), ((9957, 9995), 'os.path.isdir', 'os.path.isdir', (['(IMAGE_DIR + FOLDER_NAME)'], {}), '(IMAGE_DIR + FOLDER_NAME)\n', (9970, 9995), False, 'import os\n'), ((10010, 10046), 'os.makedirs', 'os.makedirs', (['(IMAGE_DIR + FOLDER_NAME)'], {}), '(IMAGE_DIR + FOLDER_NAME)\n', (10021, 10046), False, 'import os\n'), ((13109, 13149), 'os.path.isdir', 'os.path.isdir', (["(IMAGE_DIR + '/rot_curves')"], {}), "(IMAGE_DIR + '/rot_curves')\n", (13122, 13149), False, 'import os\n'), ((13164, 13202), 'os.makedirs', 'os.makedirs', (["(IMAGE_DIR + '/rot_curves')"], {}), "(IMAGE_DIR + '/rot_curves')\n", (13175, 13202), False, 'import os\n'), ((15548, 15589), 'os.path.isdir', 'os.path.isdir', (["(IMAGE_DIR + '/mass_curves')"], {}), "(IMAGE_DIR + '/mass_curves')\n", (15561, 15589), False, 'import os\n'), ((15604, 15643), 'os.makedirs', 'os.makedirs', (["(IMAGE_DIR + '/mass_curves')"], {}), "(IMAGE_DIR + '/mass_curves')\n", (15615, 15643), False, 'import os\n'), ((18716, 18763), 'os.path.isdir', 'os.path.isdir', (["(IMAGE_DIR + '/diagnostic_panels')"], {}), "(IMAGE_DIR + '/diagnostic_panels')\n", (18729, 18763), False, 'import os\n'), ((18778, 18823), 'os.makedirs', 'os.makedirs', (["(IMAGE_DIR + '/diagnostic_panels')"], {}), "(IMAGE_DIR + '/diagnostic_panels')\n", (18789, 18823), False, 'import os\n'), ((8696, 8711), 'numpy.abs', 'np.abs', (['minimum'], {}), '(minimum)\n', (8702, 8711), True, 'import numpy as np\n'), ((8713, 8728), 'numpy.abs', 'np.abs', (['maximum'], {}), '(maximum)\n', (8719, 8728), True, 'import numpy as np\n')]
import os.path import os import random import math from scipy.misc import imsave import cv2 import numpy as np from skimage.util import random_noise import math def add_noise(img, mode='gaussian', mean=0, var=0.01, level=None): """ img: 0-1 or 0-255 noisy_img: 0-255 """ if level: var = (level/255.0)**2 noisy_img = random_noise(img, mode=mode, clip=True, mean=mean, var=var) noisy_img = (noisy_img*255.0).clip(0,255).astype('uint8') return noisy_img def imread(path): # print(path) img = cv2.imread(path, cv2.IMREAD_UNCHANGED) # HWC # convert BGR to RGB img = img[:,:,[2, 1, 0]] return img def imsave(path, img): # convert RGB to BGR img = img[:,:,[2, 1, 0]] # save cv2.imwrite(path, img) def make_dataset(root, list_file_folder, shuffle=False): raw_im_list = [] items = sorted(os.listdir(os.path.join(root, list_file_folder))) for it in items: it_name = it[:-12] it_path = os.path.join(root, list_file_folder, it) f = open(it_path, "r") subits = f.read().split('\n') for idx, subit in enumerate(subits): if idx == 10: break key = '{}/{}'.format(it_name, subit.split('/')[0]) raw_im_list.append(key) if shuffle == True: random.shuffle(raw_im_list) return raw_im_list def ShortLong_loader(root, im_path, output_root, img_list, level): folder, subfolder = im_path.split('/') short_root = os.path.join(root, 'test_sharp', folder, subfolder) output_folder = os.path.join(output_root, folder) if not os.path.exists(output_folder): os.mkdir(output_folder) output_subfolder = os.path.join(output_root, folder, subfolder) if not os.path.exists(output_subfolder): os.mkdir(output_subfolder) # add gaussion noise to short imgs # noise_var = np.random.uniform(0.01, 0.1) noise_var = level for i in range(1, 22): img_name = '{:05d}.png'.format(i) path_short_path = os.path.join(short_root, img_name) output_path = os.path.join(output_subfolder, img_name) if not os.path.exists(output_path): img_short = imread(path_short_path) img_short_noisy = add_noise(img_short, var=None, level=level) imsave(output_path, img_short_noisy) print(noise_var, output_path) img_list.append(im_path+'/'+str(noise_var)+'/'+str(math.sqrt(noise_var)*255.0)) return img_list level = 60 root = '/DATA/wangshen_data/ShortLongDataset/Combined_Dataset' out_root = '/DATA/wangshen_data/ShortLongDataset/Combined_Dataset/test_noise_random' out_root = out_root+'_{}'.format(level) random.seed(0) np.random.seed(0) if not os.path.exists(out_root): os.mkdir(out_root) test_list = make_dataset(root,"test_list", shuffle=False) WRIList = [] for it in test_list: WRIList = ShortLong_loader(root, it, out_root, WRIList, level) # fl = open(os.path.join(out_root, "noise_str.txt"), 'w') # sep = '\n' # fl.write(sep.join(WRIList)) # fl.close()
[ "cv2.imwrite", "os.path.exists", "random.shuffle", "scipy.misc.imsave", "os.path.join", "math.sqrt", "random.seed", "numpy.random.seed", "skimage.util.random_noise", "os.mkdir", "cv2.imread" ]
[((2713, 2727), 'random.seed', 'random.seed', (['(0)'], {}), '(0)\n', (2724, 2727), False, 'import random\n'), ((2728, 2745), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (2742, 2745), True, 'import numpy as np\n'), ((349, 408), 'skimage.util.random_noise', 'random_noise', (['img'], {'mode': 'mode', 'clip': '(True)', 'mean': 'mean', 'var': 'var'}), '(img, mode=mode, clip=True, mean=mean, var=var)\n', (361, 408), False, 'from skimage.util import random_noise\n'), ((539, 577), 'cv2.imread', 'cv2.imread', (['path', 'cv2.IMREAD_UNCHANGED'], {}), '(path, cv2.IMREAD_UNCHANGED)\n', (549, 577), False, 'import cv2\n'), ((747, 769), 'cv2.imwrite', 'cv2.imwrite', (['path', 'img'], {}), '(path, img)\n', (758, 769), False, 'import cv2\n'), ((1509, 1560), 'os.path.join', 'os.path.join', (['root', '"""test_sharp"""', 'folder', 'subfolder'], {}), "(root, 'test_sharp', folder, subfolder)\n", (1521, 1560), False, 'import os\n'), ((1582, 1615), 'os.path.join', 'os.path.join', (['output_root', 'folder'], {}), '(output_root, folder)\n', (1594, 1615), False, 'import os\n'), ((1718, 1762), 'os.path.join', 'os.path.join', (['output_root', 'folder', 'subfolder'], {}), '(output_root, folder, subfolder)\n', (1730, 1762), False, 'import os\n'), ((2754, 2778), 'os.path.exists', 'os.path.exists', (['out_root'], {}), '(out_root)\n', (2768, 2778), False, 'import os\n'), ((2784, 2802), 'os.mkdir', 'os.mkdir', (['out_root'], {}), '(out_root)\n', (2792, 2802), False, 'import os\n'), ((984, 1024), 'os.path.join', 'os.path.join', (['root', 'list_file_folder', 'it'], {}), '(root, list_file_folder, it)\n', (996, 1024), False, 'import os\n'), ((1318, 1345), 'random.shuffle', 'random.shuffle', (['raw_im_list'], {}), '(raw_im_list)\n', (1332, 1345), False, 'import random\n'), ((1627, 1656), 'os.path.exists', 'os.path.exists', (['output_folder'], {}), '(output_folder)\n', (1641, 1656), False, 'import os\n'), ((1666, 1689), 'os.mkdir', 'os.mkdir', (['output_folder'], {}), '(output_folder)\n', (1674, 1689), False, 'import os\n'), ((1774, 1806), 'os.path.exists', 'os.path.exists', (['output_subfolder'], {}), '(output_subfolder)\n', (1788, 1806), False, 'import os\n'), ((1816, 1842), 'os.mkdir', 'os.mkdir', (['output_subfolder'], {}), '(output_subfolder)\n', (1824, 1842), False, 'import os\n'), ((2048, 2082), 'os.path.join', 'os.path.join', (['short_root', 'img_name'], {}), '(short_root, img_name)\n', (2060, 2082), False, 'import os\n'), ((2105, 2145), 'os.path.join', 'os.path.join', (['output_subfolder', 'img_name'], {}), '(output_subfolder, img_name)\n', (2117, 2145), False, 'import os\n'), ((879, 915), 'os.path.join', 'os.path.join', (['root', 'list_file_folder'], {}), '(root, list_file_folder)\n', (891, 915), False, 'import os\n'), ((2161, 2188), 'os.path.exists', 'os.path.exists', (['output_path'], {}), '(output_path)\n', (2175, 2188), False, 'import os\n'), ((2324, 2360), 'scipy.misc.imsave', 'imsave', (['output_path', 'img_short_noisy'], {}), '(output_path, img_short_noisy)\n', (2330, 2360), False, 'from scipy.misc import imsave\n'), ((2455, 2475), 'math.sqrt', 'math.sqrt', (['noise_var'], {}), '(noise_var)\n', (2464, 2475), False, 'import math\n')]
import numpy as np import scanpy as sc from scipy.sparse import csr_matrix, find from scipy.sparse.linalg import eigs class DiffusionMap: """This Diffusion Map implementation is inspired from the implementation of https://github.com/dpeerlab/Palantir/blob/master/src/palantir/utils.py """ def __init__(self, n_components=10, n_neighbors=30, alpha=0, **kwargs): self.n_components = n_components self.n_neighbors = n_neighbors self.alpha = alpha self.kwargs = kwargs def __call__(self, data): if not isinstance(data, np.ndarray): raise ValueError("The input data must be a numpy array!") print("Determing nearest neighbor graph...") temp = sc.AnnData(data) sc.pp.neighbors(temp, n_neighbors=self.n_neighbors, n_pcs=0, **self.kwargs) N = temp.shape[0] kNN = temp.obsp["distances"] # Adaptive k # This gives the lth neighbor as described in the Palantir paper adaptive_k = int(np.floor(self.n_neighbors / 10)) adaptive_std = np.zeros(N) for i in np.arange(len(adaptive_std)): # Take the distance to lth nearest neighbor as the sigm value adaptive_std[i] = np.sort(kNN.data[kNN.indptr[i] : kNN.indptr[i + 1]])[ adaptive_k - 1 ] # Kernel Construction (Anisotropic Scaling) x, y, dists = find(kNN) dists = dists / adaptive_std[x] W = csr_matrix((np.exp(-dists), (x, y)), shape=[N, N]) # Diffusion components (Make the kernel symmetric for better performance) kernel = W + W.T # Row-stochastic Normalization D = np.ravel(kernel.sum(axis=1)) if self.alpha > 0: D[D != 0] = D[D != 0] ** (-alpha) mat = csr_matrix((D, (range(N), range(N))), shape=[N, N]) kernel = mat.dot(kernel).dot(mat) D = np.ravel(kernel.sum(axis=1)) D[D != 0] = 1 / D[D != 0] T = csr_matrix((D, (range(N), range(N))), shape=[N, N]).dot(kernel) # Eigen value dcomposition # Taking the n + 1 components cause the first eigenvector is trivial # and will be removed D, V = eigs(T, self.n_components, tol=1e-4, maxiter=1000) D = np.real(D) V = np.real(V) inds = np.argsort(D)[::-1] D = D[inds] V = V[:, inds] # Account for the multi-scale distance computation # which avoids the selection of an additional t parameter for i in range(V.shape[1]): V[:, i] = V[:, i] / np.linalg.norm(V[:, i]) # Create are results dictionary return {"T": T, "eigenvectors": V, "eigenvalues": D, "kernel": kernel} def determine_multiscale_space(self, eigenvalues, eigenvectors, n_eigs=None): # Perform eigen gap analysis to select eigenvectors n_eigs = eigenvalues.shape[-1] if n_eigs is None: vals = np.ravel(eigenvalues) n_eigs = np.argsort(vals[: (len(vals) - 1)] - vals[1:])[-1] + 1 if n_eigs < 3: n_eigs = np.argsort(vals[: (len(vals) - 1)] - vals[1:])[-2] + 1 # Select eigenvalues use_eigs = list(range(1, n_eigs)) eig_vals = np.ravel(eigenvalues[use_eigs]) # Scale the data scaled_eigenvectors = eigenvectors[:, use_eigs] * (eig_vals / (1 - eig_vals)) return scaled_eigenvectors class IterativeDiffusionMap: # Does not Work def __init__(self, iterations=10, n_components=10, **kwargs): self.iterations = iterations self.kwargs = kwargs self.n_components = n_components self.map = DiffusionMap(n_components=self.n_components, **self.kwargs) def __call__(self, data): if not isinstance(data, np.ndarray): raise ValueError("The input data must be a numpy array!") print(f"Running Iterative Diffusion Maps for {self.iterations} iterations") ev = data for _ in range(self.iterations): res = self.map(ev) ev = res["eigenvectors"] return res class IterativeDiffusionMapv2: # Does not Work def __init__(self, inter, n_components=10, **kwargs): self.inter = inter self.kwargs = kwargs def __call__(self, data): if not isinstance(data, np.ndarray): raise ValueError("The input data must be a numpy array!") print(f"Running Iterative Diffusion Maps for {self.iterations} iterations") ev = data for d in self.inter: map_ = DiffusionMap(n_components=d, **self.kwargs) res = map_(ev) ev = res["eigenvectors"] return res
[ "numpy.sort", "numpy.floor", "numpy.linalg.norm", "numpy.argsort", "numpy.real", "numpy.zeros", "scanpy.pp.neighbors", "numpy.exp", "scipy.sparse.find", "scanpy.AnnData", "scipy.sparse.linalg.eigs", "numpy.ravel" ]
[((731, 747), 'scanpy.AnnData', 'sc.AnnData', (['data'], {}), '(data)\n', (741, 747), True, 'import scanpy as sc\n'), ((756, 831), 'scanpy.pp.neighbors', 'sc.pp.neighbors', (['temp'], {'n_neighbors': 'self.n_neighbors', 'n_pcs': '(0)'}), '(temp, n_neighbors=self.n_neighbors, n_pcs=0, **self.kwargs)\n', (771, 831), True, 'import scanpy as sc\n'), ((1071, 1082), 'numpy.zeros', 'np.zeros', (['N'], {}), '(N)\n', (1079, 1082), True, 'import numpy as np\n'), ((1409, 1418), 'scipy.sparse.find', 'find', (['kNN'], {}), '(kNN)\n', (1413, 1418), False, 'from scipy.sparse import csr_matrix, find\n'), ((2214, 2266), 'scipy.sparse.linalg.eigs', 'eigs', (['T', 'self.n_components'], {'tol': '(0.0001)', 'maxiter': '(1000)'}), '(T, self.n_components, tol=0.0001, maxiter=1000)\n', (2218, 2266), False, 'from scipy.sparse.linalg import eigs\n'), ((2277, 2287), 'numpy.real', 'np.real', (['D'], {}), '(D)\n', (2284, 2287), True, 'import numpy as np\n'), ((2300, 2310), 'numpy.real', 'np.real', (['V'], {}), '(V)\n', (2307, 2310), True, 'import numpy as np\n'), ((3251, 3282), 'numpy.ravel', 'np.ravel', (['eigenvalues[use_eigs]'], {}), '(eigenvalues[use_eigs])\n', (3259, 3282), True, 'import numpy as np\n'), ((1015, 1046), 'numpy.floor', 'np.floor', (['(self.n_neighbors / 10)'], {}), '(self.n_neighbors / 10)\n', (1023, 1046), True, 'import numpy as np\n'), ((2326, 2339), 'numpy.argsort', 'np.argsort', (['D'], {}), '(D)\n', (2336, 2339), True, 'import numpy as np\n'), ((2955, 2976), 'numpy.ravel', 'np.ravel', (['eigenvalues'], {}), '(eigenvalues)\n', (2963, 2976), True, 'import numpy as np\n'), ((1235, 1285), 'numpy.sort', 'np.sort', (['kNN.data[kNN.indptr[i]:kNN.indptr[i + 1]]'], {}), '(kNN.data[kNN.indptr[i]:kNN.indptr[i + 1]])\n', (1242, 1285), True, 'import numpy as np\n'), ((1483, 1497), 'numpy.exp', 'np.exp', (['(-dists)'], {}), '(-dists)\n', (1489, 1497), True, 'import numpy as np\n'), ((2583, 2606), 'numpy.linalg.norm', 'np.linalg.norm', (['V[:, i]'], {}), '(V[:, i])\n', (2597, 2606), True, 'import numpy as np\n')]
import torch from torch.utils.tensorboard import SummaryWriter from torch.nn.utils.clip_grad import clip_grad_norm_ from torch import distributions from boltzmann import protein from boltzmann.generative import transforms from boltzmann import nn from boltzmann import utils from boltzmann import training from sklearn.neighbors.kde import KernelDensity from sklearn.model_selection import GridSearchCV from simtk import openmm as mm from simtk.openmm import app import numpy as np import mdtraj as md import os import shutil import argparse from tqdm import tqdm # # Command line and logging # def parse_args(): parser = argparse.ArgumentParser( prog="train.py", description="Train generative model of molecular conformation." ) subparsers = parser.add_subparsers(dest="action") # Common io arguments io_parent_parser = argparse.ArgumentParser(add_help=False) io_parent_parser.add_argument("--save", required=True, help="basename for output") io_parent_parser.add_argument( "--overwrite", action="store_true", help="overwrite previous run" ) io_parent_parser.set_defaults(overwrite=False) io_parent_parser.add_argument("--pdb-path", required=True, help="path to pdb file") io_parent_parser.add_argument( "--validation", required=True, help="validation dataset name" ) # # Init parameters # init_parser = subparsers.add_parser( "init", help="initialize a new network", parents=[io_parent_parser] ) # Init paths and filenames init_parser.add_argument("--dcd-path", required=True, help="path to dcd file") init_parser.add_argument( "--validation-fraction", default=0.05, type=float, help="fraction of dataset to use for validation (default: %(default)g)", ) # Network parameters network_group = init_parser.add_argument_group("network parameters") network_group.add_argument( "--model-type", default="nsf-coupling", choices=[ "affine-coupling", "affine-made", "nsf-unconditional", "nsf-coupling", "nsf-made", ], help="type of model (default: %(default)s)", ) network_group.add_argument( "--coupling-layers", type=int, default=8, help="number of coupling layers (default: %(default)d)", ) network_group.add_argument( "--hidden-features", type=int, default=128, help="number of hidden features in each layer (default: %(default)d)", ) network_group.add_argument( "--hidden-layers", type=int, default=2, help="number of hidden layers (default: %(default)d)", ) network_group.add_argument( "--spline-points", type=int, default=8, help="number of spline points in NSF layers (default: %(default)d)", ) network_group.add_argument( "--dropout-fraction", type=float, default=0.0, help="strength of dropout (default: %(default)g)", ) network_group.add_argument( "--ensemble-size", type=int, default=100_000, help="size of configuration ensemble (default: %(default)d)", ) # Pretrainsformation parameters pretrans_group = init_parser.add_argument_group("pretransformation parameters") pretrans_group.add_argument( "--pretrans-type", default="quad-cdf", choices=["quad-cdf", "none"], help="pre-transform inputs before neural network (default: %(default)s)", ) pretrans_group.add_argument( "--pretrans-epochs", type=int, default=500, help="number of training epochs for pre-transformation layer (default: %(default)d)", ) pretrans_group.add_argument( "--pretrans-lr", type=float, default=1e-2, help="learning rate for pretransform training (default: %(default)g)", ) pretrans_group.add_argument( "--pretrans-batch-size", type=int, default=1024, help="batch size for pretransformation training (default: %(default)g)", ) # Noise parameters noise_group = init_parser.add_argument_group("noise parameters") noise_group.add_argument( "--training-noise", default=None, type=float, help="amount of noise to add to training examples (default: automatic)", ) noise_group.add_argument( "--min-noise", default=0.1, type=float, help="minimum example noise level for automatic training noise (default: %(default)g)", ) noise_group.add_argument( "--max-noise", default=0.7, type=float, help="maximum example noise level for automatic training noise (default: %(default)g)", ) noise_group.add_argument( "--n-noise", default=10, type=int, help="number of trial values for automatic training noise (default: %(default)g)", ) # # Training Parameters # train_parser = subparsers.add_parser( "train", help="train a network", parents=[io_parent_parser] ) # Training paths train_parser.add_argument( "--load", required=True, help="basename of network to load" ) # Loss Function parameters loss_group = train_parser.add_argument_group("loss function parameters") loss_group.add_argument( "--example-weight", type=float, default=1.0, help="weight for training by example (default: %(default)g)", ) loss_group.add_argument( "--energy-weight", type=float, default=0.0, help="weight for training by energy (default: %(default)g)", ) # Energy evaluation parameters energy_group = train_parser.add_argument_group("parameters for energy function") energy_group.add_argument( "--temperature", type=float, default=298.0, help="temperature (default: %(default)g)", ) energy_group.add_argument( "--energy-max", type=float, default=1e20, help="maximum energy (default: %(default)g)", ) energy_group.add_argument( "--energy-high", type=float, default=1e10, help="log transform energies above this value (default: %(default)g)", ) # Optimization parameters optimizer_group = train_parser.add_argument_group("optimization parameters") optimizer_group.add_argument( "--epochs", type=int, default=1000, help="number of training iterations (default: %(default)d)", ) optimizer_group.add_argument( "--batch-size", type=int, default=1024, help="size of training batch (default: %(default)d)", ) optimizer_group.add_argument( "--warmup-epochs", type=int, default=10, help="gradually raise learning rate over first WARMUP_EPOCHS (default: %(default)d)", ) optimizer_group.add_argument( "--warmup-factor", type=float, default=1000, help="learning rate starts WARMUP_FACTOR below init-lr (default: %(default)d)", ) optimizer_group.add_argument( "--init-lr", type=float, default=1e-3, help="initial learning rate (default: %(default)g)", ) optimizer_group.add_argument( "--final-lr", type=float, default=1e-4, help="final learning rate (default: %(default)g)", ) optimizer_group.add_argument( "--weight-decay", type=float, default=1e-3, help="strength of weight decay (default: %(default)g)", ) optimizer_group.add_argument( "--max-gradient", type=float, default=1000.0, help="maximum allowed gradient (default: %(default)g)", ) optimizer_group.add_argument( "--log-freq", type=int, default=10, help="how often to update tensorboard (default: %(default)d)", ) args = parser.parse_args() return args def setup_writer(args): writer = SummaryWriter(log_dir=f"runs/{args.save}", purge_step=0, flush_secs=30) setup_custom_scalars(args, writer) return writer def setup_custom_scalars(args, writer): writer.add_custom_scalars( { "Sampling": { "acceptance rate": ["Multiline", ["acceptance_rate"]], "step size": ["Multiline", ["step_size"]], "gradient norm": ["Multiline", ["gradient_norm"]], }, "Total Losses (weighted)": { "total loss": ["Multiline", ["total_loss"]], "energy loss": ["Multiline", ["weighted_energy_total_loss"]], "example loss": ["Multiline", ["weighted_example_total_loss"]], }, "Example Losses (unweighted)": { "total": [ "Multiline", ["example_total_loss", "val_example_total_loss"], ], "ml": ["Multiline", ["example_ml_loss", "val_example_ml_loss"]], "jac": ["Multiline", ["example_jac_loss", "val_example_jac_loss"]], }, "Energy Losses (unweighted)": { "total": ["Multiline", ["energy_total_loss"]], "ml": ["Multiline", ["energy_kl_loss"]], "jac": ["Multiline", ["energy_jac_loss"]], }, "Generative Energies": { "minimum": ["Multiline", ["minimum_energy"]], "mean": ["Multiline", ["mean_energy"]], "median": ["Multiline", ["median_energy"]], }, } ) # # File input / output # def delete_run(name): if os.path.exists(f"models/{name}.pkl"): os.remove(f"models/{name}.pkl") if os.path.exists(f"gen_samples/{name}.pdb"): os.remove(f"gen_samples/{name}.pdb") if os.path.exists(f"ensembles/{name}.dcd"): os.remove(f"ensembles/{name}.dcd") if os.path.exists(f"runs/{name}"): shutil.rmtree(f"runs/{name}") def create_dirs(): os.makedirs("models", exist_ok=True) os.makedirs("gen_samples", exist_ok=True) os.makedirs("ensembles", exist_ok=True) os.makedirs("validation", exist_ok=True) def load_trajectory(pdb_path, dcd_path, align=False): t = md.load(dcd_path, top=pdb_path) if align: ind = t.topology.select("backbone") t.superpose(t, frame=0, atom_indices=ind) return t def load_network(path, device): net = torch.load(path).to(device) print(net) print_number_trainable_params(net) return net # # Build network # def build_affine_coupling( n_dim, n_coupling, hidden_layers, hidden_features, dropout_fraction ): layers = [] for _ in range(n_coupling): p = transforms.RandomPermutation(n_dim, 1) mask_even = utils.create_alternating_binary_mask(features=n_dim, even=True) mask_odd = utils.create_alternating_binary_mask(features=n_dim, even=False) t1 = transforms.AffineCouplingTransform( mask=mask_even, transform_net_create_fn=lambda in_features, out_features: nn.ResidualNet( in_features=in_features, out_features=out_features, hidden_features=hidden_features, num_blocks=hidden_layers, dropout_probability=dropout_fraction, use_batch_norm=False, ), ) t2 = transforms.AffineCouplingTransform( mask=mask_odd, transform_net_create_fn=lambda in_features, out_features: nn.ResidualNet( in_features=in_features, out_features=out_features, hidden_features=hidden_features, num_blocks=hidden_layers, dropout_probability=dropout_fraction, use_batch_norm=False, ), ) layers.append(p) layers.append(t1) layers.append(t2) return layers def build_affine_made(n_dim, hidden_layers, hidden_features, dropout_fraction): made = transforms.MaskedAffineAutoregressiveTransform( n_dim, hidden_features=hidden_features, num_blocks=hidden_layers, dropout_probability=dropout_fraction, use_batch_norm=False, ) return [made] def build_nsf_unconditional(n_dim, spline_points): nsf = transforms.PiecewiseRationalQuadraticCDF( [n_dim], num_bins=spline_points, tails="linear", tail_bound=15, identity_init=True, ) return [nsf] def build_nsf_coupling( n_dim, n_coupling, spline_points, hidden_layers, hidden_features, dropout_fraction ): layers = [] for _ in range(n_coupling): p = transforms.RandomPermutation(n_dim, 1) mask_even = utils.create_alternating_binary_mask(features=n_dim, even=True) mask_odd = utils.create_alternating_binary_mask(features=n_dim, even=False) t1 = transforms.PiecewiseRationalQuadraticCouplingTransform( mask=mask_even, transform_net_create_fn=lambda in_features, out_features: nn.ResidualNet( in_features=in_features, out_features=out_features, hidden_features=hidden_features, num_blocks=hidden_layers, dropout_probability=dropout_fraction, use_batch_norm=False, ), tails="linear", tail_bound=15, num_bins=spline_points, apply_unconditional_transform=False, ) t2 = transforms.PiecewiseRationalQuadraticCouplingTransform( mask=mask_odd, transform_net_create_fn=lambda in_features, out_features: nn.ResidualNet( in_features=in_features, out_features=out_features, hidden_features=hidden_features, num_blocks=hidden_layers, dropout_probability=dropout_fraction, use_batch_norm=False, ), tails="linear", tail_bound=15, num_bins=spline_points, apply_unconditional_transform=False, ) layers.append(p) layers.append(t1) layers.append(t2) return layers def build_nsf_made( n_dim, spline_points, hidden_layers, hidden_features, dropout_fraction ): made = transforms.MaskedPiecewiseRationalQuadraticAutoregressiveTransform( features=n_dim, hidden_features=hidden_features, num_blocks=hidden_layers, dropout_probability=dropout_fraction, use_batch_norm=False, num_bins=spline_points, tails="linear", tail_bound=15, ) return [made] def build_network( model_type, n_dim, topology, training_data, n_coupling, spline_points, hidden_features, hidden_layers, dropout_fraction, pretrans_type, pretrans_epochs, pretrans_lr, pretrans_batch_size, device, ): training_data = training_data.to(device) print("Creating network") stage1_layers = [] # Create the mixed transofrm layer pca_block = protein.PCABlock("backbone", True) mixed = protein.MixedTransform(n_dim, topology, [pca_block], training_data) stage1_layers.append(mixed) if pretrans_type == "quad-cdf": print() print("Pre-training unconditional NSF layer") print() unconditional = build_nsf_unconditional(n_dim - 6, spline_points)[0] stage1_layers.append(unconditional) unconditional_net = transforms.CompositeTransform(stage1_layers).to(device) pre_train_unconditional_nsf( unconditional_net, device, training_data, pretrans_batch_size, pretrans_epochs, pretrans_lr, 10, ) print() print("Pretraining completed. Freezing weights") unconditional.unnormalized_heights.requires_grad_(False) unconditional.unnormalized_widths.requires_grad_(False) unconditional.unnormalized_derivatives.requires_grad_(False) stage1 = unconditional_net else: stage1 = transforms.CompositeTransform(head_layers).to(device) if model_type == "affine-coupling": stage2_layers = build_affine_coupling( n_dim - 6, n_coupling, hidden_layers, hidden_features, dropout_fraction ) elif model_type == "affine-made": stage2_layers = build_affine_made( n_dim - 6, hidden_layers, hidden_features, dropout_fraction ) elif model_type == "nsf-unconditional": stage2_layers = build_nsf_unconditional(n_dim - 6, spline_points) elif model_type == "nsf-coupling": stage2_layers = build_nsf_coupling( n_dim - 6, n_coupling, spline_points, hidden_layers, hidden_features, dropout_fraction, ) elif model_type == "nsf-made": stage2_layers = build_nsf_made( n_dim - 6, spline_points, hidden_layers, hidden_features, dropout_fraction ) else: raise RuntimeError() stage2 = transforms.CompositeTransform(stage2_layers).to(device) net = transforms.TwoStageComposite(stage1, stage2) print() print("Network constructed.") print(net) print_number_trainable_params(net) print() return net def print_number_trainable_params(net): total_params = sum(p.numel() for p in net.parameters() if p.requires_grad) print() print(f"Network has {total_params} trainable parameters") print() # # Energy function # def get_openmm_context(pdb_path): pdb = app.PDBFile(pdb_path) ff = app.ForceField("amber99sbildn.xml", "amber99_obc.xml") system = ff.createSystem( pdb.topology, nonbondedMethod=app.CutoffNonPeriodic, nonbondedCutoff=1.0, constraints=None, ) integrator = mm.LangevinIntegrator(298, 1.0, 0.002) simulation = app.Simulation(pdb.topology, system, integrator) context = simulation.context return context def get_energy_evaluator(openmm_context, temperature, energy_high, energy_max, device): energy_high = torch.tensor( energy_high, dtype=torch.float32, device=device, requires_grad=False ) energy_max = torch.tensor( energy_max, dtype=torch.float32, device=device, requires_grad=False ) def eval_energy(x): return protein.regularize_energy( protein.openmm_energy(x, openmm_context, temperature), energy_high, energy_max, ) return eval_energy # # Optimizer # def setup_optimizer(net, init_lr, weight_decay): optimizer = torch.optim.AdamW( net.parameters(), lr=init_lr, weight_decay=weight_decay ) return optimizer def setup_scheduler(optimizer, init_lr, final_lr, epochs, warmup_epochs, warmup_factor): anneal = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, epochs, final_lr) warmup = utils.GradualWarmupScheduler( optimizer, warmup_factor, warmup_epochs, after_scheduler=anneal ) return warmup # # Loss functions # def get_ml_loss(net, x_batch, example_weight, dist): z, z_jac = net.forward(x_batch) example_ml_loss = -torch.mean(dist.log_prob(z)) * example_weight example_jac_loss = -torch.mean(z_jac) * example_weight example_loss = example_ml_loss + example_jac_loss return example_loss, example_ml_loss, example_jac_loss # # Training # def get_device(): if torch.cuda.is_available(): print("Using cuda") device = torch.device("cuda") else: print("Using CPU") device = torch.device("cpu") return device def pre_train_unconditional_nsf( net, device, training_data, batch_size, epochs, lr, out_freq ): mu = torch.zeros(training_data.shape[-1] - 6, device=device) cov = torch.eye(training_data.shape[-1] - 6, device=device) dist = distributions.MultivariateNormal(mu, covariance_matrix=cov).expand( (batch_size,) ) indices = np.arange(training_data.shape[0]) optimizer = setup_optimizer(net, lr, 0.0) with tqdm(range(epochs)) as progress: for epoch in progress: net.train() index_batch = np.random.choice( indices, args.pretrans_batch_size, replace=True ) x_batch = training_data[index_batch, :] loss, _, _ = get_ml_loss(net, x_batch, 1.0, dist) optimizer.zero_grad() loss.backward() optimizer.step() if epoch % out_freq == 0: progress.set_postfix(loss=f"{loss.item():8.3f}") def train_network(args, device): writer = setup_writer(args) dcd_path = f"ensembles/{args.load}.dcd" traj = load_trajectory(args.pdb_path, dcd_path, align=False) traj.unitcell_lengths = None traj.unitcell_angles = None n_dim = traj.xyz.shape[1] * 3 ensemble = traj.xyz.reshape(-1, n_dim) ensemble = torch.from_numpy(ensemble.astype("float32")) print(f"Ensemble has size {ensemble.shape[0]} x {ensemble.shape[1]}.\n") validation_dcd_path = f"validation/{args.validation}.dcd" valid_traj = load_trajectory(args.pdb_path, validation_dcd_path, align=False) n_valid_dim = valid_traj.xyz.shape[1] * 3 validation_data = valid_traj.xyz.reshape(-1, n_valid_dim) validation_data = torch.from_numpy(validation_data.astype("float32")).to(device) print( f"Validation has size {validation_data.shape[0]} x {validation_data.shape[1]}.\n" ) net = load_network(f"models/{args.load}.pkl", device=device) optimizer = setup_optimizer( net=net, init_lr=args.init_lr / args.warmup_factor, weight_decay=args.weight_decay, ) scheduler = setup_scheduler( optimizer, init_lr=args.init_lr, final_lr=args.final_lr, epochs=args.epochs, warmup_epochs=args.warmup_epochs, warmup_factor=args.warmup_factor, ) openmm_context = get_openmm_context(args.pdb_path) energy_evaluator = get_energy_evaluator( openmm_context=openmm_context, temperature=args.temperature, energy_high=args.energy_high, energy_max=args.energy_max, device=device, ) trainer = MixedLossTrainer( net, device, ensemble, validation_data, args.batch_size, energy_evaluator ) with tqdm(range(args.epochs)) as progress: for epoch in progress: net.train() trainer.compute_training_losses() loss = ( trainer.forward_loss * args.example_weight + trainer.inverse_loss * args.energy_weight ) optimizer.zero_grad() loss.backward() gradient_norm = clip_grad_norm_(net.parameters(), args.max_gradient) optimizer.step() scheduler.step(epoch) validation_step = epoch % args.log_freq == 0 if validation_step: net.eval() trainer.compute_validation_losses() writer.add_scalar( "val_example_ml_loss", trainer.val_forward_ml.item(), epoch ) writer.add_scalar( "val_example_jac_loss", trainer.val_forward_jac.item(), epoch ) writer.add_scalar( "val_example_total_loss", trainer.val_forward_loss.item(), epoch ) # Output our training losses # writer.add_scalar( # "acceptance_rate", trainer.acceptance_probs[-1], epoch # ) # writer.add_scalar("step_size", trainer.step_size, epoch) writer.add_scalar("total_loss", loss.item(), epoch) writer.add_scalar("gradient_norm", gradient_norm, epoch) writer.add_scalar("example_ml_loss", trainer.forward_ml, epoch) writer.add_scalar("example_jac_loss", trainer.forward_jac, epoch) writer.add_scalar("example_total_loss", trainer.forward_loss, epoch) writer.add_scalar( "weighted_example_total_loss", trainer.forward_loss * args.example_weight, epoch, ) writer.add_scalar("energy_kl_loss", trainer.inverse_kl, epoch) writer.add_scalar("energy_jac_loss", trainer.inverse_jac, epoch) writer.add_scalar("energy_total_loss", trainer.inverse_loss, epoch) writer.add_scalar( "weighted_energy_total_loss", trainer.inverse_loss * args.energy_weight, epoch, ) writer.add_scalar("minimum_energy", trainer.min_energy.item(), epoch) writer.add_scalar("median_energy", trainer.median_energy.item(), epoch) writer.add_scalar("mean_energy", trainer.mean_energy.item(), epoch) progress.set_postfix(loss=f"{loss.item():8.3f}") # Save our final model torch.save(net, f"models/{args.save}.pkl") # Save our reservoir x = trainer.reservoir.cpu().detach().numpy() x = x.reshape(trainer.res_size, -1, 3) traj.xyz = x traj.save(f"ensembles/{args.save}.dcd") # Generate examples and write trajectory net.eval() z = torch.normal(0, 1, size=(args.batch_size, n_dim - 6), device=device) x, _ = net.inverse(z) x = x.cpu().detach().numpy() x = x.reshape(args.batch_size, -1, 3) traj.xyz = x traj.save(f"gen_samples/{args.save}.dcd") def calculate_example_noise(net, training_data, min_noise, max_noise, n_noise): # Run all training data through the pretransformation stage of the network transformed_data, _ = net.stage1_forward(training_data) transformed_data = transformed_data.cpu().detach().numpy() np.random.shuffle(transformed_data) params = {"bandwidth": np.linspace(min_noise, max_noise, n_noise)} grid = GridSearchCV( KernelDensity(kernel="gaussian", atol=1e-4, rtol=1e-4), params, cv=3, return_train_score=False, ) grid.fit(transformed_data) # Use cross-validation to identify the optimal noise bandwidth. return grid.best_params_["bandwidth"] def init_ensemble(ensemble_size, data): if data.shape[0] != ensemble_size: print( f"Generating ensemble by sampling from {data.shape[0]} to {ensemble_size}.\n" ) sampled = np.random.choice( np.arange(data.shape[0]), ensemble_size, replace=True ) ensemble = data[sampled, :] else: ensemble = data return ensemble def init_network(args, device): traj = load_trajectory(args.pdb_path, args.dcd_path, align=True) traj.unitcell_lengths = None traj.unitcell_angles = None n_dim = traj.xyz.shape[1] * 3 training_data_npy = traj.xyz.reshape(-1, n_dim) # Shuffle the training data for later training / test split np.random.shuffle(training_data_npy) training_data = torch.from_numpy(training_data_npy.astype("float32")) print( f"Trajectory loaded with size {training_data.shape[0]} x {training_data.shape[1]}" ) net = build_network( n_dim=n_dim, model_type=args.model_type, topology=traj.topology, training_data=training_data, n_coupling=args.coupling_layers, spline_points=args.spline_points, hidden_features=args.hidden_features, hidden_layers=args.hidden_layers, dropout_fraction=args.dropout_fraction, pretrans_type=args.pretrans_type, pretrans_epochs=args.pretrans_epochs, pretrans_lr=args.pretrans_lr, pretrans_batch_size=args.pretrans_batch_size, device=device, ) if args.training_noise is None: print( f"Using automatic noise level detection with {args.n_noise} trials from {args.min_noise} to {args.max_noise}." ) net.example_noise = calculate_example_noise( net, training_data.to(device), args.min_noise, args.max_noise, args.n_noise ) print(f"Using automatically determined noise level {net.example_noise}.\n") else: net.example_noise = args.training_noise print(f"Using noise level {net.example_noise} specified on command line.\n") # We do this just to test if we can. openmm_context_ = get_openmm_context(args.pdb_path) # Set aside our validation dataset and create our initial ensemble. n_valid = int(training_data.shape[0] * args.validation_fraction) n_train = training_data.shape[0] - n_valid print( f"Splitting data into training ({n_train} points) and validation ({n_valid} points) sets.\n" ) validation_data = training_data[:n_valid, :] training_data = training_data[n_valid:, :] ensemble = init_ensemble(args.ensemble_size, training_data) # Save everything torch.save(net, f"models/{args.save}.pkl") x = ensemble.cpu().detach().numpy() x = x.reshape(args.ensemble_size, -1, 3) traj.xyz = x traj.save(f"ensembles/{args.save}.dcd") y = validation_data.cpu().detach().numpy() y = y.reshape(n_valid, -1, 3) traj.xyz = y traj.save(f"validation/{args.validation}.dcd") class MixedLossTrainer: def __init__( self, net, device, training_data, validation_data, batch_size, energy_evaluator ): self.net = net self.device = device self.training_data = training_data self.validation_data = validation_data self.batch_size = batch_size self.energy_evaluator = energy_evaluator self.training_indices = np.arange(self.training_data.shape[0]) self.validation_indices = np.arange(self.validation_data.shape[0]) # Setup latent gaussian distribution mu = torch.zeros(self.training_data.shape[-1] - 6, device=device) cov = torch.eye(self.training_data.shape[-1] - 6, device=device) self.latent_distribution = distributions.MultivariateNormal( mu, covariance_matrix=cov ).expand((self.batch_size,)) # These statistics are updated during training. self.forward_loss = None self.forward_ml = None self.forward_jac = None self.val_forward_loss = None self.val_forward_ml = None self.val_forward_jac = None self.inverse_loss = None self.inverse_kl = None self.inverse_jac = None self.mean_energy = None self.median_energy = None self.min_energy = None self.acceptance_probs = [] def compute_training_losses(self): with torch.no_grad(): # choose random examples example_ind = np.random.choice( self.training_indices, size=self.batch_size, replace=True ) x = self.training_data[example_ind, :].to(self.device) # transform through stage1 z_pretrans, _ = self.net.stage1_forward(x) # add noise z_pretrans = z_pretrans + torch.normal( 0, self.net.example_noise, size=z_pretrans.shape, device=z_pretrans.device, ) # transform back to x x, _ = self.net.stage1_inverse(z_pretrans) # transform through full network z, z_jac = self.net.forward(x) # compute loss self.forward_ml = -torch.mean(self.latent_distribution.log_prob(z)) self.forward_jac = -torch.mean(z_jac) self.forward_loss = self.forward_ml + self.forward_jac # choose random latent and compute losses z_prime = self.latent_distribution.sample().to(self.device) x_prime, x_jac_prime = self.net.inverse(z_prime) energies = self.energy_evaluator(x_prime) self.min_energy = torch.min(energies) self.median_energy = torch.median(energies) self.mean_energy = torch.mean(energies) self.inverse_kl = torch.mean(energies) self.inverse_jac = -torch.mean(x_jac_prime) self.inverse_loss = self.inverse_kl + self.inverse_jac def compute_validation_losses(self): with torch.no_grad(): valid_ind = np.random.choice( self.validation_indices, size=self.batch_size, replace=True ) x_valid = self.validation_data[valid_ind, :].to(self.device) z_valid, z_jac_valid = self.net.forward(x_valid) self.val_forward_ml = -torch.mean( self.latent_distribution.log_prob(z_valid) ) self.val_forward_jac = -torch.mean(z_jac_valid) self.val_forward_loss = self.val_forward_ml + self.val_forward_jac if __name__ == "__main__": args = parse_args() model_path = f"models/{args.save}.pkl" if os.path.exists(model_path): if args.overwrite: print(f"Warning: output `{model_path}' already exists. Overwriting anyway.") else: raise RuntimeError( f"Output '{model_path}' already exists. If you're sure use --overwrite." ) delete_run(args.save) create_dirs() device = get_device() if args.action == "init": init_network(args, device) elif args.action == "train": train_network(args, device) else: raise RuntimeError(f"Unknown command {args.action}.")
[ "boltzmann.generative.transforms.PiecewiseRationalQuadraticCDF", "torch.min", "torch.cuda.is_available", "boltzmann.utils.GradualWarmupScheduler", "simtk.openmm.app.PDBFile", "torch.normal", "simtk.openmm.app.ForceField", "numpy.arange", "os.remove", "torch.utils.tensorboard.SummaryWriter", "os....
[((630, 740), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'prog': '"""train.py"""', 'description': '"""Train generative model of molecular conformation."""'}), "(prog='train.py', description=\n 'Train generative model of molecular conformation.')\n", (653, 740), False, 'import argparse\n'), ((854, 893), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'add_help': '(False)'}), '(add_help=False)\n', (877, 893), False, 'import argparse\n'), ((8174, 8245), 'torch.utils.tensorboard.SummaryWriter', 'SummaryWriter', ([], {'log_dir': 'f"""runs/{args.save}"""', 'purge_step': '(0)', 'flush_secs': '(30)'}), "(log_dir=f'runs/{args.save}', purge_step=0, flush_secs=30)\n", (8187, 8245), False, 'from torch.utils.tensorboard import SummaryWriter\n'), ((9816, 9852), 'os.path.exists', 'os.path.exists', (['f"""models/{name}.pkl"""'], {}), "(f'models/{name}.pkl')\n", (9830, 9852), False, 'import os\n'), ((9901, 9942), 'os.path.exists', 'os.path.exists', (['f"""gen_samples/{name}.pdb"""'], {}), "(f'gen_samples/{name}.pdb')\n", (9915, 9942), False, 'import os\n'), ((9996, 10035), 'os.path.exists', 'os.path.exists', (['f"""ensembles/{name}.dcd"""'], {}), "(f'ensembles/{name}.dcd')\n", (10010, 10035), False, 'import os\n'), ((10087, 10117), 'os.path.exists', 'os.path.exists', (['f"""runs/{name}"""'], {}), "(f'runs/{name}')\n", (10101, 10117), False, 'import os\n'), ((10182, 10218), 'os.makedirs', 'os.makedirs', (['"""models"""'], {'exist_ok': '(True)'}), "('models', exist_ok=True)\n", (10193, 10218), False, 'import os\n'), ((10223, 10264), 'os.makedirs', 'os.makedirs', (['"""gen_samples"""'], {'exist_ok': '(True)'}), "('gen_samples', exist_ok=True)\n", (10234, 10264), False, 'import os\n'), ((10269, 10308), 'os.makedirs', 'os.makedirs', (['"""ensembles"""'], {'exist_ok': '(True)'}), "('ensembles', exist_ok=True)\n", (10280, 10308), False, 'import os\n'), ((10313, 10353), 'os.makedirs', 'os.makedirs', (['"""validation"""'], {'exist_ok': '(True)'}), "('validation', exist_ok=True)\n", (10324, 10353), False, 'import os\n'), ((10418, 10449), 'mdtraj.load', 'md.load', (['dcd_path'], {'top': 'pdb_path'}), '(dcd_path, top=pdb_path)\n', (10425, 10449), True, 'import mdtraj as md\n'), ((12202, 12384), 'boltzmann.generative.transforms.MaskedAffineAutoregressiveTransform', 'transforms.MaskedAffineAutoregressiveTransform', (['n_dim'], {'hidden_features': 'hidden_features', 'num_blocks': 'hidden_layers', 'dropout_probability': 'dropout_fraction', 'use_batch_norm': '(False)'}), '(n_dim, hidden_features=\n hidden_features, num_blocks=hidden_layers, dropout_probability=\n dropout_fraction, use_batch_norm=False)\n', (12248, 12384), False, 'from boltzmann.generative import transforms\n'), ((12503, 12631), 'boltzmann.generative.transforms.PiecewiseRationalQuadraticCDF', 'transforms.PiecewiseRationalQuadraticCDF', (['[n_dim]'], {'num_bins': 'spline_points', 'tails': '"""linear"""', 'tail_bound': '(15)', 'identity_init': '(True)'}), "([n_dim], num_bins=spline_points,\n tails='linear', tail_bound=15, identity_init=True)\n", (12543, 12631), False, 'from boltzmann.generative import transforms\n'), ((14510, 14780), 'boltzmann.generative.transforms.MaskedPiecewiseRationalQuadraticAutoregressiveTransform', 'transforms.MaskedPiecewiseRationalQuadraticAutoregressiveTransform', ([], {'features': 'n_dim', 'hidden_features': 'hidden_features', 'num_blocks': 'hidden_layers', 'dropout_probability': 'dropout_fraction', 'use_batch_norm': '(False)', 'num_bins': 'spline_points', 'tails': '"""linear"""', 'tail_bound': '(15)'}), "(features\n =n_dim, hidden_features=hidden_features, num_blocks=hidden_layers,\n dropout_probability=dropout_fraction, use_batch_norm=False, num_bins=\n spline_points, tails='linear', tail_bound=15)\n", (14576, 14780), False, 'from boltzmann.generative import transforms\n'), ((15286, 15320), 'boltzmann.protein.PCABlock', 'protein.PCABlock', (['"""backbone"""', '(True)'], {}), "('backbone', True)\n", (15302, 15320), False, 'from boltzmann import protein\n'), ((15333, 15400), 'boltzmann.protein.MixedTransform', 'protein.MixedTransform', (['n_dim', 'topology', '[pca_block]', 'training_data'], {}), '(n_dim, topology, [pca_block], training_data)\n', (15355, 15400), False, 'from boltzmann import protein\n'), ((17384, 17428), 'boltzmann.generative.transforms.TwoStageComposite', 'transforms.TwoStageComposite', (['stage1', 'stage2'], {}), '(stage1, stage2)\n', (17412, 17428), False, 'from boltzmann.generative import transforms\n'), ((17833, 17854), 'simtk.openmm.app.PDBFile', 'app.PDBFile', (['pdb_path'], {}), '(pdb_path)\n', (17844, 17854), False, 'from simtk.openmm import app\n'), ((17864, 17918), 'simtk.openmm.app.ForceField', 'app.ForceField', (['"""amber99sbildn.xml"""', '"""amber99_obc.xml"""'], {}), "('amber99sbildn.xml', 'amber99_obc.xml')\n", (17878, 17918), False, 'from simtk.openmm import app\n'), ((18096, 18134), 'simtk.openmm.LangevinIntegrator', 'mm.LangevinIntegrator', (['(298)', '(1.0)', '(0.002)'], {}), '(298, 1.0, 0.002)\n', (18117, 18134), True, 'from simtk import openmm as mm\n'), ((18152, 18200), 'simtk.openmm.app.Simulation', 'app.Simulation', (['pdb.topology', 'system', 'integrator'], {}), '(pdb.topology, system, integrator)\n', (18166, 18200), False, 'from simtk.openmm import app\n'), ((18361, 18448), 'torch.tensor', 'torch.tensor', (['energy_high'], {'dtype': 'torch.float32', 'device': 'device', 'requires_grad': '(False)'}), '(energy_high, dtype=torch.float32, device=device, requires_grad\n =False)\n', (18373, 18448), False, 'import torch\n'), ((18475, 18561), 'torch.tensor', 'torch.tensor', (['energy_max'], {'dtype': 'torch.float32', 'device': 'device', 'requires_grad': '(False)'}), '(energy_max, dtype=torch.float32, device=device, requires_grad=\n False)\n', (18487, 18561), False, 'import torch\n'), ((19087, 19158), 'torch.optim.lr_scheduler.CosineAnnealingLR', 'torch.optim.lr_scheduler.CosineAnnealingLR', (['optimizer', 'epochs', 'final_lr'], {}), '(optimizer, epochs, final_lr)\n', (19129, 19158), False, 'import torch\n'), ((19172, 19269), 'boltzmann.utils.GradualWarmupScheduler', 'utils.GradualWarmupScheduler', (['optimizer', 'warmup_factor', 'warmup_epochs'], {'after_scheduler': 'anneal'}), '(optimizer, warmup_factor, warmup_epochs,\n after_scheduler=anneal)\n', (19200, 19269), False, 'from boltzmann import utils\n'), ((19698, 19723), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (19721, 19723), False, 'import torch\n'), ((19995, 20050), 'torch.zeros', 'torch.zeros', (['(training_data.shape[-1] - 6)'], {'device': 'device'}), '(training_data.shape[-1] - 6, device=device)\n', (20006, 20050), False, 'import torch\n'), ((20061, 20114), 'torch.eye', 'torch.eye', (['(training_data.shape[-1] - 6)'], {'device': 'device'}), '(training_data.shape[-1] - 6, device=device)\n', (20070, 20114), False, 'import torch\n'), ((20237, 20270), 'numpy.arange', 'np.arange', (['training_data.shape[0]'], {}), '(training_data.shape[0])\n', (20246, 20270), True, 'import numpy as np\n'), ((25313, 25355), 'torch.save', 'torch.save', (['net', 'f"""models/{args.save}.pkl"""'], {}), "(net, f'models/{args.save}.pkl')\n", (25323, 25355), False, 'import torch\n'), ((25604, 25672), 'torch.normal', 'torch.normal', (['(0)', '(1)'], {'size': '(args.batch_size, n_dim - 6)', 'device': 'device'}), '(0, 1, size=(args.batch_size, n_dim - 6), device=device)\n', (25616, 25672), False, 'import torch\n'), ((26125, 26160), 'numpy.random.shuffle', 'np.random.shuffle', (['transformed_data'], {}), '(transformed_data)\n', (26142, 26160), True, 'import numpy as np\n'), ((27253, 27289), 'numpy.random.shuffle', 'np.random.shuffle', (['training_data_npy'], {}), '(training_data_npy)\n', (27270, 27289), True, 'import numpy as np\n'), ((29207, 29249), 'torch.save', 'torch.save', (['net', 'f"""models/{args.save}.pkl"""'], {}), "(net, f'models/{args.save}.pkl')\n", (29217, 29249), False, 'import torch\n'), ((33127, 33153), 'os.path.exists', 'os.path.exists', (['model_path'], {}), '(model_path)\n', (33141, 33153), False, 'import os\n'), ((9862, 9893), 'os.remove', 'os.remove', (['f"""models/{name}.pkl"""'], {}), "(f'models/{name}.pkl')\n", (9871, 9893), False, 'import os\n'), ((9952, 9988), 'os.remove', 'os.remove', (['f"""gen_samples/{name}.pdb"""'], {}), "(f'gen_samples/{name}.pdb')\n", (9961, 9988), False, 'import os\n'), ((10045, 10079), 'os.remove', 'os.remove', (['f"""ensembles/{name}.dcd"""'], {}), "(f'ensembles/{name}.dcd')\n", (10054, 10079), False, 'import os\n'), ((10127, 10156), 'shutil.rmtree', 'shutil.rmtree', (['f"""runs/{name}"""'], {}), "(f'runs/{name}')\n", (10140, 10156), False, 'import shutil\n'), ((10898, 10936), 'boltzmann.generative.transforms.RandomPermutation', 'transforms.RandomPermutation', (['n_dim', '(1)'], {}), '(n_dim, 1)\n', (10926, 10936), False, 'from boltzmann.generative import transforms\n'), ((10957, 11020), 'boltzmann.utils.create_alternating_binary_mask', 'utils.create_alternating_binary_mask', ([], {'features': 'n_dim', 'even': '(True)'}), '(features=n_dim, even=True)\n', (10993, 11020), False, 'from boltzmann import utils\n'), ((11040, 11104), 'boltzmann.utils.create_alternating_binary_mask', 'utils.create_alternating_binary_mask', ([], {'features': 'n_dim', 'even': '(False)'}), '(features=n_dim, even=False)\n', (11076, 11104), False, 'from boltzmann import utils\n'), ((12868, 12906), 'boltzmann.generative.transforms.RandomPermutation', 'transforms.RandomPermutation', (['n_dim', '(1)'], {}), '(n_dim, 1)\n', (12896, 12906), False, 'from boltzmann.generative import transforms\n'), ((12927, 12990), 'boltzmann.utils.create_alternating_binary_mask', 'utils.create_alternating_binary_mask', ([], {'features': 'n_dim', 'even': '(True)'}), '(features=n_dim, even=True)\n', (12963, 12990), False, 'from boltzmann import utils\n'), ((13010, 13074), 'boltzmann.utils.create_alternating_binary_mask', 'utils.create_alternating_binary_mask', ([], {'features': 'n_dim', 'even': '(False)'}), '(features=n_dim, even=False)\n', (13046, 13074), False, 'from boltzmann import utils\n'), ((19770, 19790), 'torch.device', 'torch.device', (['"""cuda"""'], {}), "('cuda')\n", (19782, 19790), False, 'import torch\n'), ((19845, 19864), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (19857, 19864), False, 'import torch\n'), ((26188, 26230), 'numpy.linspace', 'np.linspace', (['min_noise', 'max_noise', 'n_noise'], {}), '(min_noise, max_noise, n_noise)\n', (26199, 26230), True, 'import numpy as np\n'), ((26265, 26323), 'sklearn.neighbors.kde.KernelDensity', 'KernelDensity', ([], {'kernel': '"""gaussian"""', 'atol': '(0.0001)', 'rtol': '(0.0001)'}), "(kernel='gaussian', atol=0.0001, rtol=0.0001)\n", (26278, 26323), False, 'from sklearn.neighbors.kde import KernelDensity\n'), ((29945, 29983), 'numpy.arange', 'np.arange', (['self.training_data.shape[0]'], {}), '(self.training_data.shape[0])\n', (29954, 29983), True, 'import numpy as np\n'), ((30018, 30058), 'numpy.arange', 'np.arange', (['self.validation_data.shape[0]'], {}), '(self.validation_data.shape[0])\n', (30027, 30058), True, 'import numpy as np\n'), ((30118, 30178), 'torch.zeros', 'torch.zeros', (['(self.training_data.shape[-1] - 6)'], {'device': 'device'}), '(self.training_data.shape[-1] - 6, device=device)\n', (30129, 30178), False, 'import torch\n'), ((30193, 30251), 'torch.eye', 'torch.eye', (['(self.training_data.shape[-1] - 6)'], {'device': 'device'}), '(self.training_data.shape[-1] - 6, device=device)\n', (30202, 30251), False, 'import torch\n'), ((32144, 32163), 'torch.min', 'torch.min', (['energies'], {}), '(energies)\n', (32153, 32163), False, 'import torch\n'), ((32193, 32215), 'torch.median', 'torch.median', (['energies'], {}), '(energies)\n', (32205, 32215), False, 'import torch\n'), ((32243, 32263), 'torch.mean', 'torch.mean', (['energies'], {}), '(energies)\n', (32253, 32263), False, 'import torch\n'), ((32290, 32310), 'torch.mean', 'torch.mean', (['energies'], {}), '(energies)\n', (32300, 32310), False, 'import torch\n'), ((10615, 10631), 'torch.load', 'torch.load', (['path'], {}), '(path)\n', (10625, 10631), False, 'import torch\n'), ((17317, 17361), 'boltzmann.generative.transforms.CompositeTransform', 'transforms.CompositeTransform', (['stage2_layers'], {}), '(stage2_layers)\n', (17346, 17361), False, 'from boltzmann.generative import transforms\n'), ((18650, 18703), 'boltzmann.protein.openmm_energy', 'protein.openmm_energy', (['x', 'openmm_context', 'temperature'], {}), '(x, openmm_context, temperature)\n', (18671, 18703), False, 'from boltzmann import protein\n'), ((19506, 19523), 'torch.mean', 'torch.mean', (['z_jac'], {}), '(z_jac)\n', (19516, 19523), False, 'import torch\n'), ((20126, 20185), 'torch.distributions.MultivariateNormal', 'distributions.MultivariateNormal', (['mu'], {'covariance_matrix': 'cov'}), '(mu, covariance_matrix=cov)\n', (20158, 20185), False, 'from torch import distributions\n'), ((20441, 20506), 'numpy.random.choice', 'np.random.choice', (['indices', 'args.pretrans_batch_size'], {'replace': '(True)'}), '(indices, args.pretrans_batch_size, replace=True)\n', (20457, 20506), True, 'import numpy as np\n'), ((26776, 26800), 'numpy.arange', 'np.arange', (['data.shape[0]'], {}), '(data.shape[0])\n', (26785, 26800), True, 'import numpy as np\n'), ((30938, 30953), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (30951, 30953), False, 'import torch\n'), ((31018, 31093), 'numpy.random.choice', 'np.random.choice', (['self.training_indices'], {'size': 'self.batch_size', 'replace': '(True)'}), '(self.training_indices, size=self.batch_size, replace=True)\n', (31034, 31093), True, 'import numpy as np\n'), ((31811, 31828), 'torch.mean', 'torch.mean', (['z_jac'], {}), '(z_jac)\n', (31821, 31828), False, 'import torch\n'), ((32339, 32362), 'torch.mean', 'torch.mean', (['x_jac_prime'], {}), '(x_jac_prime)\n', (32349, 32362), False, 'import torch\n'), ((32481, 32496), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (32494, 32496), False, 'import torch\n'), ((32522, 32599), 'numpy.random.choice', 'np.random.choice', (['self.validation_indices'], {'size': 'self.batch_size', 'replace': '(True)'}), '(self.validation_indices, size=self.batch_size, replace=True)\n', (32538, 32599), True, 'import numpy as np\n'), ((15705, 15749), 'boltzmann.generative.transforms.CompositeTransform', 'transforms.CompositeTransform', (['stage1_layers'], {}), '(stage1_layers)\n', (15734, 15749), False, 'from boltzmann.generative import transforms\n'), ((16322, 16364), 'boltzmann.generative.transforms.CompositeTransform', 'transforms.CompositeTransform', (['head_layers'], {}), '(head_layers)\n', (16351, 16364), False, 'from boltzmann.generative import transforms\n'), ((30287, 30346), 'torch.distributions.MultivariateNormal', 'distributions.MultivariateNormal', (['mu'], {'covariance_matrix': 'cov'}), '(mu, covariance_matrix=cov)\n', (30319, 30346), False, 'from torch import distributions\n'), ((31347, 31440), 'torch.normal', 'torch.normal', (['(0)', 'self.net.example_noise'], {'size': 'z_pretrans.shape', 'device': 'z_pretrans.device'}), '(0, self.net.example_noise, size=z_pretrans.shape, device=\n z_pretrans.device)\n', (31359, 31440), False, 'import torch\n'), ((32920, 32943), 'torch.mean', 'torch.mean', (['z_jac_valid'], {}), '(z_jac_valid)\n', (32930, 32943), False, 'import torch\n'), ((11252, 11445), 'boltzmann.nn.ResidualNet', 'nn.ResidualNet', ([], {'in_features': 'in_features', 'out_features': 'out_features', 'hidden_features': 'hidden_features', 'num_blocks': 'hidden_layers', 'dropout_probability': 'dropout_fraction', 'use_batch_norm': '(False)'}), '(in_features=in_features, out_features=out_features,\n hidden_features=hidden_features, num_blocks=hidden_layers,\n dropout_probability=dropout_fraction, use_batch_norm=False)\n', (11266, 11445), False, 'from boltzmann import nn\n'), ((11706, 11899), 'boltzmann.nn.ResidualNet', 'nn.ResidualNet', ([], {'in_features': 'in_features', 'out_features': 'out_features', 'hidden_features': 'hidden_features', 'num_blocks': 'hidden_layers', 'dropout_probability': 'dropout_fraction', 'use_batch_norm': '(False)'}), '(in_features=in_features, out_features=out_features,\n hidden_features=hidden_features, num_blocks=hidden_layers,\n dropout_probability=dropout_fraction, use_batch_norm=False)\n', (11720, 11899), False, 'from boltzmann import nn\n'), ((13242, 13435), 'boltzmann.nn.ResidualNet', 'nn.ResidualNet', ([], {'in_features': 'in_features', 'out_features': 'out_features', 'hidden_features': 'hidden_features', 'num_blocks': 'hidden_layers', 'dropout_probability': 'dropout_fraction', 'use_batch_norm': '(False)'}), '(in_features=in_features, out_features=out_features,\n hidden_features=hidden_features, num_blocks=hidden_layers,\n dropout_probability=dropout_fraction, use_batch_norm=False)\n', (13256, 13435), False, 'from boltzmann import nn\n'), ((13856, 14049), 'boltzmann.nn.ResidualNet', 'nn.ResidualNet', ([], {'in_features': 'in_features', 'out_features': 'out_features', 'hidden_features': 'hidden_features', 'num_blocks': 'hidden_layers', 'dropout_probability': 'dropout_fraction', 'use_batch_norm': '(False)'}), '(in_features=in_features, out_features=out_features,\n hidden_features=hidden_features, num_blocks=hidden_layers,\n dropout_probability=dropout_fraction, use_batch_norm=False)\n', (13870, 14049), False, 'from boltzmann import nn\n')]
import os, argparse, traceback, glob, librosa, random, itertools, time, torch import numpy as np import soundfile as sf import torch.optim as optim import torch.nn.functional as F from torch.utils.data import Dataset, DataLoader from gan import Generator, MultiScale from hparams import * class MelDataset(Dataset): def __init__(self, mel_list, audio_list): self.mel_list = mel_list self.audio_list = audio_list def __len__(self): return len(self.mel_list) def __getitem__(self, idx): mel = np.load(self.mel_list[idx]) mel = torch.from_numpy(mel).float() start = random.randint(0, mel.size(1) - seq_len - 1) mel = mel[:, start : start + seq_len] wav = np.load(self.audio_list[idx]) wav = torch.from_numpy(wav).float() start *= hop_length wav = wav[start : start + seq_len * hop_length] return mel, wav.unsqueeze(0) def train(args): base_dir = 'data' mel_list = sorted(glob.glob(os.path.join(base_dir + '/mel', '*.npy'))) audio_list = sorted(glob.glob(os.path.join(base_dir + '/audio', '*.npy'))) trainset = MelDataset(mel_list, audio_list) train_loader = DataLoader(trainset, batch_size=batch_size, num_workers=0, shuffle=True, drop_last=True) test_mel = sorted(glob.glob(os.path.join(valid_dir + '/mel', '*.npy'))) testset = [] for d in test_mel: mel = np.load(d) mel = torch.from_numpy(mel).float() mel = mel.unsqueeze(0) testset.append(mel) G = Generator().cuda() D = MultiScale().cuda() g_optimizer = optim.Adam(G.parameters(), lr=1e-4, betas=(0.5, 0.9)) d_optimizer = optim.Adam(D.parameters(), lr=1e-4, betas=(0.5, 0.9)) step, epochs = 0, 0 if args.checkpoint is not None: ckpt = torch.load(args.checkpoint) G.load_state_dict(ckpt['G']) g_optimizer.load_state_dict(ckpt['g_optimizer']) D.load_state_dict(ckpt['D']) d_optimizer.load_state_dict(ckpt['d_optimizer']) step = ckpt['step'], epochs = ckpt['epoch'] print('Load Status: Epochs %d, Step %d' % (epochs, step)) torch.backends.cudnn.benchmark = True start = time.time() try: for epoch in itertools.count(epochs): for (mel, audio) in train_loader: mel = mel.cuda() audio = audio.cuda() # Discriminator d_real = D(audio) d_loss_real = 0 for scale in d_real: d_loss_real += F.relu(1 - scale[-1]).mean() fake_audio = G(mel) d_fake = D(fake_audio.cuda().detach()) d_loss_fake = 0 for scale in d_fake: d_loss_fake += F.relu(1 + scale[-1]).mean() d_loss = d_loss_real + d_loss_fake D.zero_grad() d_loss.backward() d_optimizer.step() # Generator d_fake = D(fake_audio.cuda()) g_loss = 0 for scale in d_fake: g_loss += -scale[-1].mean() # Feature Matching feature_loss = 0 for i in range(3): for j in range(len(d_fake[i]) - 1): feature_loss += F.l1_loss(d_fake[i][j], d_real[i][j].detach()) g_loss += lambda_feat * feature_loss G.zero_grad() g_loss.backward() g_optimizer.step() step += 1 if step % log_step == 0: print('step: {}, D_loss: {:.3f}, G_loss: {:.3f}, {:.3f} sec/step'.format( step, d_loss, g_loss, (time.time() - start) / log_step)) start = time.time() if step % checkpoint_step == 0: save_dir = './ckpt/' + args.name with torch.no_grad(): for i, mel_test in enumerate(testset): g_audio = G(mel_test.cuda()) g_audio = g_audio.squeeze().cpu() audio = (g_audio.numpy() * 32768) sf.write(os.path.join(save_dir, 'generated-{}-{}.wav'.format(step, i)), audio.astype('int16'), sample_rate) print("Saving checkpoint") torch.save({ 'G': G.state_dict(), 'g_optimizer': g_optimizer.state_dict(), 'D': D.state_dict(), 'd_optimizer': d_optimizer.state_dict(), 'step': step, 'epoch': epoch }, os.path.join(save_dir, 'ckpt-{}.pt'.format(step))) except Exception as e: traceback.print_exc() if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('--checkpoint', '-p', default=None) parser.add_argument('--name', '-n', required=True) args = parser.parse_args() save_dir = os.path.join('./ckpt', args.name) os.makedirs(save_dir, exist_ok=True) train(args)
[ "gan.MultiScale", "os.makedirs", "argparse.ArgumentParser", "gan.Generator", "torch.load", "os.path.join", "torch.from_numpy", "traceback.print_exc", "itertools.count", "torch.nn.functional.relu", "torch.utils.data.DataLoader", "torch.no_grad", "numpy.load", "time.time" ]
[((1191, 1283), 'torch.utils.data.DataLoader', 'DataLoader', (['trainset'], {'batch_size': 'batch_size', 'num_workers': '(0)', 'shuffle': '(True)', 'drop_last': '(True)'}), '(trainset, batch_size=batch_size, num_workers=0, shuffle=True,\n drop_last=True)\n', (1201, 1283), False, 'from torch.utils.data import Dataset, DataLoader\n'), ((2200, 2211), 'time.time', 'time.time', ([], {}), '()\n', (2209, 2211), False, 'import os, argparse, traceback, glob, librosa, random, itertools, time, torch\n'), ((4981, 5006), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (5004, 5006), False, 'import os, argparse, traceback, glob, librosa, random, itertools, time, torch\n'), ((5168, 5201), 'os.path.join', 'os.path.join', (['"""./ckpt"""', 'args.name'], {}), "('./ckpt', args.name)\n", (5180, 5201), False, 'import os, argparse, traceback, glob, librosa, random, itertools, time, torch\n'), ((5206, 5242), 'os.makedirs', 'os.makedirs', (['save_dir'], {'exist_ok': '(True)'}), '(save_dir, exist_ok=True)\n', (5217, 5242), False, 'import os, argparse, traceback, glob, librosa, random, itertools, time, torch\n'), ((539, 566), 'numpy.load', 'np.load', (['self.mel_list[idx]'], {}), '(self.mel_list[idx])\n', (546, 566), True, 'import numpy as np\n'), ((733, 762), 'numpy.load', 'np.load', (['self.audio_list[idx]'], {}), '(self.audio_list[idx])\n', (740, 762), True, 'import numpy as np\n'), ((1411, 1421), 'numpy.load', 'np.load', (['d'], {}), '(d)\n', (1418, 1421), True, 'import numpy as np\n'), ((1802, 1829), 'torch.load', 'torch.load', (['args.checkpoint'], {}), '(args.checkpoint)\n', (1812, 1829), False, 'import os, argparse, traceback, glob, librosa, random, itertools, time, torch\n'), ((2242, 2265), 'itertools.count', 'itertools.count', (['epochs'], {}), '(epochs)\n', (2257, 2265), False, 'import os, argparse, traceback, glob, librosa, random, itertools, time, torch\n'), ((1002, 1042), 'os.path.join', 'os.path.join', (["(base_dir + '/mel')", '"""*.npy"""'], {}), "(base_dir + '/mel', '*.npy')\n", (1014, 1042), False, 'import os, argparse, traceback, glob, librosa, random, itertools, time, torch\n'), ((1079, 1121), 'os.path.join', 'os.path.join', (["(base_dir + '/audio')", '"""*.npy"""'], {}), "(base_dir + '/audio', '*.npy')\n", (1091, 1121), False, 'import os, argparse, traceback, glob, librosa, random, itertools, time, torch\n'), ((1313, 1354), 'os.path.join', 'os.path.join', (["(valid_dir + '/mel')", '"""*.npy"""'], {}), "(valid_dir + '/mel', '*.npy')\n", (1325, 1354), False, 'import os, argparse, traceback, glob, librosa, random, itertools, time, torch\n'), ((1534, 1545), 'gan.Generator', 'Generator', ([], {}), '()\n', (1543, 1545), False, 'from gan import Generator, MultiScale\n'), ((1561, 1573), 'gan.MultiScale', 'MultiScale', ([], {}), '()\n', (1571, 1573), False, 'from gan import Generator, MultiScale\n'), ((4917, 4938), 'traceback.print_exc', 'traceback.print_exc', ([], {}), '()\n', (4936, 4938), False, 'import os, argparse, traceback, glob, librosa, random, itertools, time, torch\n'), ((581, 602), 'torch.from_numpy', 'torch.from_numpy', (['mel'], {}), '(mel)\n', (597, 602), False, 'import os, argparse, traceback, glob, librosa, random, itertools, time, torch\n'), ((777, 798), 'torch.from_numpy', 'torch.from_numpy', (['wav'], {}), '(wav)\n', (793, 798), False, 'import os, argparse, traceback, glob, librosa, random, itertools, time, torch\n'), ((1436, 1457), 'torch.from_numpy', 'torch.from_numpy', (['mel'], {}), '(mel)\n', (1452, 1457), False, 'import os, argparse, traceback, glob, librosa, random, itertools, time, torch\n'), ((3819, 3830), 'time.time', 'time.time', ([], {}), '()\n', (3828, 3830), False, 'import os, argparse, traceback, glob, librosa, random, itertools, time, torch\n'), ((3958, 3973), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (3971, 3973), False, 'import os, argparse, traceback, glob, librosa, random, itertools, time, torch\n'), ((2554, 2575), 'torch.nn.functional.relu', 'F.relu', (['(1 - scale[-1])'], {}), '(1 - scale[-1])\n', (2560, 2575), True, 'import torch.nn.functional as F\n'), ((2779, 2800), 'torch.nn.functional.relu', 'F.relu', (['(1 + scale[-1])'], {}), '(1 + scale[-1])\n', (2785, 2800), True, 'import torch.nn.functional as F\n'), ((3757, 3768), 'time.time', 'time.time', ([], {}), '()\n', (3766, 3768), False, 'import os, argparse, traceback, glob, librosa, random, itertools, time, torch\n')]
from orbit.models.ktrlite import KTRLite import pandas as pd import numpy as np import math from scipy.stats import nct from enum import Enum import torch import matplotlib.pyplot as plt from copy import deepcopy from ..constants.constants import ( KTRTimePointPriorKeys, PredictMethod, TrainingMetaKeys, PredictionMetaKeys ) from ..exceptions import IllegalArgument, ModelException, PredictionException from ..utils.general import is_ordered_datetime from ..utils.kernels import gauss_kernel, sandwich_kernel from ..utils.features import make_seasonal_regressors from .model_template import ModelTemplate from ..estimators.pyro_estimator import PyroEstimatorSVI from ..models import KTRLite from orbit.constants.palette import OrbitPalette from ..utils.knots import get_knot_idx, get_knot_dates from ..utils.plot import orbit_style_decorator class DataInputMapper(Enum): """ mapping from object input to pyro input """ # All of the following have default defined in DEFAULT_SLGT_FIT_ATTRIBUTES # ---------- Data Input ---------- # # observation related NUM_OF_VALID_RESPONSE = 'N_VALID_RES' WHICH_VALID_RESPONSE = 'WHICH_VALID_RES' RESPONSE_OFFSET = 'MEAN_Y' DEGREE_OF_FREEDOM = 'DOF' _RESIDUALS_SCALE_UPPER = 'RESID_SCALE_UB' # ---------- Level ---------- # _NUM_KNOTS_LEVEL = 'N_KNOTS_LEV' LEVEL_KNOT_SCALE = 'LEV_KNOT_SCALE' _KERNEL_LEVEL = 'K_LEV' # ---------- Regression ---------- # _NUM_KNOTS_COEFFICIENTS = 'N_KNOTS_COEF' _KERNEL_COEFFICIENTS = 'K_COEF' _NUM_OF_REGULAR_REGRESSORS = 'N_RR' _NUM_OF_POSITIVE_REGRESSORS = 'N_PR' _NUM_OF_NEGATIVE_REGRESSORS = 'N_NR' _REGULAR_REGRESSOR_MATRIX = 'RR' _POSITIVE_REGRESSOR_MATRIX = 'PR' _NEGATIVE_REGRESSOR_MATRIX = 'NR' _REGULAR_REGRESSOR_INIT_KNOT_LOC = 'RR_INIT_KNOT_LOC' _REGULAR_REGRESSOR_INIT_KNOT_SCALE = 'RR_INIT_KNOT_SCALE' _REGULAR_REGRESSOR_KNOT_SCALE = 'RR_KNOT_SCALE' _POSITIVE_REGRESSOR_INIT_KNOT_LOC = 'PR_INIT_KNOT_LOC' _POSITIVE_REGRESSOR_INIT_KNOT_SCALE = 'PR_INIT_KNOT_SCALE' _POSITIVE_REGRESSOR_KNOT_SCALE = 'PR_KNOT_SCALE' _NEGATIVE_REGRESSOR_INIT_KNOT_LOC = 'NR_INIT_KNOT_LOC' _NEGATIVE_REGRESSOR_INIT_KNOT_SCALE = 'NR_INIT_KNOT_SCALE' _NEGATIVE_REGRESSOR_KNOT_SCALE = 'NR_KNOT_SCALE' # ---------- Prior Specification ---------- # _COEF_PRIOR_LIST = 'COEF_PRIOR_LIST' _LEVEL_KNOTS = 'LEV_KNOT_LOC' _SEAS_TERM = 'SEAS_TERM' class BaseSamplingParameters(Enum): """ The output sampling parameters related with the base model """ LEVEL_KNOT = 'lev_knot' LEVEL = 'lev' YHAT = 'yhat' OBS_SCALE = 'obs_scale' class RegressionSamplingParameters(Enum): """ The output sampling parameters related with regression component. """ COEFFICIENTS_KNOT = 'coef_knot' COEFFICIENTS_INIT_KNOT = 'coef_init_knot' COEFFICIENTS = 'coef' # Defaults Values DEFAULT_REGRESSOR_SIGN = '=' DEFAULT_COEFFICIENTS_INIT_KNOT_SCALE = 1.0 DEFAULT_COEFFICIENTS_INIT_KNOT_LOC = 0 DEFAULT_COEFFICIENTS_KNOT_SCALE = 0.1 DEFAULT_LOWER_BOUND_SCALE_MULTIPLIER = 0.01 DEFAULT_UPPER_BOUND_SCALE_MULTIPLIER = 1.0 class KTRModel(ModelTemplate): """Base KTR model object with shared functionality for PyroVI method Parameters ---------- level_knot_scale : float sigma for level; default to be .1 level_segments : int the number of segments partitioned by the knots of level (trend) level_knot_distance : int the distance between every two knots of level (trend) level_knot_dates : array like list of pre-specified dates for the level knots seasonality : int, or list of int multiple seasonality seasonality_fs_order : int, or list of int fourier series order for seasonality seasonality_segments : int the number of segments partitioned by the knots of seasonality seasonal_initial_knot_scale : float scale parameter for seasonal regressors initial coefficient knots; default to be 1 seasonal_knot_scale : float scale parameter for seasonal regressors drift of coefficient knots; default to be 0.1. regressor_col : array-like strings regressor columns regressor_sign : list list of signs with '=' for regular regressor, '+' for positive regressor, and '-' for negative regressor. regressor_init_knot_loc : list list of regressor knot pooling mean priors, default to be 0's regressor_init_knot_scale : list list of regressor knot pooling sigma's to control the pooling strength towards the grand mean of regressors; default to be 1. regressor_knot_scale : list list of regressor knot sigma priors; default to be 0.1. regression_segments : int the number of segments partitioned by the knots of regression regression_knot_distance : int the distance between every two knots of regression regression_knot_dates : array-like list of pre-specified dates for regression knots regression_rho : float sigma in the Gaussian kernel for the regression term degree of freedom : int degree of freedom for error t-distribution date_freq : str date frequency; if not supplied, the minimum timestamp difference in the date would be used. coef_prior_list : list of dicts each dict in the list should have keys as 'name', prior_start_tp_idx' (inclusive), KTRTimePointPriorKeys.PRIOR_END_TP_IDX.value (not inclusive), KTRTimePointPriorKeys.PRIOR_MEAN.value, KTRTimePointPriorKeys.PRIOR_SD.value, and KTRTimePointPriorKeys.PRIOR_REGRESSOR_COL.value residuals_scale_upper : float flat_multiplier : bool Default set as True. If False, we will adjust knot scale with a multiplier based on regressor volume around each knot; When True, set all multiplier as 1 ktrlite_optim_args : dict the optimizing config for the ktrlite model (to fit level/seasonality). Default to be dict(). """ _data_input_mapper = DataInputMapper # stan or pyro model name (e.g. name of `*.stan` file in package) _model_name = 'ktr' _supported_estimator_types = [PyroEstimatorSVI] def __init__(self, # level level_knot_scale=0.1, level_segments=10, level_knot_distance=None, level_knot_dates=None, # seasonality seasonality=None, seasonality_fs_order=None, seasonality_segments=2, seasonal_initial_knot_scale=1.0, seasonal_knot_scale=0.1, # regression regressor_col=None, regressor_sign=None, regressor_init_knot_loc=None, regressor_init_knot_scale=None, regressor_knot_scale=None, regression_segments=5, regression_knot_distance=None, regression_knot_dates=None, regression_rho=0.15, # shared degree_of_freedom=30, date_freq=None, # time-based coefficient priors coef_prior_list=None, flat_multiplier=True, residuals_scale_upper=None, ktrlite_optim_args=dict(), **kwargs): super().__init__(**kwargs) # create estimator in base class # level configurations self.level_knot_scale = level_knot_scale self.level_segments = level_segments self.level_knot_distance = level_knot_distance self.level_knot_dates = level_knot_dates self._level_knot_dates = self.level_knot_dates self.level_knots = None self._level_knots = None self._kernel_level = None self._num_knots_level = None self.knots_tp_level = None # seasonality configurations self.seasonality = seasonality self.seasonality_fs_order = seasonality_fs_order self._seasonality = self.seasonality # used to name different seasonal components in prediction self._seasonality_labels = list() self._seasonality_fs_order = self.seasonality_fs_order self.seasonal_initial_knot_scale = seasonal_initial_knot_scale self.seasonal_knot_scale = seasonal_knot_scale self.seasonality_segments = seasonality_segments self._seas_term = 0 self._seasonality_coef_knot_dates = None self._seasonality_coef_knots = None # regression configurations self.regressor_col = regressor_col self.regressor_sign = regressor_sign self.regressor_init_knot_loc = regressor_init_knot_loc self.regressor_init_knot_scale = regressor_init_knot_scale self.regressor_knot_scale = regressor_knot_scale self.regression_knot_distance = regression_knot_distance self.regression_segments = regression_segments self._regression_knot_dates = regression_knot_dates self.regression_rho = regression_rho self.flat_multiplier = flat_multiplier # set private var to arg value # if None set default in _set_default_args() self._regressor_sign = self.regressor_sign self._regressor_init_knot_loc = self.regressor_init_knot_loc self._regressor_init_knot_scale = self.regressor_init_knot_scale self._regressor_knot_scale = self.regressor_knot_scale self.coef_prior_list = coef_prior_list self._coef_prior_list = [] self._regression_knots_idx = None self._num_of_regressors = 0 # positive regressors self._num_of_positive_regressors = 0 self._positive_regressor_col = list() self._positive_regressor_init_knot_loc = list() self._positive_regressor_init_knot_scale = list() self._positive_regressor_knot_scale_1d = list() self._positive_regressor_knot_scale = list() # negative regressors self._num_of_negative_regressors = 0 self._negative_regressor_col = list() self._negative_regressor_init_knot_loc = list() self._negative_regressor_init_knot_scale = list() self._negative_regressor_knot_scale_1d = list() self._negative_regressor_knot_scale = list() # regular regressors self._num_of_regular_regressors = 0 self._regular_regressor_col = list() self._regular_regressor_init_knot_loc = list() self._regular_regressor_init_knot_scale = list() self._regular_regressor_knot_scale_1d = list() self._regular_regressor_knot_scale = list() self._regressor_col = list() # init dynamic data attributes # the following are set by `_set_dynamic_attributes()` and generally set during fit() # from input df # response data self._is_valid_response = None self._which_valid_response = None self._num_of_valid_response = 0 # regression data self._knots_tp_coefficients = None self._positive_regressor_matrix = None self._negative_regressor_matrix = None self._regular_regressor_matrix = None # other configurations self.date_freq = date_freq self.degree_of_freedom = degree_of_freedom self.residuals_scale_upper = residuals_scale_upper self._residuals_scale_upper = residuals_scale_upper self.ktrlite_optim_args = ktrlite_optim_args self._set_static_attributes() self._set_model_param_names() def _set_model_param_names(self): """Overriding base template functions. Model parameters to extract""" self._model_param_names += [param.value for param in BaseSamplingParameters] if self._num_of_regressors > 0: self._model_param_names += [param.value for param in RegressionSamplingParameters] def _set_default_args(self): """Set default attributes for None""" # default checks for seasonality and seasonality_fs_order will be conducted # in ktrlite model and we will extract them from ktrlite model directly later if self.coef_prior_list is not None: self._coef_prior_list = deepcopy(self.coef_prior_list) # if no regressors, end here # if self.regressor_col is None: # regardless of what args are set for these, if regressor_col is None # these should all be empty lists self._regressor_sign = list() self._regressor_init_knot_loc = list() self._regressor_init_knot_scale = list() self._regressor_knot_scale = list() return def _validate_params_len(params, valid_length): for p in params: if p is not None and len(p) != valid_length: raise IllegalArgument('Wrong dimension length in Regression Param Input') # regressor defaults num_of_regressors = len(self.regressor_col) _validate_params_len([ self.regressor_sign, self.regressor_init_knot_loc, self.regressor_init_knot_scale, self.regressor_knot_scale], num_of_regressors ) if self.regressor_sign is None: self._regressor_sign = [DEFAULT_REGRESSOR_SIGN] * num_of_regressors if self.regressor_init_knot_loc is None: self._regressor_init_knot_loc = [DEFAULT_COEFFICIENTS_INIT_KNOT_LOC] * num_of_regressors if self.regressor_init_knot_scale is None: self._regressor_init_knot_scale = [DEFAULT_COEFFICIENTS_INIT_KNOT_SCALE] * num_of_regressors if self.regressor_knot_scale is None: self._regressor_knot_scale = [DEFAULT_COEFFICIENTS_KNOT_SCALE] * num_of_regressors self._num_of_regressors = num_of_regressors def _set_static_regression_attributes(self): # if no regressors, end here if self._num_of_regressors == 0: return for index, reg_sign in enumerate(self._regressor_sign): if reg_sign == '+': self._num_of_positive_regressors += 1 self._positive_regressor_col.append(self.regressor_col[index]) # used for 'pr_knot_loc' sampling in pyro self._positive_regressor_init_knot_loc.append(self._regressor_init_knot_loc[index]) self._positive_regressor_init_knot_scale.append(self._regressor_init_knot_scale[index]) # used for 'pr_knot' sampling in pyro self._positive_regressor_knot_scale_1d.append(self._regressor_knot_scale[index]) elif reg_sign == '-': self._num_of_negative_regressors += 1 self._negative_regressor_col.append(self.regressor_col[index]) # used for 'nr_knot_loc' sampling in pyro self._negative_regressor_init_knot_loc.append(self._regressor_init_knot_loc[index]) self._negative_regressor_init_knot_scale.append(self._regressor_init_knot_scale[index]) # used for 'nr_knot' sampling in pyro self._negative_regressor_knot_scale_1d.append(self._regressor_knot_scale[index]) else: self._num_of_regular_regressors += 1 self._regular_regressor_col.append(self.regressor_col[index]) # used for 'rr_knot_loc' sampling in pyro self._regular_regressor_init_knot_loc.append(self._regressor_init_knot_loc[index]) self._regular_regressor_init_knot_scale.append(self._regressor_init_knot_scale[index]) # used for 'rr_knot' sampling in pyro self._regular_regressor_knot_scale_1d.append(self._regressor_knot_scale[index]) # regular first, then positive, then negative self._regressor_col = self._regular_regressor_col + self._positive_regressor_col + self._negative_regressor_col # numpy conversion self._positive_regressor_init_knot_loc = np.array(self._positive_regressor_init_knot_loc) self._positive_regressor_init_knot_scale = np.array(self._positive_regressor_init_knot_scale) self._positive_regressor_knot_scale_1d = np.array(self._positive_regressor_knot_scale_1d) self._negative_regressor_init_knot_loc = np.array(self._negative_regressor_init_knot_loc) self._negative_regressor_init_knot_scale = np.array(self._negative_regressor_init_knot_scale) self._negative_regressor_knot_scale_1d = np.array(self._negative_regressor_knot_scale_1d) self._regular_regressor_init_knot_loc = np.array(self._regular_regressor_init_knot_loc) self._regular_regressor_init_knot_scale = np.array(self._regular_regressor_init_knot_scale) self._regular_regressor_knot_scale_1d = np.array(self._regular_regressor_knot_scale_1d) @staticmethod def _validate_coef_prior(coef_prior_list): for test_dict in coef_prior_list: if set(test_dict.keys()) != set([ KTRTimePointPriorKeys.NAME.value, KTRTimePointPriorKeys.PRIOR_START_TP_IDX.value, KTRTimePointPriorKeys.PRIOR_END_TP_IDX.value, KTRTimePointPriorKeys.PRIOR_MEAN.value, KTRTimePointPriorKeys.PRIOR_SD.value, KTRTimePointPriorKeys.PRIOR_REGRESSOR_COL.value ]): raise IllegalArgument('wrong key name in inserted prior dict') len_insert_prior = list() for key, val in test_dict.items(): if key in [ KTRTimePointPriorKeys.PRIOR_MEAN.value, KTRTimePointPriorKeys.PRIOR_SD.value, KTRTimePointPriorKeys.PRIOR_REGRESSOR_COL.value, ]: len_insert_prior.append(len(val)) if not all(len_insert == len_insert_prior[0] for len_insert in len_insert_prior): raise IllegalArgument('wrong dimension length in inserted prior dict') # @staticmethod # def _validate_level_knot_inputs(level_knot_dates, level_knots): # if len(level_knots) != len(level_knot_dates): # raise IllegalArgument('level_knots and level_knot_dates should have the same length') def _set_coef_prior_idx(self): if self._coef_prior_list and len(self._regressor_col) > 0: for x in self._coef_prior_list: prior_regressor_col_idx = [ np.where(np.array(self._regressor_col) == col)[0][0] for col in x[KTRTimePointPriorKeys.PRIOR_REGRESSOR_COL.value] ] x.update({'prior_regressor_col_idx': prior_regressor_col_idx}) def _set_static_attributes(self): """model data input based on args at instantiation or computed from args at instantiation""" self._set_default_args() self._set_static_regression_attributes() # self._validate_level_knot_inputs(self.level_knot_dates, self.level_knots) if self._coef_prior_list: self._validate_coef_prior(self._coef_prior_list) self._set_coef_prior_idx() def _set_valid_response_attributes(self, training_meta): num_of_observations = training_meta[TrainingMetaKeys.NUM_OF_OBS.value] response = training_meta[TrainingMetaKeys.RESPONSE.value] if self._seasonality: max_seasonality = np.round(np.max(self._seasonality)).astype(int) if num_of_observations < max_seasonality: raise ModelException( "Number of observations {} is less than max seasonality {}".format( num_of_observations, max_seasonality)) # get some reasonable offset to regularize response to make default priors scale-insensitive if self._seasonality: max_seasonality = np.round(np.max(self._seasonality)).astype(int) self.response_offset = np.nanmean(response[:max_seasonality]) else: self.response_offset = np.nanmean(response) self.is_valid_response = ~np.isnan(response) # [0] to convert tuple back to array self.which_valid_response = np.where(self.is_valid_response)[0] self.num_of_valid_response = len(self.which_valid_response) def _set_regressor_matrix(self, df, training_meta): num_of_observations = training_meta[TrainingMetaKeys.NUM_OF_OBS.value] # validate regression columns if self.regressor_col is not None and \ not set(self.regressor_col).issubset(df.columns): raise ModelException( "DataFrame does not contain specified regressor column(s)." ) # init of regression matrix depends on length of response vector self._positive_regressor_matrix = np.zeros((num_of_observations, 0), dtype=np.double) self._negative_regressor_matrix = np.zeros((num_of_observations, 0), dtype=np.double) self._regular_regressor_matrix = np.zeros((num_of_observations, 0), dtype=np.double) # update regression matrices if self._num_of_positive_regressors > 0: self._positive_regressor_matrix = df.filter( items=self._positive_regressor_col, ).values if self._num_of_negative_regressors > 0: self._negative_regressor_matrix = df.filter( items=self._negative_regressor_col, ).values if self._num_of_regular_regressors > 0: self._regular_regressor_matrix = df.filter( items=self._regular_regressor_col, ).values def _set_coefficients_kernel_matrix(self, df, training_meta): """Derive knots position and kernel matrix and other related meta data""" num_of_observations = training_meta[TrainingMetaKeys.NUM_OF_OBS.value] date_array = training_meta[TrainingMetaKeys.DATE_ARRAY.value] # date_col = training_meta[TrainingMetaKeys.DATE_COL.value] # placeholder self._kernel_coefficients = np.zeros((num_of_observations, 0), dtype=np.double) self._num_knots_coefficients = 0 if self._num_of_regressors > 0: self._regression_knots_idx = get_knot_idx( date_array=date_array, num_of_obs=num_of_observations, knot_dates=self._regression_knot_dates, knot_distance=self.regression_knot_distance, num_of_segments=self.regression_segments, date_freq=self.date_freq, ) tp = np.arange(1, num_of_observations + 1) / num_of_observations self._knots_tp_coefficients = (1 + self._regression_knots_idx) / num_of_observations self._kernel_coefficients = gauss_kernel(tp, self._knots_tp_coefficients, rho=self.regression_rho) self._num_knots_coefficients = len(self._knots_tp_coefficients) if self.date_freq is None: self.date_freq = date_array.diff().min() self._regression_knot_dates = get_knot_dates(date_array[0], self._regression_knots_idx, self.date_freq) def _set_knots_scale_matrix(self, df, training_meta): num_of_observations = training_meta[TrainingMetaKeys.NUM_OF_OBS.value] if self._num_of_positive_regressors > 0: # calculate average local absolute volume for each segment local_val = np.ones((self._num_of_positive_regressors, self._num_knots_coefficients)) if self.flat_multiplier: multiplier = np.ones(local_val.shape) else: multiplier = np.ones(local_val.shape) # store local value for the range on the left side since last knot for idx in range(len(self._regression_knots_idx)): if idx < len(self._regression_knots_idx) - 1: str_idx = self._regression_knots_idx[idx] end_idx = self._regression_knots_idx[idx + 1] else: str_idx = self._regression_knots_idx[idx] end_idx = num_of_observations local_val[:, idx] = np.mean(np.fabs(self._positive_regressor_matrix[str_idx:end_idx]), axis=0) global_mean = np.expand_dims(np.mean(np.fabs(self._positive_regressor_matrix), axis=0), -1) test_flag = local_val < 0.01 * global_mean # adjust knot scale with the multiplier derive by the average value and shift by 0.001 to avoid zeros in # scale parameters multiplier[test_flag] = DEFAULT_LOWER_BOUND_SCALE_MULTIPLIER # replace entire row of nan (when 0.1 * global_mean is equal to global_min) with upper bound multiplier[np.isnan(multiplier).all(axis=-1)] = 1.0 # geometric drift i.e. 0.1 = 10% up-down in 1 s.d. prob. # self._positive_regressor_knot_scale has shape num_of_pr x num_of_knot self._positive_regressor_knot_scale = ( multiplier * np.expand_dims(self._positive_regressor_knot_scale_1d, -1) ) # keep a lower bound of scale parameters self._positive_regressor_knot_scale[self._positive_regressor_knot_scale < 1e-4] = 1e-4 # TODO: we change the type here, maybe we should change it earlier? self._positive_regressor_init_knot_scale = np.array(self._positive_regressor_init_knot_scale) self._positive_regressor_init_knot_scale[self._positive_regressor_init_knot_scale < 1e-4] = 1e-4 if self._num_of_negative_regressors > 0: # calculate average local absolute volume for each segment local_val = np.ones((self._num_of_negative_regressors, self._num_knots_coefficients)) if self.flat_multiplier: multiplier = np.ones(local_val.shape) else: multiplier = np.ones(local_val.shape) # store local value for the range on the left side since last knot for idx in range(len(self._regression_knots_idx)): if idx < len(self._regression_knots_idx) - 1: str_idx = self._regression_knots_idx[idx] end_idx = self._regression_knots_idx[idx + 1] else: str_idx = self._regression_knots_idx[idx] end_idx = num_of_observations local_val[:, idx] = np.mean(np.fabs(self._negative_regressor_matrix[str_idx:end_idx]), axis=0) global_mean = np.expand_dims(np.mean(np.fabs(self._negative_regressor_matrix), axis=0), -1) test_flag = local_val < 0.01 * global_mean # adjust knot scale with the multiplier derive by the average value and shift by 0.001 to avoid zeros in # scale parameters multiplier[test_flag] = DEFAULT_LOWER_BOUND_SCALE_MULTIPLIER # replace entire row of nan (when 0.1 * global_mean is equal to global_min) with upper bound multiplier[np.isnan(multiplier).all(axis=-1)] = 1.0 # geometric drift i.e. 0.1 = 10% up-down in 1 s.d. prob. self._negative_regressor_knot_scale = ( multiplier * np.expand_dims(self._negative_regressor_knot_scale_1d, -1) ) # keep a lower bound of scale parameters self._negative_regressor_knot_scale[self._negative_regressor_knot_scale < 1e-4] = 1e-4 # TODO: we change the type here, maybe we should change it earlier? self._negative_regressor_init_knot_scale = np.array(self._negative_regressor_init_knot_scale) self._negative_regressor_init_knot_scale[self._negative_regressor_init_knot_scale < 1e-4] = 1e-4 if self._num_of_regular_regressors > 0: # do the same for regular regressor # calculate average local absolute volume for each segment local_val = np.ones((self._num_of_regular_regressors, self._num_knots_coefficients)) if self.flat_multiplier: multiplier = np.ones(local_val.shape) else: multiplier = np.ones(local_val.shape) # store local value for the range on the left side since last knot for idx in range(len(self._regression_knots_idx)): if idx < len(self._regression_knots_idx) - 1: str_idx = self._regression_knots_idx[idx] end_idx = self._regression_knots_idx[idx + 1] else: str_idx = self._regression_knots_idx[idx] end_idx = num_of_observations local_val[:, idx] = np.mean(np.fabs(self._regular_regressor_matrix[str_idx:end_idx]), axis=0) # adjust knot scale with the multiplier derive by the average value and shift by 0.001 to avoid zeros in # scale parameters global_mean = np.expand_dims(np.mean(np.fabs(self._regular_regressor_matrix), axis=0), -1) test_flag = local_val < 0.01 * global_mean multiplier[test_flag] = DEFAULT_LOWER_BOUND_SCALE_MULTIPLIER # replace entire row of nan (when 0.1 * global_mean is equal to global_min) with upper bound multiplier[np.isnan(multiplier).all(axis=-1)] = 1.0 # geometric drift i.e. 0.1 = 10% up-down in 1 s.d. prob. # self._regular_regressor_knot_scale has shape num_of_pr x num_of_knot self._regular_regressor_knot_scale = ( multiplier * np.expand_dims(self._regular_regressor_knot_scale_1d, -1) ) # keep a lower bound of scale parameters self._regular_regressor_knot_scale[self._regular_regressor_knot_scale < 1e-4] = 1e-4 # TODO: we change the type here, maybe we should change it earlier? self._regular_regressor_init_knot_scale = np.array(self._regular_regressor_init_knot_scale) self._regular_regressor_init_knot_scale[self._regular_regressor_init_knot_scale < 1e-4] = 1e-4 def _generate_tp(self, training_meta, prediction_date_array): """Used in _generate_seas""" training_end = training_meta[TrainingMetaKeys.END.value] num_of_observations = training_meta[TrainingMetaKeys.NUM_OF_OBS.value] date_array = training_meta[TrainingMetaKeys.DATE_ARRAY.value] prediction_start = prediction_date_array[0] output_len = len(prediction_date_array) if prediction_start > training_end: start = num_of_observations else: start = pd.Index(date_array).get_loc(prediction_start) new_tp = np.arange(start + 1, start + output_len + 1) / num_of_observations return new_tp def _generate_insample_tp(self, training_meta, date_array): """Used in _generate_seas""" train_date_array = training_meta[TrainingMetaKeys.DATE_ARRAY.value] num_of_observations = training_meta[TrainingMetaKeys.NUM_OF_OBS.value] idx = np.nonzero(np.in1d(train_date_array, date_array))[0] tp = (idx + 1) / num_of_observations return tp # def _generate_coefs(self, training_meta, prediction_date_array, coef_knot_dates, coef_knot): # """Used in _generate_seas""" # new_tp = self._generate_tp(training_meta, prediction_date_array) # knots_tp_coef = self._generate_insample_tp(training_meta, coef_knot_dates) # kernel_coef = sandwich_kernel(new_tp, knots_tp_coef) # coefs = np.squeeze(np.matmul(coef_knot, kernel_coef.transpose(1, 0)), axis=0).transpose(1, 0) # return coefs def _generate_seas(self, df, training_meta, coef_knot_dates, coef_knots, seasonality, seasonality_fs_order, seasonality_labels): """To calculate the seasonality term based on the _seasonal_knots_input. Parameters ---------- df : pd.DataFrame input df training_meta: dict meta dictionary for the training input coef_knot_dates : 1-D array like dates for seasonality coefficient knots coef_knots : dict dict of seasonal coefficient knots from each seasonality seasonality : list seasonality input; list of float seasonality_fs_order : list seasonality_fs_order input list of int Returns ----------- dict : a dictionary contains seasonal regression components mapped by each seasonality """ df = df.copy() # store each component as a dictionary seas_decomp = dict() if seasonality is not None and len(seasonality) > 0: date_col = training_meta[TrainingMetaKeys.DATE_COL.value] date_array = training_meta[TrainingMetaKeys.DATE_ARRAY.value] training_end = training_meta[TrainingMetaKeys.END.value] num_of_observations = training_meta[TrainingMetaKeys.NUM_OF_OBS.value] prediction_date_array = df[date_col].values prediction_start = prediction_date_array[0] if prediction_start > training_end: # time index for prediction start start = num_of_observations else: # time index for prediction start start = pd.Index(date_array).get_loc(prediction_start) # dictionary seas_regressors = make_seasonal_regressors( n=df.shape[0], periods=seasonality, orders=seasonality_fs_order, labels=seasonality_labels, shift=start, ) new_tp = self._generate_tp(training_meta, prediction_date_array) knots_tp_coef = self._generate_insample_tp(training_meta, coef_knot_dates) coef_kernel = sandwich_kernel(new_tp, knots_tp_coef) # init of regression matrix depends on length of response vector total_seas_regression = np.zeros((1, df.shape[0]), dtype=np.double) for k in seasonality_labels: seas_regresor_matrix = seas_regressors[k] coef_knot = coef_knots[k] # time-step x coefficients seas_coef = np.squeeze(np.matmul(coef_knot, coef_kernel.transpose(1, 0)), axis=0).transpose(1, 0) seas_regression = np.sum(seas_coef * seas_regresor_matrix, axis=-1) seas_decomp[k] = np.expand_dims(seas_regression, 0) total_seas_regression += seas_regression else: total_seas_regression = np.zeros((1, df.shape[0]), dtype=np.double) return total_seas_regression, seas_decomp def _set_levs_and_seas(self, df, training_meta): response_col = training_meta['response_col'] date_col = training_meta[TrainingMetaKeys.DATE_COL.value] num_of_observations = training_meta[TrainingMetaKeys.NUM_OF_OBS.value] date_array = training_meta[TrainingMetaKeys.DATE_ARRAY.value] # use ktrlite to derive levs and seas ktrlite = KTRLite( response_col=response_col, date_col=date_col, level_knot_scale=self.level_knot_scale, level_segments=self.level_segments, level_knot_dates=self.level_knot_dates, level_knot_distance=self.level_knot_distance, seasonality=self.seasonality, seasonality_fs_order=self.seasonality_fs_order, seasonal_initial_knot_scale=self.seasonal_initial_knot_scale, seasonal_knot_scale=self.seasonal_knot_scale, seasonality_segments=self.seasonality_segments, degree_of_freedom=self.degree_of_freedom, date_freq=self.date_freq, estimator='stan-map', **self.ktrlite_optim_args ) ktrlite.fit(df=df) # self._ktrlite_model = ktrlite ktrlite_pt_posteriors = ktrlite.get_point_posteriors() ktrlite_obs_scale = ktrlite_pt_posteriors['map']['obs_scale'] # load _seasonality and _seasonality_fs_order self._seasonality = ktrlite._model._seasonality self._seasonality_fs_order = ktrlite._model._seasonality_fs_order for seas in self._seasonality: self._seasonality_labels.append('seasonality_{}'.format(seas)) # if input None for upper bound of residuals scale, use data-driven input if self.residuals_scale_upper is None: # make it 5 times to have some buffer in case we over-fit in KTRLite self._residuals_scale_upper = min(ktrlite_obs_scale * 5, training_meta['response_sd']) # this part is to extract level and seasonality result from KTRLite self._level_knots = np.squeeze(ktrlite_pt_posteriors['map']['lev_knot']) self._level_knot_dates = ktrlite._model._level_knot_dates tp = np.arange(1, num_of_observations + 1) / num_of_observations # # trim level knots dates when they are beyond training dates # lev_knot_dates = list() # lev_knots = list() # for i, x in enumerate(self.level_knot_dates): # if (x <= df[date_col].max()) and (x >= df[date_col].min()): # lev_knot_dates.append(x) # lev_knots.append(self._level_knots[i]) # self._level_knot_dates = pd.to_datetime(lev_knot_dates) # self._level_knots = np.array(lev_knots) self._level_knots_idx = get_knot_idx( date_array=date_array, num_of_obs=None, knot_dates=self._level_knot_dates, knot_distance=None, num_of_segments=None, date_freq=self.date_freq, ) self.knots_tp_level = (1 + self._level_knots_idx) / num_of_observations self._kernel_level = sandwich_kernel(tp, self.knots_tp_level) self._num_knots_level = len(self._level_knot_dates) if self._seasonality: self._seasonality_coef_knot_dates = ktrlite._model._coef_knot_dates coef_knots_flatten = ktrlite_pt_posteriors['map']['coef_knot'] coef_knots = dict() pos = 0 for idx, label in enumerate(self._seasonality_labels): order = self._seasonality_fs_order[idx] coef_knots[label] = coef_knots_flatten[..., pos:(pos + 2 * order), :] pos += 2 * order self._seasonality_coef_knots = coef_knots # we just need total here and because of self._seas_term, _ = self._generate_seas( df, training_meta, self._seasonality_coef_knot_dates, self._seasonality_coef_knots, self._seasonality, self._seasonality_fs_order, self._seasonality_labels) # remove batch size as an input for models self._seas_term = np.squeeze(self._seas_term, 0) def _filter_coef_prior(self, df): if self._coef_prior_list and len(self._regressor_col) > 0: # iterate over a copy due to the removal operation for test_dict in self._coef_prior_list[:]: prior_regressor_col = test_dict[KTRTimePointPriorKeys.PRIOR_REGRESSOR_COL.value] m = test_dict[KTRTimePointPriorKeys.PRIOR_MEAN.value] sd = test_dict[KTRTimePointPriorKeys.PRIOR_SD.value] end_tp_idx = min(test_dict[KTRTimePointPriorKeys.PRIOR_END_TP_IDX.value], df.shape[0]) start_tp_idx = min(test_dict[KTRTimePointPriorKeys.PRIOR_START_TP_IDX.value], df.shape[0]) if start_tp_idx < end_tp_idx: expected_shape = (end_tp_idx - start_tp_idx, len(prior_regressor_col)) test_dict.update({KTRTimePointPriorKeys.PRIOR_END_TP_IDX.value: end_tp_idx}) test_dict.update({KTRTimePointPriorKeys.PRIOR_START_TP_IDX.value: start_tp_idx}) # mean/sd expanding test_dict.update({KTRTimePointPriorKeys.PRIOR_MEAN.value: np.full(expected_shape, m)}) test_dict.update({KTRTimePointPriorKeys.PRIOR_SD.value: np.full(expected_shape, sd)}) else: # removing invalid prior self._coef_prior_list.remove(test_dict) def set_dynamic_attributes(self, df, training_meta): """Overriding: func: `~orbit.models.BaseETS._set_dynamic_attributes""" self._set_regressor_matrix(df, training_meta) self._set_coefficients_kernel_matrix(df, training_meta) self._set_knots_scale_matrix(df, training_meta) self._set_levs_and_seas(df, training_meta) self._filter_coef_prior(df) self._set_valid_response_attributes(training_meta) @staticmethod def _concat_regression_coefs(pr_beta=None, rr_beta=None): """Concatenates regression posterior matrix In the case that `pr_beta` or `rr_beta` is a 1d tensor, transform to 2d tensor and concatenate. Args ---- pr_beta : array like postive-value constrainted regression betas rr_beta : array like regular regression betas Returns ------- array like concatenated 2d array of shape (1, len(rr_beta) + len(pr_beta)) """ regressor_beta = None if pr_beta is not None and rr_beta is not None: pr_beta = pr_beta if len(pr_beta.shape) == 2 else pr_beta.reshape(1, -1) rr_beta = rr_beta if len(rr_beta.shape) == 2 else rr_beta.reshape(1, -1) regressor_beta = torch.cat((rr_beta, pr_beta), dim=1) elif pr_beta is not None: regressor_beta = pr_beta elif rr_beta is not None: regressor_beta = rr_beta return regressor_beta def predict(self, posterior_estimates, df, training_meta, prediction_meta, coefficient_method="smooth", include_error=False, store_prediction_array=False, **kwargs): """Vectorized version of prediction math Parameters ---- coefficient_method : str either "smooth" or "empirical". when "empirical" is used, curves are sampled/aggregated directly from beta posteriors; when "smooth" is used, first extract sampled/aggregated posteriors of knots then beta. this mainly impacts the aggregated estimation method; full bayesian should not be impacted include_error : bool if generating the noise samples store_prediction_array : bool if storing the prediction array """ ################################################################ # Model Attributes ################################################################ # FIXME: do we still need this? model = deepcopy(posterior_estimates) arbitrary_posterior_value = list(model.values())[0] num_sample = arbitrary_posterior_value.shape[0] ################################################################ # Prediction Attributes ################################################################ output_len = prediction_meta[PredictionMetaKeys.PREDICTION_DF_LEN.value] prediction_start = prediction_meta[PredictionMetaKeys.START.value] date_array = training_meta[TrainingMetaKeys.DATE_ARRAY.value] num_of_observations = training_meta[TrainingMetaKeys.NUM_OF_OBS.value] training_end = training_meta[TrainingMetaKeys.END.value] # Here assume dates are ordered and consecutive # if prediction_meta[PredictionMetaKeys.START.value] > self.training_end, # assume prediction starts right after train end if prediction_start > training_end: # time index for prediction start start = num_of_observations else: start = pd.Index(date_array).get_loc(prediction_start) new_tp = np.arange(start + 1, start + output_len + 1) / num_of_observations if include_error: # in-sample knots lev_knot_in = model.get(BaseSamplingParameters.LEVEL_KNOT.value) # TODO: hacky way; let's just assume last two knot distance is knots distance for all knots lev_knot_width = self.knots_tp_level[-1] - self.knots_tp_level[-2] # check whether we need to put new knots for simulation if new_tp[-1] >= self.knots_tp_level[-1] + lev_knot_width: # derive knots tp knots_tp_level_out = np.arange(self.knots_tp_level[-1] + lev_knot_width, new_tp[-1], lev_knot_width) new_knots_tp_level = np.concatenate([self.knots_tp_level, knots_tp_level_out]) lev_knot_out = np.random.laplace(0, self.level_knot_scale, size=(lev_knot_in.shape[0], len(knots_tp_level_out))) lev_knot_out = np.cumsum(np.concatenate([lev_knot_in[:, -1].reshape(-1, 1), lev_knot_out], axis=1), axis=1)[:, 1:] lev_knot = np.concatenate([lev_knot_in, lev_knot_out], axis=1) else: new_knots_tp_level = self.knots_tp_level lev_knot = lev_knot_in kernel_level = sandwich_kernel(new_tp, new_knots_tp_level) else: lev_knot = model.get(BaseSamplingParameters.LEVEL_KNOT.value) kernel_level = sandwich_kernel(new_tp, self.knots_tp_level) obs_scale = model.get(BaseSamplingParameters.OBS_SCALE.value) obs_scale = obs_scale.reshape(-1, 1) # if self._seasonality is not None: # condition of seasonality is checked inside total_seas, seas_decomp = self._generate_seas(df, training_meta, self._seasonality_coef_knot_dates, self._seasonality_coef_knots, self._seasonality, self._seasonality_fs_order, self._seasonality_labels) # # seas is 1-d array, add the batch size back # seas = np.expand_dims(seas, 0) # else: # # follow component shapes # seas = np.zeros((1, output_len)) trend = np.matmul(lev_knot, kernel_level.transpose((1, 0))) regression = np.zeros(trend.shape) if self._num_of_regressors > 0: regressor_matrix = df.filter(items=self._regressor_col, ).values regressor_betas = self._get_regression_coefs_matrix( training_meta, posterior_estimates, coefficient_method, date_array=prediction_meta[TrainingMetaKeys.DATE_ARRAY.value] ) regression = np.sum(regressor_betas * regressor_matrix, axis=-1) if include_error: epsilon = nct.rvs(self.degree_of_freedom, nc=0, loc=0, scale=obs_scale, size=(num_sample, len(new_tp))) trend += epsilon pred_array = trend + total_seas + regression # if decompose output dictionary of components decomp_dict = { 'prediction': pred_array, 'trend': trend, 'regression': regression } # this is an input from ktrlite decomp_dict.update(seas_decomp) if store_prediction_array: self.pred_array = pred_array else: self.pred_array = None return decomp_dict def _get_regression_coefs_matrix(self, training_meta, posteriors, coefficient_method='smooth', date_array=None): """internal function to provide coefficient matrix given a date array Args ---- posteriors : dict posterior samples date_array : array like array of date stamp coefficient_method : str either "smooth" or "empirical". when "empirical" is used, curves are sampled/aggregated directly from beta posteriors; when "smooth" is used, first extract sampled/aggregated posteriors of knots then beta. this mainly impacts the aggregated estimation method; full bayesian should not be impacted. """ num_of_observations = training_meta[TrainingMetaKeys.NUM_OF_OBS.value] training_start = training_meta[TrainingMetaKeys.START.value] training_end = training_meta[TrainingMetaKeys.END.value] train_date_array = training_meta[TrainingMetaKeys.DATE_ARRAY.value] if self._num_of_regular_regressors + self._num_of_positive_regressors + self._num_of_negative_regressors == 0: return None # if date_array not specified, coefficients in the training period will be retrieved if date_array is None: if coefficient_method == 'smooth': coef_knots = posteriors.get(RegressionSamplingParameters.COEFFICIENTS_KNOT.value) # only 1 knot for 0 segments if self.regression_segments == 0: coef_knots = np.expand_dims(coef_knots, -1) if len(self._regressor_col) == 1: coef_knots = np.expand_dims(coef_knots, 1) # result in batch x time step x regressor size shape regressor_betas = np.matmul(coef_knots, self._kernel_coefficients.transpose((1, 0))) # if len(self._regressor_col) == 1: # regressor_betas = np.expand_dims(regressor_betas, 0) regressor_betas = regressor_betas.transpose((0, 2, 1)) elif coefficient_method == 'empirical': regressor_betas = posteriors.get(RegressionSamplingParameters.COEFFICIENTS.value) else: raise IllegalArgument('Wrong coefficient_method:{}'.format(coefficient_method)) else: date_array = pd.to_datetime(date_array).values output_len = len(date_array) train_len = num_of_observations # some validation of date array if not is_ordered_datetime(date_array): raise IllegalArgument('Datetime index must be ordered and not repeat') prediction_start = date_array[0] if prediction_start < training_start: raise PredictionException('Prediction start must be after training start.') # If we cannot find a match of prediction range, assume prediction starts right after train end if prediction_start > training_end: # time index for prediction start start = train_len coef_repeats = [0] * (start - 1) + [output_len] else: # time index for prediction start start = pd.Index(train_date_array).get_loc(prediction_start) if output_len <= train_len - start: coef_repeats = [0] * start + [1] * output_len + [0] * (train_len - start - output_len) else: coef_repeats = [0] * start + [1] * (train_len - start - 1) + [output_len - train_len + start + 1] new_tp = np.arange(start + 1, start + output_len + 1) / num_of_observations if coefficient_method == 'smooth': kernel_coefficients = gauss_kernel(new_tp, self._knots_tp_coefficients, rho=self.regression_rho) coef_knots = posteriors.get(RegressionSamplingParameters.COEFFICIENTS_KNOT.value) if len(self._regressor_col) == 1: coef_knots = np.expand_dims(coef_knots, -1) # only 1 knot for 0 segments if self.regression_segments == 0: coef_knots = np.expand_dims(coef_knots, -1) regressor_betas = np.matmul(coef_knots, kernel_coefficients.transpose((1, 0))) if len(regressor_betas.shape) == 2: regressor_betas = np.expand_dims(regressor_betas, 0) regressor_betas = regressor_betas.transpose((0, 2, 1)) elif coefficient_method == 'empirical': regressor_betas = posteriors.get(RegressionSamplingParameters.COEFFICIENTS.value) regressor_betas = np.repeat(regressor_betas, repeats=coef_repeats, axis=1) else: raise IllegalArgument('Wrong coefficient_method:{}'.format(coefficient_method)) return regressor_betas def get_regression_coefs(self, training_meta, point_method, point_posteriors, posterior_samples, coefficient_method='smooth', date_array=None, include_ci=False, lower=0.05, upper=0.95 ): """Return DataFrame regression coefficients. Parameters ---------- coefficient_method : str either "smooth" or "empirical". when "empirical" is used, curves are sampled/aggregated directly from beta posteriors; when "smooth" is used, first extract sampled/aggregated posteriors of knots then beta. date_array : array-like the list of dates for which the regressio coefficients will be reported. Default to be None. When it's None, all the dates in the training data will be used. include_ci : bool if including the confidence intervals for the regression coefficients lower : float between (0, 1). default to be 0.05 lower bound for the CI upper : float between (0, 1). default to be 0.95. upper bound for the CI Returns ------- Pandas data frame holding the dynamic regression coefficients """ date_col = training_meta[TrainingMetaKeys.DATE_COL.value] reg_df = pd.DataFrame() if self._num_of_regressors == 0: return reg_df _point_method = point_method if point_method is None: _point_method = PredictMethod.MEDIAN.value posteriors = point_posteriors.get(_point_method) coefs = np.squeeze(self._get_regression_coefs_matrix(training_meta, posteriors, coefficient_method=coefficient_method, date_array=date_array)) if len(coefs.shape) == 1: coefs = np.expand_dims(coefs, -1) reg_df = pd.DataFrame(data=coefs, columns=self._regressor_col) if date_array is not None: reg_df[date_col] = date_array else: reg_df[date_col] = training_meta[TrainingMetaKeys.DATE_ARRAY.value] # re-arrange columns reg_df = reg_df[[date_col] + self._regressor_col] if include_ci: posteriors = posterior_samples coefs = self._get_regression_coefs_matrix(training_meta, posteriors, coefficient_method=coefficient_method, date_array=date_array) coefficients_lower = np.quantile(coefs, lower, axis=0) coefficients_upper = np.quantile(coefs, upper, axis=0) reg_df_lower = reg_df.copy() reg_df_upper = reg_df.copy() for idx, col in enumerate(self._regressor_col): reg_df_lower[col] = coefficients_lower[:, idx] reg_df_upper[col] = coefficients_upper[:, idx] return reg_df, reg_df_lower, reg_df_upper return reg_df def get_regression_coef_knots(self, training_meta, point_method, point_posteriors, posterior_samples): """Return DataFrame regression coefficient knots """ date_col = training_meta[TrainingMetaKeys.DATE_COL.value] _point_method = point_method if point_method is None: _point_method = PredictMethod.MEDIAN.value # init dataframe knots_df = pd.DataFrame() # end if no regressors if self._num_of_regular_regressors + self._num_of_positive_regressors + self._num_of_negative_regressors == 0: return knots_df knots_df[date_col] = self._regression_knot_dates # TODO: make the label as a constant knots_df['step'] = self._regression_knots_idx # batch size x regressor size x knot size coef_knots = point_posteriors \ .get(_point_method) \ .get(RegressionSamplingParameters.COEFFICIENTS_KNOT.value) # only 1 knot for 0 segments if self.regression_segments == 0: coef_knots = np.expand_dims(coef_knots, -1) if len(self._regressor_col) == 1: coef_knots = np.expand_dims(coef_knots, 1) for idx, col in enumerate(self._regressor_col): knots_df[col] = np.transpose(coef_knots[:, idx]) return knots_df @orbit_style_decorator def plot_regression_coefs(self, training_meta, point_method, point_posteriors, posterior_samples, coefficient_method='smooth', date_array=None, include_ci=False, lower=0.05, upper=0.95, with_knot=False, is_visible=True, ncol=2, ylim=None, markersize=200, figsize=(16, 8)): """Plot regression coefficients. Parameters ---------- coefficient_method : str either "smooth" or "empirical". when "empirical" is used, curves are sampled/aggregated directly from beta posteriors; when "smooth" is used, first extract sampled/aggregated posteriors of knots then beta. date_array : array-like the list of dates for which the regressio coefficients will be reported. Default to be None. When it's None, all the dates in the training data will be used. include_ci : bool if including the confidence intervals for the regression coefficients lower : float between (0, 1). default to be 0.05 lower bound for the CI upper : float between (0, 1). default to be 0.95. upper bound for the CI with_knot : bool if plotting the regression knots in the graph ncol : int number of columns of the panel grid is_visible : boolean whether we want to show the plot. If called from unittest, is_visible might = False. is_visible : bool whether we want to show the plot. If called from unittest, is_visible might = False. markersize : int; optional knot marker size figsize : tuple; optional figsize passed to `matplotlib.pyplot.figure()` """ # assume your first column is the date; this way can use a static method if include_ci: coef_df, coef_df_lower, coef_df_upper = self.get_regression_coefs( training_meta, point_method, point_posteriors, posterior_samples, coefficient_method=coefficient_method, date_array=date_array, include_ci=include_ci, lower=lower, upper=upper ) else: coef_df = self.get_regression_coefs( training_meta, point_method, point_posteriors, posterior_samples, coefficient_method=coefficient_method, date_array=date_array, include_ci=include_ci, lower=lower, upper=upper ) coef_df_lower, coef_df_upper = None, None if with_knot: knot_df = self.get_regression_coef_knots(training_meta, point_method, point_posteriors, posterior_samples) else: knot_df = None regressor_col = coef_df.columns.tolist()[1:] nrow = math.ceil(len(regressor_col) / ncol) fig, axes = plt.subplots(nrow, ncol, figsize=figsize, squeeze=False) for idx, col in enumerate(regressor_col): row_idx = idx // ncol col_idx = idx % ncol coef = coef_df[col] axes[row_idx, col_idx].plot(coef, alpha=.8, label='coefficients', color=OrbitPalette.BLUE.value) if coef_df_lower is not None and coef_df_upper is not None: coef_lower = coef_df_lower[col] coef_upper = coef_df_upper[col] axes[row_idx, col_idx].fill_between(np.arange(0, coef_df.shape[0]), coef_lower, coef_upper, alpha=.3, color=OrbitPalette.BLUE.value) if knot_df is not None: step = knot_df['step'] knots = knot_df[col].values axes[row_idx, col_idx].scatter(x=step, y=knots, marker='^', s=markersize, color=OrbitPalette.GREEN.value, alpha=0.5) if ylim is not None: axes[row_idx, col_idx].set_ylim(ylim) axes[row_idx, col_idx].set_title('{}'.format(col)) axes[row_idx, col_idx].ticklabel_format(useOffset=False) plt.tight_layout() if is_visible: plt.show() else: plt.close() return axes # TODO: need a unit test of this function def get_level_knots(self, training_meta, point_method, point_posteriors, posterior_samples): """Given posteriors, return knots and correspondent date""" date_col = training_meta[TrainingMetaKeys.DATE_COL.value] _point_method = point_method if point_method is None: _point_method = PredictMethod.MEDIAN.value lev_knots = point_posteriors \ .get(_point_method) \ .get(BaseSamplingParameters.LEVEL_KNOT.value) lev_knots = np.squeeze(lev_knots, 0) out = { date_col: self._level_knot_dates, BaseSamplingParameters.LEVEL_KNOT.value: lev_knots, } return pd.DataFrame(out) def get_levels(self, training_meta, point_method, point_posteriors, posterior_samples): date_col = training_meta[TrainingMetaKeys.DATE_COL.value] date_array = training_meta[TrainingMetaKeys.DATE_ARRAY.value] _point_method = point_method if point_method is None: _point_method = PredictMethod.MEDIAN.value levs = point_posteriors \ .get(_point_method) \ .get(BaseSamplingParameters.LEVEL.value) levs = np.squeeze(levs, 0) out = { date_col: date_array, BaseSamplingParameters.LEVEL.value: levs, } return pd.DataFrame(out) @orbit_style_decorator def plot_lev_knots(self, training_meta, point_method, point_posteriors, posterior_samples, path=None, is_visible=True, title="", fontsize=16, markersize=250, figsize=(16, 8)): """ Plot the fitted level knots along with the actual time series. Parameters ---------- path : str; optional path to save the figure is_visible : boolean whether we want to show the plot. If called from unittest, is_visible might = False. title : str; optional title of the plot fontsize : int; optional fontsize of the title markersize : int; optional knot marker size figsize : tuple; optional figsize passed to `matplotlib.pyplot.figure()` Returns ------- matplotlib axes object """ date_col = training_meta[TrainingMetaKeys.DATE_COL.value] date_array = training_meta[TrainingMetaKeys.DATE_ARRAY.value] response = training_meta[TrainingMetaKeys.RESPONSE.value] levels_df = self.get_levels(training_meta, point_method, point_posteriors, posterior_samples) knots_df = self.get_level_knots(training_meta, point_method, point_posteriors, posterior_samples) fig, ax = plt.subplots(1, 1, figsize=figsize) ax.plot(date_array, response, color=OrbitPalette.BLUE.value, lw=1, alpha=0.7, label='actual') ax.plot(levels_df[date_col], levels_df[BaseSamplingParameters.LEVEL.value], color=OrbitPalette.BLACK.value, lw=1, alpha=0.8, label=BaseSamplingParameters.LEVEL.value) ax.scatter(knots_df[date_col], knots_df[BaseSamplingParameters.LEVEL_KNOT.value], color=OrbitPalette.GREEN.value, lw=1, s=markersize, marker='^', alpha=0.8, label=BaseSamplingParameters.LEVEL_KNOT.value) ax.legend() ax.grid(True, which='major', c='grey', ls='-', lw=1, alpha=0.5) ax.set_title(title, fontsize=fontsize) if path: fig.savefig(path) if is_visible: plt.show() else: plt.close() return ax
[ "pandas.Index", "numpy.array", "numpy.nanmean", "copy.deepcopy", "numpy.arange", "pandas.to_datetime", "numpy.repeat", "numpy.where", "numpy.max", "matplotlib.pyplot.close", "numpy.concatenate", "pandas.DataFrame", "orbit.models.ktrlite.KTRLite", "numpy.ones", "numpy.in1d", "numpy.sque...
[((16118, 16166), 'numpy.array', 'np.array', (['self._positive_regressor_init_knot_loc'], {}), '(self._positive_regressor_init_knot_loc)\n', (16126, 16166), True, 'import numpy as np\n'), ((16218, 16268), 'numpy.array', 'np.array', (['self._positive_regressor_init_knot_scale'], {}), '(self._positive_regressor_init_knot_scale)\n', (16226, 16268), True, 'import numpy as np\n'), ((16318, 16366), 'numpy.array', 'np.array', (['self._positive_regressor_knot_scale_1d'], {}), '(self._positive_regressor_knot_scale_1d)\n', (16326, 16366), True, 'import numpy as np\n'), ((16416, 16464), 'numpy.array', 'np.array', (['self._negative_regressor_init_knot_loc'], {}), '(self._negative_regressor_init_knot_loc)\n', (16424, 16464), True, 'import numpy as np\n'), ((16516, 16566), 'numpy.array', 'np.array', (['self._negative_regressor_init_knot_scale'], {}), '(self._negative_regressor_init_knot_scale)\n', (16524, 16566), True, 'import numpy as np\n'), ((16616, 16664), 'numpy.array', 'np.array', (['self._negative_regressor_knot_scale_1d'], {}), '(self._negative_regressor_knot_scale_1d)\n', (16624, 16664), True, 'import numpy as np\n'), ((16713, 16760), 'numpy.array', 'np.array', (['self._regular_regressor_init_knot_loc'], {}), '(self._regular_regressor_init_knot_loc)\n', (16721, 16760), True, 'import numpy as np\n'), ((16811, 16860), 'numpy.array', 'np.array', (['self._regular_regressor_init_knot_scale'], {}), '(self._regular_regressor_init_knot_scale)\n', (16819, 16860), True, 'import numpy as np\n'), ((16909, 16956), 'numpy.array', 'np.array', (['self._regular_regressor_knot_scale_1d'], {}), '(self._regular_regressor_knot_scale_1d)\n', (16917, 16956), True, 'import numpy as np\n'), ((20921, 20972), 'numpy.zeros', 'np.zeros', (['(num_of_observations, 0)'], {'dtype': 'np.double'}), '((num_of_observations, 0), dtype=np.double)\n', (20929, 20972), True, 'import numpy as np\n'), ((21015, 21066), 'numpy.zeros', 'np.zeros', (['(num_of_observations, 0)'], {'dtype': 'np.double'}), '((num_of_observations, 0), dtype=np.double)\n', (21023, 21066), True, 'import numpy as np\n'), ((21108, 21159), 'numpy.zeros', 'np.zeros', (['(num_of_observations, 0)'], {'dtype': 'np.double'}), '((num_of_observations, 0), dtype=np.double)\n', (21116, 21159), True, 'import numpy as np\n'), ((22123, 22174), 'numpy.zeros', 'np.zeros', (['(num_of_observations, 0)'], {'dtype': 'np.double'}), '((num_of_observations, 0), dtype=np.double)\n', (22131, 22174), True, 'import numpy as np\n'), ((35299, 35902), 'orbit.models.ktrlite.KTRLite', 'KTRLite', ([], {'response_col': 'response_col', 'date_col': 'date_col', 'level_knot_scale': 'self.level_knot_scale', 'level_segments': 'self.level_segments', 'level_knot_dates': 'self.level_knot_dates', 'level_knot_distance': 'self.level_knot_distance', 'seasonality': 'self.seasonality', 'seasonality_fs_order': 'self.seasonality_fs_order', 'seasonal_initial_knot_scale': 'self.seasonal_initial_knot_scale', 'seasonal_knot_scale': 'self.seasonal_knot_scale', 'seasonality_segments': 'self.seasonality_segments', 'degree_of_freedom': 'self.degree_of_freedom', 'date_freq': 'self.date_freq', 'estimator': '"""stan-map"""'}), "(response_col=response_col, date_col=date_col, level_knot_scale=self\n .level_knot_scale, level_segments=self.level_segments, level_knot_dates\n =self.level_knot_dates, level_knot_distance=self.level_knot_distance,\n seasonality=self.seasonality, seasonality_fs_order=self.\n seasonality_fs_order, seasonal_initial_knot_scale=self.\n seasonal_initial_knot_scale, seasonal_knot_scale=self.\n seasonal_knot_scale, seasonality_segments=self.seasonality_segments,\n degree_of_freedom=self.degree_of_freedom, date_freq=self.date_freq,\n estimator='stan-map', **self.ktrlite_optim_args)\n", (35306, 35902), False, 'from orbit.models.ktrlite import KTRLite\n'), ((36970, 37022), 'numpy.squeeze', 'np.squeeze', (["ktrlite_pt_posteriors['map']['lev_knot']"], {}), "(ktrlite_pt_posteriors['map']['lev_knot'])\n", (36980, 37022), True, 'import numpy as np\n'), ((43107, 43136), 'copy.deepcopy', 'deepcopy', (['posterior_estimates'], {}), '(posterior_estimates)\n', (43115, 43136), False, 'from copy import deepcopy\n'), ((46776, 46797), 'numpy.zeros', 'np.zeros', (['trend.shape'], {}), '(trend.shape)\n', (46784, 46797), True, 'import numpy as np\n'), ((54209, 54223), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (54221, 54223), True, 'import pandas as pd\n'), ((54908, 54961), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': 'coefs', 'columns': 'self._regressor_col'}), '(data=coefs, columns=self._regressor_col)\n', (54920, 54961), True, 'import pandas as pd\n'), ((56484, 56498), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (56496, 56498), True, 'import pandas as pd\n'), ((60353, 60409), 'matplotlib.pyplot.subplots', 'plt.subplots', (['nrow', 'ncol'], {'figsize': 'figsize', 'squeeze': '(False)'}), '(nrow, ncol, figsize=figsize, squeeze=False)\n', (60365, 60409), True, 'import matplotlib.pyplot as plt\n'), ((61565, 61583), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (61581, 61583), True, 'import matplotlib.pyplot as plt\n'), ((62244, 62268), 'numpy.squeeze', 'np.squeeze', (['lev_knots', '(0)'], {}), '(lev_knots, 0)\n', (62254, 62268), True, 'import numpy as np\n'), ((62421, 62438), 'pandas.DataFrame', 'pd.DataFrame', (['out'], {}), '(out)\n', (62433, 62438), True, 'import pandas as pd\n'), ((62929, 62948), 'numpy.squeeze', 'np.squeeze', (['levs', '(0)'], {}), '(levs, 0)\n', (62939, 62948), True, 'import numpy as np\n'), ((63079, 63096), 'pandas.DataFrame', 'pd.DataFrame', (['out'], {}), '(out)\n', (63091, 63096), True, 'import pandas as pd\n'), ((64447, 64482), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': 'figsize'}), '(1, 1, figsize=figsize)\n', (64459, 64482), True, 'import matplotlib.pyplot as plt\n'), ((12333, 12363), 'copy.deepcopy', 'deepcopy', (['self.coef_prior_list'], {}), '(self.coef_prior_list)\n', (12341, 12363), False, 'from copy import deepcopy\n'), ((20045, 20083), 'numpy.nanmean', 'np.nanmean', (['response[:max_seasonality]'], {}), '(response[:max_seasonality])\n', (20055, 20083), True, 'import numpy as np\n'), ((20133, 20153), 'numpy.nanmean', 'np.nanmean', (['response'], {}), '(response)\n', (20143, 20153), True, 'import numpy as np\n'), ((20189, 20207), 'numpy.isnan', 'np.isnan', (['response'], {}), '(response)\n', (20197, 20207), True, 'import numpy as np\n'), ((20289, 20321), 'numpy.where', 'np.where', (['self.is_valid_response'], {}), '(self.is_valid_response)\n', (20297, 20321), True, 'import numpy as np\n'), ((23486, 23559), 'numpy.ones', 'np.ones', (['(self._num_of_positive_regressors, self._num_knots_coefficients)'], {}), '((self._num_of_positive_regressors, self._num_knots_coefficients))\n', (23493, 23559), True, 'import numpy as np\n'), ((25515, 25565), 'numpy.array', 'np.array', (['self._positive_regressor_init_knot_scale'], {}), '(self._positive_regressor_init_knot_scale)\n', (25523, 25565), True, 'import numpy as np\n'), ((25820, 25893), 'numpy.ones', 'np.ones', (['(self._num_of_negative_regressors, self._num_knots_coefficients)'], {}), '((self._num_of_negative_regressors, self._num_knots_coefficients))\n', (25827, 25893), True, 'import numpy as np\n'), ((27765, 27815), 'numpy.array', 'np.array', (['self._negative_regressor_init_knot_scale'], {}), '(self._negative_regressor_init_knot_scale)\n', (27773, 27815), True, 'import numpy as np\n'), ((28117, 28189), 'numpy.ones', 'np.ones', (['(self._num_of_regular_regressors, self._num_knots_coefficients)'], {}), '((self._num_of_regular_regressors, self._num_knots_coefficients))\n', (28124, 28189), True, 'import numpy as np\n'), ((30108, 30157), 'numpy.array', 'np.array', (['self._regular_regressor_init_knot_scale'], {}), '(self._regular_regressor_init_knot_scale)\n', (30116, 30157), True, 'import numpy as np\n'), ((30866, 30910), 'numpy.arange', 'np.arange', (['(start + 1)', '(start + output_len + 1)'], {}), '(start + 1, start + output_len + 1)\n', (30875, 30910), True, 'import numpy as np\n'), ((34215, 34258), 'numpy.zeros', 'np.zeros', (['(1, df.shape[0])'], {'dtype': 'np.double'}), '((1, df.shape[0]), dtype=np.double)\n', (34223, 34258), True, 'import numpy as np\n'), ((34817, 34860), 'numpy.zeros', 'np.zeros', (['(1, df.shape[0])'], {'dtype': 'np.double'}), '((1, df.shape[0]), dtype=np.double)\n', (34825, 34860), True, 'import numpy as np\n'), ((37102, 37139), 'numpy.arange', 'np.arange', (['(1)', '(num_of_observations + 1)'], {}), '(1, num_of_observations + 1)\n', (37111, 37139), True, 'import numpy as np\n'), ((39120, 39150), 'numpy.squeeze', 'np.squeeze', (['self._seas_term', '(0)'], {}), '(self._seas_term, 0)\n', (39130, 39150), True, 'import numpy as np\n'), ((41839, 41875), 'torch.cat', 'torch.cat', (['(rr_beta, pr_beta)'], {'dim': '(1)'}), '((rr_beta, pr_beta), dim=1)\n', (41848, 41875), False, 'import torch\n'), ((44227, 44271), 'numpy.arange', 'np.arange', (['(start + 1)', '(start + output_len + 1)'], {}), '(start + 1, start + output_len + 1)\n', (44236, 44271), True, 'import numpy as np\n'), ((47201, 47252), 'numpy.sum', 'np.sum', (['(regressor_betas * regressor_matrix)'], {'axis': '(-1)'}), '(regressor_betas * regressor_matrix, axis=-1)\n', (47207, 47252), True, 'import numpy as np\n'), ((54863, 54888), 'numpy.expand_dims', 'np.expand_dims', (['coefs', '(-1)'], {}), '(coefs, -1)\n', (54877, 54888), True, 'import numpy as np\n'), ((55625, 55658), 'numpy.quantile', 'np.quantile', (['coefs', 'lower'], {'axis': '(0)'}), '(coefs, lower, axis=0)\n', (55636, 55658), True, 'import numpy as np\n'), ((55692, 55725), 'numpy.quantile', 'np.quantile', (['coefs', 'upper'], {'axis': '(0)'}), '(coefs, upper, axis=0)\n', (55703, 55725), True, 'import numpy as np\n'), ((57134, 57164), 'numpy.expand_dims', 'np.expand_dims', (['coef_knots', '(-1)'], {}), '(coef_knots, -1)\n', (57148, 57164), True, 'import numpy as np\n'), ((57232, 57261), 'numpy.expand_dims', 'np.expand_dims', (['coef_knots', '(1)'], {}), '(coef_knots, 1)\n', (57246, 57261), True, 'import numpy as np\n'), ((57347, 57379), 'numpy.transpose', 'np.transpose', (['coef_knots[:, idx]'], {}), '(coef_knots[:, idx])\n', (57359, 57379), True, 'import numpy as np\n'), ((61620, 61630), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (61628, 61630), True, 'import matplotlib.pyplot as plt\n'), ((61657, 61668), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (61666, 61668), True, 'import matplotlib.pyplot as plt\n'), ((65263, 65273), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (65271, 65273), True, 'import matplotlib.pyplot as plt\n'), ((65300, 65311), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (65309, 65311), True, 'import matplotlib.pyplot as plt\n'), ((22648, 22685), 'numpy.arange', 'np.arange', (['(1)', '(num_of_observations + 1)'], {}), '(1, num_of_observations + 1)\n', (22657, 22685), True, 'import numpy as np\n'), ((23626, 23650), 'numpy.ones', 'np.ones', (['local_val.shape'], {}), '(local_val.shape)\n', (23633, 23650), True, 'import numpy as np\n'), ((23698, 23722), 'numpy.ones', 'np.ones', (['local_val.shape'], {}), '(local_val.shape)\n', (23705, 23722), True, 'import numpy as np\n'), ((25155, 25213), 'numpy.expand_dims', 'np.expand_dims', (['self._positive_regressor_knot_scale_1d', '(-1)'], {}), '(self._positive_regressor_knot_scale_1d, -1)\n', (25169, 25213), True, 'import numpy as np\n'), ((25960, 25984), 'numpy.ones', 'np.ones', (['local_val.shape'], {}), '(local_val.shape)\n', (25967, 25984), True, 'import numpy as np\n'), ((26032, 26056), 'numpy.ones', 'np.ones', (['local_val.shape'], {}), '(local_val.shape)\n', (26039, 26056), True, 'import numpy as np\n'), ((27405, 27463), 'numpy.expand_dims', 'np.expand_dims', (['self._negative_regressor_knot_scale_1d', '(-1)'], {}), '(self._negative_regressor_knot_scale_1d, -1)\n', (27419, 27463), True, 'import numpy as np\n'), ((28256, 28280), 'numpy.ones', 'np.ones', (['local_val.shape'], {}), '(local_val.shape)\n', (28263, 28280), True, 'import numpy as np\n'), ((28328, 28352), 'numpy.ones', 'np.ones', (['local_val.shape'], {}), '(local_val.shape)\n', (28335, 28352), True, 'import numpy as np\n'), ((29752, 29809), 'numpy.expand_dims', 'np.expand_dims', (['self._regular_regressor_knot_scale_1d', '(-1)'], {}), '(self._regular_regressor_knot_scale_1d, -1)\n', (29766, 29809), True, 'import numpy as np\n'), ((31237, 31274), 'numpy.in1d', 'np.in1d', (['train_date_array', 'date_array'], {}), '(train_date_array, date_array)\n', (31244, 31274), True, 'import numpy as np\n'), ((34592, 34641), 'numpy.sum', 'np.sum', (['(seas_coef * seas_regresor_matrix)'], {'axis': '(-1)'}), '(seas_coef * seas_regresor_matrix, axis=-1)\n', (34598, 34641), True, 'import numpy as np\n'), ((34675, 34709), 'numpy.expand_dims', 'np.expand_dims', (['seas_regression', '(0)'], {}), '(seas_regression, 0)\n', (34689, 34709), True, 'import numpy as np\n'), ((44820, 44899), 'numpy.arange', 'np.arange', (['(self.knots_tp_level[-1] + lev_knot_width)', 'new_tp[-1]', 'lev_knot_width'], {}), '(self.knots_tp_level[-1] + lev_knot_width, new_tp[-1], lev_knot_width)\n', (44829, 44899), True, 'import numpy as np\n'), ((44937, 44994), 'numpy.concatenate', 'np.concatenate', (['[self.knots_tp_level, knots_tp_level_out]'], {}), '([self.knots_tp_level, knots_tp_level_out])\n', (44951, 44994), True, 'import numpy as np\n'), ((45387, 45438), 'numpy.concatenate', 'np.concatenate', (['[lev_knot_in, lev_knot_out]'], {'axis': '(1)'}), '([lev_knot_in, lev_knot_out], axis=1)\n', (45401, 45438), True, 'import numpy as np\n'), ((50319, 50345), 'pandas.to_datetime', 'pd.to_datetime', (['date_array'], {}), '(date_array)\n', (50333, 50345), True, 'import pandas as pd\n'), ((51579, 51623), 'numpy.arange', 'np.arange', (['(start + 1)', '(start + output_len + 1)'], {}), '(start + 1, start + output_len + 1)\n', (51588, 51623), True, 'import numpy as np\n'), ((29164, 29203), 'numpy.fabs', 'np.fabs', (['self._regular_regressor_matrix'], {}), '(self._regular_regressor_matrix)\n', (29171, 29203), True, 'import numpy as np\n'), ((30801, 30821), 'pandas.Index', 'pd.Index', (['date_array'], {}), '(date_array)\n', (30809, 30821), True, 'import pandas as pd\n'), ((44162, 44182), 'pandas.Index', 'pd.Index', (['date_array'], {}), '(date_array)\n', (44170, 44182), True, 'import pandas as pd\n'), ((49502, 49532), 'numpy.expand_dims', 'np.expand_dims', (['coef_knots', '(-1)'], {}), '(coef_knots, -1)\n', (49516, 49532), True, 'import numpy as np\n'), ((49616, 49645), 'numpy.expand_dims', 'np.expand_dims', (['coef_knots', '(1)'], {}), '(coef_knots, 1)\n', (49630, 49645), True, 'import numpy as np\n'), ((51989, 52019), 'numpy.expand_dims', 'np.expand_dims', (['coef_knots', '(-1)'], {}), '(coef_knots, -1)\n', (52003, 52019), True, 'import numpy as np\n'), ((52148, 52178), 'numpy.expand_dims', 'np.expand_dims', (['coef_knots', '(-1)'], {}), '(coef_knots, -1)\n', (52162, 52178), True, 'import numpy as np\n'), ((52365, 52399), 'numpy.expand_dims', 'np.expand_dims', (['regressor_betas', '(0)'], {}), '(regressor_betas, 0)\n', (52379, 52399), True, 'import numpy as np\n'), ((52655, 52711), 'numpy.repeat', 'np.repeat', (['regressor_betas'], {'repeats': 'coef_repeats', 'axis': '(1)'}), '(regressor_betas, repeats=coef_repeats, axis=1)\n', (52664, 52711), True, 'import numpy as np\n'), ((60889, 60919), 'numpy.arange', 'np.arange', (['(0)', 'coef_df.shape[0]'], {}), '(0, coef_df.shape[0])\n', (60898, 60919), True, 'import numpy as np\n'), ((19519, 19544), 'numpy.max', 'np.max', (['self._seasonality'], {}), '(self._seasonality)\n', (19525, 19544), True, 'import numpy as np\n'), ((19971, 19996), 'numpy.max', 'np.max', (['self._seasonality'], {}), '(self._seasonality)\n', (19977, 19996), True, 'import numpy as np\n'), ((24270, 24327), 'numpy.fabs', 'np.fabs', (['self._positive_regressor_matrix[str_idx:end_idx]'], {}), '(self._positive_regressor_matrix[str_idx:end_idx])\n', (24277, 24327), True, 'import numpy as np\n'), ((24391, 24431), 'numpy.fabs', 'np.fabs', (['self._positive_regressor_matrix'], {}), '(self._positive_regressor_matrix)\n', (24398, 24431), True, 'import numpy as np\n'), ((26604, 26661), 'numpy.fabs', 'np.fabs', (['self._negative_regressor_matrix[str_idx:end_idx]'], {}), '(self._negative_regressor_matrix[str_idx:end_idx])\n', (26611, 26661), True, 'import numpy as np\n'), ((26725, 26765), 'numpy.fabs', 'np.fabs', (['self._negative_regressor_matrix'], {}), '(self._negative_regressor_matrix)\n', (26732, 26765), True, 'import numpy as np\n'), ((28900, 28956), 'numpy.fabs', 'np.fabs', (['self._regular_regressor_matrix[str_idx:end_idx]'], {}), '(self._regular_regressor_matrix[str_idx:end_idx])\n', (28907, 28956), True, 'import numpy as np\n'), ((29474, 29494), 'numpy.isnan', 'np.isnan', (['multiplier'], {}), '(multiplier)\n', (29482, 29494), True, 'import numpy as np\n'), ((33543, 33563), 'pandas.Index', 'pd.Index', (['date_array'], {}), '(date_array)\n', (33551, 33563), True, 'import pandas as pd\n'), ((51206, 51232), 'pandas.Index', 'pd.Index', (['train_date_array'], {}), '(train_date_array)\n', (51214, 51232), True, 'import pandas as pd\n'), ((24875, 24895), 'numpy.isnan', 'np.isnan', (['multiplier'], {}), '(multiplier)\n', (24883, 24895), True, 'import numpy as np\n'), ((27209, 27229), 'numpy.isnan', 'np.isnan', (['multiplier'], {}), '(multiplier)\n', (27217, 27229), True, 'import numpy as np\n'), ((40274, 40300), 'numpy.full', 'np.full', (['expected_shape', 'm'], {}), '(expected_shape, m)\n', (40281, 40300), True, 'import numpy as np\n'), ((40379, 40406), 'numpy.full', 'np.full', (['expected_shape', 'sd'], {}), '(expected_shape, sd)\n', (40386, 40406), True, 'import numpy as np\n'), ((18577, 18606), 'numpy.array', 'np.array', (['self._regressor_col'], {}), '(self._regressor_col)\n', (18585, 18606), True, 'import numpy as np\n')]
""" Loading and interacting with data in the change filmstrips notebook, inside the Real_world_examples folder. """ # Load modules import os import dask import datacube import warnings import numpy as np import pandas as pd import xarray as xr import matplotlib.pyplot as plt from odc.algo import geomedian_with_mads from odc.ui import select_on_a_map from dask.utils import parse_bytes from datacube.utils.geometry import CRS, assign_crs from datacube.utils.rio import configure_s3_access from datacube.utils.dask import start_local_dask from ipyleaflet import basemaps, basemap_to_tiles # Load utility functions from deafrica_tools.datahandling import load_ard, mostcommon_crs from deafrica_tools.coastal import tidal_tag from deafrica_tools.dask import create_local_dask_cluster def run_filmstrip_app( output_name, time_range, time_step, tide_range=(0.0, 1.0), resolution=(-30, 30), max_cloud=0.5, ls7_slc_off=False, size_limit=10000, ): """ An interactive app that allows the user to select a region from a map, then load Digital Earth Africa Landsat data and combine it using the geometric median ("geomedian") statistic to reveal the median or 'typical' appearance of the landscape for a series of time periods. The results for each time period are combined into a 'filmstrip' plot which visualises how the landscape has changed in appearance across time, with a 'change heatmap' panel highlighting potential areas of greatest change. For coastal applications, the analysis can be customised to select only satellite images obtained during a specific tidal range (e.g. low, average or high tide). Last modified: April 2020 Parameters ---------- output_name : str A name that will be used to name the output filmstrip plot file. time_range : tuple A tuple giving the date range to analyse (e.g. `time_range = ('1988-01-01', '2017-12-31')`). time_step : dict This parameter sets the length of the time periods to compare (e.g. `time_step = {'years': 5}` will generate one filmstrip plot for every five years of data; `time_step = {'months': 18}` will generate one plot for each 18 month period etc. Time periods are counted from the first value given in `time_range`. tide_range : tuple, optional An optional parameter that can be used to generate filmstrip plots based on specific ocean tide conditions. This can be valuable for analysing change consistently along the coast. For example, `tide_range = (0.0, 0.2)` will select only satellite images acquired at the lowest 20% of tides; `tide_range = (0.8, 1.0)` will select images from the highest 20% of tides. The default is `tide_range = (0.0, 1.0)` which will select all images regardless of tide. resolution : tuple, optional The spatial resolution to load data. The default is `resolution = (-30, 30)`, which will load data at 30 m pixel resolution. Increasing this (e.g. to `resolution = (-100, 100)`) can be useful for loading large spatial extents. max_cloud : float, optional This parameter can be used to exclude satellite images with excessive cloud. The default is `0.5`, which will keep all images with less than 50% cloud. ls7_slc_off : bool, optional An optional boolean indicating whether to include data from after the Landsat 7 SLC failure (i.e. SLC-off). Defaults to False, which removes all Landsat 7 observations > May 31 2003. size_limit : int, optional An optional integer (in hectares) specifying the size limit for the data query. Queries larger than this size will receive a warning that he data query is too large (and may therefore result in memory errors). Returns ------- ds_geomedian : xarray Dataset An xarray dataset containing geomedian composites for each timestep in the analysis. """ ######################## # Select and load data # ######################## # Define centre_coords as a global variable global centre_coords # Test if centre_coords is in the global namespace; # use default value if it isn't if "centre_coords" not in globals(): centre_coords = (6.587292, 1.532833) # Plot interactive map to select area basemap = basemap_to_tiles(basemaps.Esri.WorldImagery) geopolygon = select_on_a_map(height="600px", layers=(basemap,), center=centre_coords, zoom=14) # Set centre coords based on most recent selection to re-focus # subsequent data selections centre_coords = geopolygon.centroid.points[0][::-1] # Test size of selected area msq_per_hectare = 10000 area = geopolygon.to_crs(crs=CRS("epsg:6933")).area / msq_per_hectare radius = np.round(np.sqrt(size_limit), 1) if area > size_limit: print(f"Warning: Your selected area is {area:.00f} hectares. " f"Please select an area of less than {size_limit} hectares." f"\nTo select a smaller area, re-run the cell " f"above and draw a new polygon.") else: print("Starting analysis...") # Connect to datacube database dc = datacube.Datacube(app="Change_filmstrips") # Configure local dask cluster client = create_local_dask_cluster(return_client=True) # Obtain native CRS crs = mostcommon_crs(dc=dc, product="ls8_sr", query={ "time": "2014", "geopolygon": geopolygon }) # Create query based on time range, area selected, custom params query = { "time": time_range, "geopolygon": geopolygon, "output_crs": crs, "resolution": resolution, "dask_chunks": { "x": 3000, "y": 3000 }, "align": (resolution[1] / 2.0, resolution[1] / 2.0), } # Load data from all three Landsats warnings.filterwarnings("ignore") ds = load_ard( dc=dc, measurements=["red", "green", "blue"], products=["ls5_sr", "ls7_sr", "ls8_sr"], min_gooddata=max_cloud, ls7_slc_off=ls7_slc_off, **query, ) # Optionally calculate tides for each timestep in the satellite # dataset and drop any observations out side this range if tide_range != (0.0, 1.0): ds = tidal_tag(ds=ds, tidepost_lat=None, tidepost_lon=None) min_tide, max_tide = ds.tide_height.quantile(tide_range).values ds = ds.sel(time=(ds.tide_height >= min_tide) & (ds.tide_height <= max_tide)) ds = ds.drop("tide_height") print(f" Keeping {len(ds.time)} observations with tides " f"between {min_tide:.2f} and {max_tide:.2f} m") # Create time step ranges to generate filmstrips from bins_dt = pd.date_range(start=time_range[0], end=time_range[1], freq=pd.DateOffset(**time_step)) # Bin all satellite observations by timestep. If some observations # fall outside the upper bin, label these with the highest bin labels = bins_dt.astype("str") time_steps = (pd.cut(ds.time.values, bins_dt, labels=labels[:-1]).add_categories( labels[-1]).fillna(labels[-1])) time_steps_var = xr.DataArray(time_steps, [("time", ds.time.values)], name="timestep") # Resample data temporally into time steps, and compute geomedians ds_geomedian = (ds.groupby(time_steps_var).apply( lambda ds_subset: geomedian_with_mads( ds_subset, compute_mads=False, compute_count=False))) print("\nGenerating geomedian composites and plotting " "filmstrips... (click the Dashboard link above for status)") ds_geomedian = ds_geomedian.compute() # Reset CRS that is lost during geomedian compositing ds_geomedian = assign_crs(ds_geomedian, crs=ds.geobox.crs) ############ # Plotting # ############ # Convert to array and extract vmin/vmax output_array = ds_geomedian[["red", "green", "blue"]].to_array() percentiles = output_array.quantile(q=(0.02, 0.98)).values # Create the plot with one subplot more than timesteps in the # dataset. Figure width is set based on the number of subplots # and aspect ratio n_obs = output_array.sizes["timestep"] ratio = output_array.sizes["x"] / output_array.sizes["y"] fig, axes = plt.subplots(1, n_obs + 1, figsize=(5 * ratio * (n_obs + 1), 5)) fig.subplots_adjust(wspace=0.05, hspace=0.05) # Add timesteps to the plot, set aspect to equal to preserve shape for i, ax_i in enumerate(axes.flatten()[:n_obs]): output_array.isel(timestep=i).plot.imshow(ax=ax_i, vmin=percentiles[0], vmax=percentiles[1]) ax_i.get_xaxis().set_visible(False) ax_i.get_yaxis().set_visible(False) ax_i.set_aspect("equal") # Add change heatmap panel to final subplot. Heatmap is computed # by first taking the log of the array (so change in dark areas # can be identified), then computing standard deviation between # all timesteps (np.log(output_array).std(dim=["timestep"]).mean( dim="variable").plot.imshow(ax=axes.flatten()[-1], robust=True, cmap="magma", add_colorbar=False)) axes.flatten()[-1].get_xaxis().set_visible(False) axes.flatten()[-1].get_yaxis().set_visible(False) axes.flatten()[-1].set_aspect("equal") axes.flatten()[-1].set_title("Change heatmap") # Export to file date_string = "_".join(time_range) ts_v = list(time_step.values())[0] ts_k = list(time_step.keys())[0] fig.savefig( f"filmstrip_{output_name}_{date_string}_{ts_v}{ts_k}.png", dpi=150, bbox_inches="tight", pad_inches=0.1, ) # close dask client client.shutdown() return ds_geomedian
[ "ipyleaflet.basemap_to_tiles", "datacube.utils.geometry.assign_crs", "numpy.sqrt", "datacube.Datacube", "odc.ui.select_on_a_map", "numpy.log", "deafrica_tools.datahandling.mostcommon_crs", "pandas.cut", "deafrica_tools.datahandling.load_ard", "deafrica_tools.dask.create_local_dask_cluster", "mat...
[((4518, 4562), 'ipyleaflet.basemap_to_tiles', 'basemap_to_tiles', (['basemaps.Esri.WorldImagery'], {}), '(basemaps.Esri.WorldImagery)\n', (4534, 4562), False, 'from ipyleaflet import basemaps, basemap_to_tiles\n'), ((4580, 4665), 'odc.ui.select_on_a_map', 'select_on_a_map', ([], {'height': '"""600px"""', 'layers': '(basemap,)', 'center': 'centre_coords', 'zoom': '(14)'}), "(height='600px', layers=(basemap,), center=centre_coords,\n zoom=14)\n", (4595, 4665), False, 'from odc.ui import select_on_a_map\n'), ((5076, 5095), 'numpy.sqrt', 'np.sqrt', (['size_limit'], {}), '(size_limit)\n', (5083, 5095), True, 'import numpy as np\n'), ((5485, 5527), 'datacube.Datacube', 'datacube.Datacube', ([], {'app': '"""Change_filmstrips"""'}), "(app='Change_filmstrips')\n", (5502, 5527), False, 'import datacube\n'), ((5585, 5630), 'deafrica_tools.dask.create_local_dask_cluster', 'create_local_dask_cluster', ([], {'return_client': '(True)'}), '(return_client=True)\n', (5610, 5630), False, 'from deafrica_tools.dask import create_local_dask_cluster\n'), ((5674, 5767), 'deafrica_tools.datahandling.mostcommon_crs', 'mostcommon_crs', ([], {'dc': 'dc', 'product': '"""ls8_sr"""', 'query': "{'time': '2014', 'geopolygon': geopolygon}"}), "(dc=dc, product='ls8_sr', query={'time': '2014', 'geopolygon':\n geopolygon})\n", (5688, 5767), False, 'from deafrica_tools.datahandling import load_ard, mostcommon_crs\n'), ((6375, 6408), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (6398, 6408), False, 'import warnings\n'), ((6422, 6583), 'deafrica_tools.datahandling.load_ard', 'load_ard', ([], {'dc': 'dc', 'measurements': "['red', 'green', 'blue']", 'products': "['ls5_sr', 'ls7_sr', 'ls8_sr']", 'min_gooddata': 'max_cloud', 'ls7_slc_off': 'ls7_slc_off'}), "(dc=dc, measurements=['red', 'green', 'blue'], products=['ls5_sr',\n 'ls7_sr', 'ls8_sr'], min_gooddata=max_cloud, ls7_slc_off=ls7_slc_off,\n **query)\n", (6430, 6583), False, 'from deafrica_tools.datahandling import load_ard, mostcommon_crs\n'), ((7902, 7971), 'xarray.DataArray', 'xr.DataArray', (['time_steps', "[('time', ds.time.values)]"], {'name': '"""timestep"""'}), "(time_steps, [('time', ds.time.values)], name='timestep')\n", (7914, 7971), True, 'import xarray as xr\n'), ((8537, 8580), 'datacube.utils.geometry.assign_crs', 'assign_crs', (['ds_geomedian'], {'crs': 'ds.geobox.crs'}), '(ds_geomedian, crs=ds.geobox.crs)\n', (8547, 8580), False, 'from datacube.utils.geometry import CRS, assign_crs\n'), ((9137, 9201), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(n_obs + 1)'], {'figsize': '(5 * ratio * (n_obs + 1), 5)'}), '(1, n_obs + 1, figsize=(5 * ratio * (n_obs + 1), 5))\n', (9149, 9201), True, 'import matplotlib.pyplot as plt\n'), ((6850, 6904), 'deafrica_tools.coastal.tidal_tag', 'tidal_tag', ([], {'ds': 'ds', 'tidepost_lat': 'None', 'tidepost_lon': 'None'}), '(ds=ds, tidepost_lat=None, tidepost_lon=None)\n', (6859, 6904), False, 'from deafrica_tools.coastal import tidal_tag\n'), ((7478, 7504), 'pandas.DateOffset', 'pd.DateOffset', ([], {}), '(**time_step)\n', (7491, 7504), True, 'import pandas as pd\n'), ((8174, 8245), 'odc.algo.geomedian_with_mads', 'geomedian_with_mads', (['ds_subset'], {'compute_mads': '(False)', 'compute_count': '(False)'}), '(ds_subset, compute_mads=False, compute_count=False)\n', (8193, 8245), False, 'from odc.algo import geomedian_with_mads\n'), ((5013, 5029), 'datacube.utils.geometry.CRS', 'CRS', (['"""epsg:6933"""'], {}), "('epsg:6933')\n", (5016, 5029), False, 'from datacube.utils.geometry import CRS, assign_crs\n'), ((7714, 7765), 'pandas.cut', 'pd.cut', (['ds.time.values', 'bins_dt'], {'labels': 'labels[:-1]'}), '(ds.time.values, bins_dt, labels=labels[:-1])\n', (7720, 7765), True, 'import pandas as pd\n'), ((10053, 10073), 'numpy.log', 'np.log', (['output_array'], {}), '(output_array)\n', (10059, 10073), True, 'import numpy as np\n')]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon May 3 15:28:32 2021 @author: <NAME> & <NAME> """ # ============================================================================= # Importing necessary libraries # ============================================================================= import pandas as pd import numpy as np #for dataset from data_filtering import highschool from data_filtering import university_exam_data #for regression/statistical analysis from statsmodels.formula.api import ols from statsmodels.stats.outliers_influence import variance_inflation_factor import statsmodels.api as sm from patsy import dmatrices #for visualization import seaborn as sns import matplotlib.pyplot as plt import plotly.express as px #for LaTex table from stargazer.stargazer import Stargazer from IPython.core.display import HTML # ============================================================================= # ============================================================================= # EFFICIENCY FACTOR REGRESSION # ============================================================================= # ============================================================================= #define location for output graph_location="graphs/" table_location="table/" # ============================================================================= # Checking correlation and visualize # ============================================================================= #create new dataframe and remove unnecessary columns to_corr_check = highschool to_corr_check = to_corr_check.drop(columns = ["factor", "bubblesize", "province", "lowest_score" ]) #find correlation coefficients to_corr_check.corr() #visualize sns.heatmap(to_corr_check.corr()) #save as png file plt.savefig(graph_location+'correlation-coefficients.png') # ============================================================================= # Creating OLS Model for Efficiency Factor Regression # ============================================================================= #remove 0 values of factor highschool= highschool[highschool['factor'] != 0] #insert log(percentile_of_2019) to dataframe highschool.insert(5, "log_percentile_of_2019", np.log(highschool["percentile_of_2019"])) #create OLS Model - Define Y and X variables factor_model = ols('factor ~ log_percentile_of_2019 + C(high_school_type) + average_diploma_grade + high_school_with_prep + high_school_dormitory + gdpdata ', data=highschool) y = highschool["factor"] X = highschool[['log_percentile_of_2019','high_school_type' , "average_diploma_grade" , "high_school_with_prep" , "high_school_dormitory" , "gdpdata"]] #fit Model fitted_factor_model = factor_model.fit() fitted_factor_model.get_robustcov_results().summary() # ============================================================================= # Find Predicted Values # ============================================================================= X = sm.add_constant(X) predicted_values = fitted_factor_model.predict(X) #visualize predicted vs real values highschool = highschool.rename_axis('index1').reset_index() highschool.insert(1, "predicted_factor", predicted_values) highschool.insert(2, 'real_factor', highschool['factor']) fig_prediction_vs_factor = px.line(highschool, x="index1", y=highschool.columns[1:3] ) fig_prediction_vs_factor.update_traces(mode="lines", hovertemplate=None) fig_prediction_vs_factor.update_layout(hovermode="x") fig_prediction_vs_factor.update_layout( xaxis_title="Indexes", yaxis_title="Predicted and Real Factor Value ", legend_title="Predicted vs Real", legend=dict( yanchor="bottom", y=0.01, xanchor="left", x=0.01 ), font=dict( family="Roboto", size=8, color="#011126" ) ) fig_prediction_vs_factor.show() fig_prediction_vs_factor.write_html(graph_location+"prediction_vs_factor.html",auto_open=True) fig_prediction_vs_factor.write_image(graph_location+"prediction_vs_factor.pdf") #save as pdf file # ============================================================================= # Hypothesis Testing and Check Multicollinearity # ============================================================================= #find t-score hypothesis = 'high_school_dormitory = 0' #can used with other hypothesis t_test = fitted_factor_model.t_test(hypothesis) #calculate VIF y, X = dmatrices('factor ~ log_percentile_of_2019 + high_school_type + average_diploma_grade + high_school_with_prep + high_school_dormitory + gdpdata ', data=highschool, return_type='dataframe') vif_factor = pd.DataFrame() vif_factor['VIF'] = [variance_inflation_factor(X.values, i) for i in range(X.shape[1])] vif_factor['variable'] = X.columns # ============================================================================= # Create LaTex Table # ============================================================================= stargazer = Stargazer([fitted_factor_model]) HTML(stargazer.render_html()) f = open(table_location+'my_factor_reg.tex', 'w') f.write(stargazer.render_latex()) f.close() # ============================================================================= # ============================================================================= # EXAM SCORE REGRESSION # ============================================================================= # ============================================================================= # ============================================================================= # Creating OLS Model for Exam Score Regression # ============================================================================= #remove 0 values of factor university_exam_data= university_exam_data[university_exam_data['lowest_score'] != 0] #insert log(percentile_of_2019) to dataframe university_exam_data.insert(5, "log_percentile_of_2019", np.log(university_exam_data["percentile_of_2019"])) #create OLS Model - Define Y and X variables exam_model = ols('lowest_score ~ log_percentile_of_2019 + C(high_school_type) + newly_graduated_student + average_diploma_grade + high_school_with_prep + high_school_dormitory + gdpdata ', data=university_exam_data) y_exam = university_exam_data["lowest_score"] X_exam = university_exam_data[['log_percentile_of_2019','high_school_type' ,"newly_graduated_student", "average_diploma_grade" , "high_school_with_prep" , "high_school_dormitory" , "gdpdata"]] #fit Model fitted_exam_model = exam_model.fit() fitted_exam_model.get_robustcov_results().summary() # ============================================================================= # Find Predicted Values # ============================================================================= X_exam = sm.add_constant(X_exam) predicted_values_exam = fitted_exam_model.predict(X_exam) #visualize predicted vs real values university_exam_data = university_exam_data.rename_axis('index1').reset_index() university_exam_data.insert(1, "predicted_exam_score", predicted_values_exam) university_exam_data.insert(2, 'real_score', university_exam_data['lowest_score']) fig_prediction_vs_exam = px.line(university_exam_data, x="index1", y=university_exam_data.columns[1:3] ) fig_prediction_vs_exam.update_traces(mode="lines", hovertemplate=None) fig_prediction_vs_exam.update_layout(hovermode="x") fig_prediction_vs_exam.update_layout( xaxis_title="Indexes", yaxis_title="Predicted and Real Exam Score", legend_title="Predicted vs Real", legend=dict( yanchor="bottom", y=0.01, xanchor="left", x=0.01 ), font=dict( family="Roboto", size=8, color="#011126" ) ) fig_prediction_vs_exam.show() fig_prediction_vs_exam.write_html(graph_location+"prediction_vs_exam.html",auto_open=True) fig_prediction_vs_exam.write_image(graph_location+"prediction_vs_exam.pdf") #save as pdf file # ============================================================================= # Hypothesis Testing and Check Multicollinearity # ============================================================================= #find t-score hypothesis_exam = 'average_diploma_grade = 0' #can used with other hypothesis t_test = fitted_exam_model.t_test(hypothesis_exam) #calculate VIF y_exam, X_exam = dmatrices('lowest_score ~ log_percentile_of_2019 + C(high_school_type) + newly_graduated_student + average_diploma_grade + high_school_with_prep + high_school_dormitory + gdpdata ', data=university_exam_data, return_type='dataframe') vif_exam = pd.DataFrame() vif_exam['VIF'] = [variance_inflation_factor(X_exam.values, i) for i in range(X_exam.shape[1])] vif_exam['variable'] = X_exam.columns # ============================================================================= # Create LaTex Table # ============================================================================= stargazer = Stargazer([fitted_exam_model]) HTML(stargazer.render_html()) f = open(table_location+'my_exam_reg.tex', 'w') f.write(stargazer.render_latex()) f.close()
[ "data_filtering.university_exam_data.rename_axis", "matplotlib.pyplot.savefig", "data_filtering.university_exam_data.insert", "pandas.DataFrame", "numpy.log", "data_filtering.highschool.insert", "stargazer.stargazer.Stargazer", "plotly.express.line", "statsmodels.api.add_constant", "statsmodels.fo...
[((1788, 1848), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(graph_location + 'correlation-coefficients.png')"], {}), "(graph_location + 'correlation-coefficients.png')\n", (1799, 1848), True, 'import matplotlib.pyplot as plt\n'), ((2336, 2507), 'statsmodels.formula.api.ols', 'ols', (['"""factor ~ log_percentile_of_2019 + C(high_school_type) + average_diploma_grade + high_school_with_prep + high_school_dormitory + gdpdata """'], {'data': 'highschool'}), "('factor ~ log_percentile_of_2019 + C(high_school_type) + average_diploma_grade + high_school_with_prep + high_school_dormitory + gdpdata '\n , data=highschool)\n", (2339, 2507), False, 'from statsmodels.formula.api import ols\n'), ((2978, 2996), 'statsmodels.api.add_constant', 'sm.add_constant', (['X'], {}), '(X)\n', (2993, 2996), True, 'import statsmodels.api as sm\n'), ((3144, 3202), 'data_filtering.highschool.insert', 'highschool.insert', (['(1)', '"""predicted_factor"""', 'predicted_values'], {}), "(1, 'predicted_factor', predicted_values)\n", (3161, 3202), False, 'from data_filtering import highschool\n'), ((3203, 3260), 'data_filtering.highschool.insert', 'highschool.insert', (['(2)', '"""real_factor"""', "highschool['factor']"], {}), "(2, 'real_factor', highschool['factor'])\n", (3220, 3260), False, 'from data_filtering import highschool\n'), ((3288, 3346), 'plotly.express.line', 'px.line', (['highschool'], {'x': '"""index1"""', 'y': 'highschool.columns[1:3]'}), "(highschool, x='index1', y=highschool.columns[1:3])\n", (3295, 3346), True, 'import plotly.express as px\n'), ((4431, 4635), 'patsy.dmatrices', 'dmatrices', (['"""factor ~ log_percentile_of_2019 + high_school_type + average_diploma_grade + high_school_with_prep + high_school_dormitory + gdpdata """'], {'data': 'highschool', 'return_type': '"""dataframe"""'}), "(\n 'factor ~ log_percentile_of_2019 + high_school_type + average_diploma_grade + high_school_with_prep + high_school_dormitory + gdpdata '\n , data=highschool, return_type='dataframe')\n", (4440, 4635), False, 'from patsy import dmatrices\n'), ((4639, 4653), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (4651, 4653), True, 'import pandas as pd\n'), ((4972, 5004), 'stargazer.stargazer.Stargazer', 'Stargazer', (['[fitted_factor_model]'], {}), '([fitted_factor_model])\n', (4981, 5004), False, 'from stargazer.stargazer import Stargazer\n'), ((6011, 6223), 'statsmodels.formula.api.ols', 'ols', (['"""lowest_score ~ log_percentile_of_2019 + C(high_school_type) + newly_graduated_student + average_diploma_grade + high_school_with_prep + high_school_dormitory + gdpdata """'], {'data': 'university_exam_data'}), "('lowest_score ~ log_percentile_of_2019 + C(high_school_type) + newly_graduated_student + average_diploma_grade + high_school_with_prep + high_school_dormitory + gdpdata '\n , data=university_exam_data)\n", (6014, 6223), False, 'from statsmodels.formula.api import ols\n'), ((6755, 6778), 'statsmodels.api.add_constant', 'sm.add_constant', (['X_exam'], {}), '(X_exam)\n', (6770, 6778), True, 'import statsmodels.api as sm\n'), ((6954, 7031), 'data_filtering.university_exam_data.insert', 'university_exam_data.insert', (['(1)', '"""predicted_exam_score"""', 'predicted_values_exam'], {}), "(1, 'predicted_exam_score', predicted_values_exam)\n", (6981, 7031), False, 'from data_filtering import university_exam_data\n'), ((7032, 7119), 'data_filtering.university_exam_data.insert', 'university_exam_data.insert', (['(2)', '"""real_score"""', "university_exam_data['lowest_score']"], {}), "(2, 'real_score', university_exam_data[\n 'lowest_score'])\n", (7059, 7119), False, 'from data_filtering import university_exam_data\n'), ((7140, 7218), 'plotly.express.line', 'px.line', (['university_exam_data'], {'x': '"""index1"""', 'y': 'university_exam_data.columns[1:3]'}), "(university_exam_data, x='index1', y=university_exam_data.columns[1:3])\n", (7147, 7218), True, 'import plotly.express as px\n'), ((8302, 8550), 'patsy.dmatrices', 'dmatrices', (['"""lowest_score ~ log_percentile_of_2019 + C(high_school_type) + newly_graduated_student + average_diploma_grade + high_school_with_prep + high_school_dormitory + gdpdata """'], {'data': 'university_exam_data', 'return_type': '"""dataframe"""'}), "(\n 'lowest_score ~ log_percentile_of_2019 + C(high_school_type) + newly_graduated_student + average_diploma_grade + high_school_with_prep + high_school_dormitory + gdpdata '\n , data=university_exam_data, return_type='dataframe')\n", (8311, 8550), False, 'from patsy import dmatrices\n'), ((8552, 8566), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (8564, 8566), True, 'import pandas as pd\n'), ((8896, 8926), 'stargazer.stargazer.Stargazer', 'Stargazer', (['[fitted_exam_model]'], {}), '([fitted_exam_model])\n', (8905, 8926), False, 'from stargazer.stargazer import Stargazer\n'), ((2233, 2273), 'numpy.log', 'np.log', (["highschool['percentile_of_2019']"], {}), "(highschool['percentile_of_2019'])\n", (2239, 2273), True, 'import numpy as np\n'), ((4675, 4713), 'statsmodels.stats.outliers_influence.variance_inflation_factor', 'variance_inflation_factor', (['X.values', 'i'], {}), '(X.values, i)\n', (4700, 4713), False, 'from statsmodels.stats.outliers_influence import variance_inflation_factor\n'), ((5900, 5950), 'numpy.log', 'np.log', (["university_exam_data['percentile_of_2019']"], {}), "(university_exam_data['percentile_of_2019'])\n", (5906, 5950), True, 'import numpy as np\n'), ((8586, 8629), 'statsmodels.stats.outliers_influence.variance_inflation_factor', 'variance_inflation_factor', (['X_exam.values', 'i'], {}), '(X_exam.values, i)\n', (8611, 8629), False, 'from statsmodels.stats.outliers_influence import variance_inflation_factor\n'), ((3097, 3129), 'data_filtering.highschool.rename_axis', 'highschool.rename_axis', (['"""index1"""'], {}), "('index1')\n", (3119, 3129), False, 'from data_filtering import highschool\n'), ((6897, 6939), 'data_filtering.university_exam_data.rename_axis', 'university_exam_data.rename_axis', (['"""index1"""'], {}), "('index1')\n", (6929, 6939), False, 'from data_filtering import university_exam_data\n')]
import hivae import vae import sys import torch import functools import my_util import math import pathlib import argparse import numpy as np filedir = pathlib.Path(__file__).resolve().parent sys.path.append(str(filedir.parent / "privacy")) from tensorflow_privacy.privacy.analysis.rdp_accountant import compute_rdp, get_privacy_spent sys.path.append(str(filedir.parent)) import dp_utils # The method to compute the sum of the privacy budget for P3GM. # This method is depending on the tensorflow.privacy library def analysis_privacy(lot_size, data_size, sgd_sigma, gmm_sigma, gmm_iter, gmm_n_comp, sgd_epoch, pca_eps, delta=1e-5): q = lot_size / data_size sgd_steps = int(math.ceil(sgd_epoch * data_size / lot_size)) gmm_steps = gmm_iter * (2 * gmm_n_comp + 1) orders = ([1.25, 1.5, 1.75, 2., 2.25, 2.5, 3., 3.5, 4., 4.5] + list(range(5, 64)) + [128, 256, 512]) pca_rdp = np.array(orders) * 2 * (pca_eps**2) sgd_rdp = compute_rdp(q, sgd_sigma, sgd_steps, orders) gmm_rdp = compute_rdp(1, gmm_sigma, gmm_steps, orders) rdp = pca_rdp + gmm_rdp + sgd_rdp eps, _, opt_order = get_privacy_spent(orders, rdp, target_delta=delta) index = orders.index(opt_order) print(f"ratio(pca:gmm:sgd):{pca_rdp[index]/rdp[index]}:{gmm_rdp[index]/rdp[index]}:{sgd_rdp[index]/rdp[index]}") print(f"GMM + SGD + PCA (MA): {eps}, {delta}-DP") return eps, [pca_rdp[index]/rdp[index], gmm_rdp[index]/rdp[index], sgd_rdp[index]/rdp[index]] # The method to construct the P3GM class. # We prepare two types of P3GM which are depending on VAE and HI-VAE. # Refer to https://arxiv.org/abs/1807.03653 for HI-VAE. def main(): parser = argparse.ArgumentParser() parser.add_argument('--noise_sigma', '-n', type=float, default=None, help='noise_sigma') parser.add_argument('--epoch', '-e', type=int, default=None, help='epoch') args = parser.parse_args() # compute the sum of privacy budgets using RDP print(analysis_privacy(240, 62880, args.noise_sigma, 120.0, 20, 1, args.epoch, 0.01, delta=1e-5)) if __name__ == '__main__': main()
[ "math.ceil", "argparse.ArgumentParser", "pathlib.Path", "numpy.array", "tensorflow_privacy.privacy.analysis.rdp_accountant.compute_rdp", "tensorflow_privacy.privacy.analysis.rdp_accountant.get_privacy_spent" ]
[((958, 1002), 'tensorflow_privacy.privacy.analysis.rdp_accountant.compute_rdp', 'compute_rdp', (['q', 'sgd_sigma', 'sgd_steps', 'orders'], {}), '(q, sgd_sigma, sgd_steps, orders)\n', (969, 1002), False, 'from tensorflow_privacy.privacy.analysis.rdp_accountant import compute_rdp, get_privacy_spent\n'), ((1017, 1061), 'tensorflow_privacy.privacy.analysis.rdp_accountant.compute_rdp', 'compute_rdp', (['(1)', 'gmm_sigma', 'gmm_steps', 'orders'], {}), '(1, gmm_sigma, gmm_steps, orders)\n', (1028, 1061), False, 'from tensorflow_privacy.privacy.analysis.rdp_accountant import compute_rdp, get_privacy_spent\n'), ((1134, 1184), 'tensorflow_privacy.privacy.analysis.rdp_accountant.get_privacy_spent', 'get_privacy_spent', (['orders', 'rdp'], {'target_delta': 'delta'}), '(orders, rdp, target_delta=delta)\n', (1151, 1184), False, 'from tensorflow_privacy.privacy.analysis.rdp_accountant import compute_rdp, get_privacy_spent\n'), ((1696, 1721), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (1719, 1721), False, 'import argparse\n'), ((684, 727), 'math.ceil', 'math.ceil', (['(sgd_epoch * data_size / lot_size)'], {}), '(sgd_epoch * data_size / lot_size)\n', (693, 727), False, 'import math\n'), ((152, 174), 'pathlib.Path', 'pathlib.Path', (['__file__'], {}), '(__file__)\n', (164, 174), False, 'import pathlib\n'), ((908, 924), 'numpy.array', 'np.array', (['orders'], {}), '(orders)\n', (916, 924), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- """ Created on Thu Mar 29 19:36:28 2018 @author: fhp7 """ import virtual_battery as virbat import numpy as np from bokeh.plotting import figure from bokeh.io import output_file, show import model_output as out #%% Example of running the model once straight through model_df = virbat.acquire_data("Cowen_Green_Button_20180403.csv") ui_dict = virbat.set_params() result_dict, result_df = virbat.simulate(ui_dict, model_df) virbat.visualize(ui_dict, result_dict, result_df, display=False) virbat.save_results(ui_dict, result_dict, result_df, save_model_df=True) #%% Example of running the model with two different sets of parameters ### Note how using the appropriate ui_dict is very important. model_df = virbat.acquire_data("Cowen_Green_Button_20180403.csv") ui_dict_A = virbat.set_params(run_name="daily_thresh_20180522", controller_type="daily_threshold") ui_dict_B = virbat.set_params(run_name="simple_peak_20180522", controller_type="simple_peak") result_dict_A, result_df_A = virbat.simulate(ui_dict_A, model_df) result_dict_B, result_df_B = virbat.simulate(ui_dict_B, model_df) virbat.visualize(ui_dict_A, result_dict_A, result_df_A) virbat.visualize(ui_dict_B, result_dict_B, result_df_B) virbat.save_results(ui_dict_A, result_dict_A, result_df_A, save_model_df=True) virbat.save_results(ui_dict_B, result_dict_B, result_df_B, save_model_df=True) #%% Example of running the simulation multiple times to create a graph model_df = virbat.acquire_data("Cowen_Green_Button_20180403.csv") bat_cap = list(np.arange(7,13.5,0.5)) bat_val = [] for max_cap in bat_cap: ui_dict = virbat.set_params(battery_max_capacity=max_cap) result_dict, result_df = virbat.simulate(ui_dict, model_df) bat_val.append(result_dict['monthly_cost_diff_$']) output_file(filename=out.out_loc("Varying_Battery_Max_Cap.html", "Multi-Run")) val_plot = figure(plot_width=600, x_axis_label='Battery Capacity (kWh)', y_axis_label='Avg. Battery Monthly Value') val_plot.line(x=bat_cap, y=bat_val) show(val_plot)
[ "bokeh.io.show", "bokeh.plotting.figure", "virtual_battery.acquire_data", "numpy.arange", "virtual_battery.save_results", "virtual_battery.set_params", "model_output.out_loc", "virtual_battery.simulate", "virtual_battery.visualize" ]
[((319, 373), 'virtual_battery.acquire_data', 'virbat.acquire_data', (['"""Cowen_Green_Button_20180403.csv"""'], {}), "('Cowen_Green_Button_20180403.csv')\n", (338, 373), True, 'import virtual_battery as virbat\n'), ((385, 404), 'virtual_battery.set_params', 'virbat.set_params', ([], {}), '()\n', (402, 404), True, 'import virtual_battery as virbat\n'), ((431, 465), 'virtual_battery.simulate', 'virbat.simulate', (['ui_dict', 'model_df'], {}), '(ui_dict, model_df)\n', (446, 465), True, 'import virtual_battery as virbat\n'), ((467, 531), 'virtual_battery.visualize', 'virbat.visualize', (['ui_dict', 'result_dict', 'result_df'], {'display': '(False)'}), '(ui_dict, result_dict, result_df, display=False)\n', (483, 531), True, 'import virtual_battery as virbat\n'), ((533, 605), 'virtual_battery.save_results', 'virbat.save_results', (['ui_dict', 'result_dict', 'result_df'], {'save_model_df': '(True)'}), '(ui_dict, result_dict, result_df, save_model_df=True)\n', (552, 605), True, 'import virtual_battery as virbat\n'), ((761, 815), 'virtual_battery.acquire_data', 'virbat.acquire_data', (['"""Cowen_Green_Button_20180403.csv"""'], {}), "('Cowen_Green_Button_20180403.csv')\n", (780, 815), True, 'import virtual_battery as virbat\n'), ((831, 922), 'virtual_battery.set_params', 'virbat.set_params', ([], {'run_name': '"""daily_thresh_20180522"""', 'controller_type': '"""daily_threshold"""'}), "(run_name='daily_thresh_20180522', controller_type=\n 'daily_threshold')\n", (848, 922), True, 'import virtual_battery as virbat\n'), ((962, 1048), 'virtual_battery.set_params', 'virbat.set_params', ([], {'run_name': '"""simple_peak_20180522"""', 'controller_type': '"""simple_peak"""'}), "(run_name='simple_peak_20180522', controller_type=\n 'simple_peak')\n", (979, 1048), True, 'import virtual_battery as virbat\n'), ((1107, 1143), 'virtual_battery.simulate', 'virbat.simulate', (['ui_dict_A', 'model_df'], {}), '(ui_dict_A, model_df)\n', (1122, 1143), True, 'import virtual_battery as virbat\n'), ((1174, 1210), 'virtual_battery.simulate', 'virbat.simulate', (['ui_dict_B', 'model_df'], {}), '(ui_dict_B, model_df)\n', (1189, 1210), True, 'import virtual_battery as virbat\n'), ((1214, 1269), 'virtual_battery.visualize', 'virbat.visualize', (['ui_dict_A', 'result_dict_A', 'result_df_A'], {}), '(ui_dict_A, result_dict_A, result_df_A)\n', (1230, 1269), True, 'import virtual_battery as virbat\n'), ((1271, 1326), 'virtual_battery.visualize', 'virbat.visualize', (['ui_dict_B', 'result_dict_B', 'result_df_B'], {}), '(ui_dict_B, result_dict_B, result_df_B)\n', (1287, 1326), True, 'import virtual_battery as virbat\n'), ((1330, 1408), 'virtual_battery.save_results', 'virbat.save_results', (['ui_dict_A', 'result_dict_A', 'result_df_A'], {'save_model_df': '(True)'}), '(ui_dict_A, result_dict_A, result_df_A, save_model_df=True)\n', (1349, 1408), True, 'import virtual_battery as virbat\n'), ((1410, 1488), 'virtual_battery.save_results', 'virbat.save_results', (['ui_dict_B', 'result_dict_B', 'result_df_B'], {'save_model_df': '(True)'}), '(ui_dict_B, result_dict_B, result_df_B, save_model_df=True)\n', (1429, 1488), True, 'import virtual_battery as virbat\n'), ((1577, 1631), 'virtual_battery.acquire_data', 'virbat.acquire_data', (['"""Cowen_Green_Button_20180403.csv"""'], {}), "('Cowen_Green_Button_20180403.csv')\n", (1596, 1631), True, 'import virtual_battery as virbat\n'), ((1988, 2097), 'bokeh.plotting.figure', 'figure', ([], {'plot_width': '(600)', 'x_axis_label': '"""Battery Capacity (kWh)"""', 'y_axis_label': '"""Avg. Battery Monthly Value"""'}), "(plot_width=600, x_axis_label='Battery Capacity (kWh)', y_axis_label=\n 'Avg. Battery Monthly Value')\n", (1994, 2097), False, 'from bokeh.plotting import figure\n'), ((2184, 2198), 'bokeh.io.show', 'show', (['val_plot'], {}), '(val_plot)\n', (2188, 2198), False, 'from bokeh.io import output_file, show\n'), ((1648, 1671), 'numpy.arange', 'np.arange', (['(7)', '(13.5)', '(0.5)'], {}), '(7, 13.5, 0.5)\n', (1657, 1671), True, 'import numpy as np\n'), ((1725, 1772), 'virtual_battery.set_params', 'virbat.set_params', ([], {'battery_max_capacity': 'max_cap'}), '(battery_max_capacity=max_cap)\n', (1742, 1772), True, 'import virtual_battery as virbat\n'), ((1803, 1837), 'virtual_battery.simulate', 'virbat.simulate', (['ui_dict', 'model_df'], {}), '(ui_dict, model_df)\n', (1818, 1837), True, 'import virtual_battery as virbat\n'), ((1918, 1974), 'model_output.out_loc', 'out.out_loc', (['"""Varying_Battery_Max_Cap.html"""', '"""Multi-Run"""'], {}), "('Varying_Battery_Max_Cap.html', 'Multi-Run')\n", (1929, 1974), True, 'import model_output as out\n')]
# -*- coding: utf-8 -*- import numpy as np import pandas as pd import matplotlib.pyplot as plt class TimeSeries(): """A class that holds time series data Attributes: - series (pd.Series) - a pandas Series with a Datetime index. The index must be in time order. """ def __init__(self,series=None): if not series is None: self.series=series else: self.series=pd.Series() def _fget_timestamps(self): "Returns a list of the series timestamps" return list(self.series.index) timestamps=property(_fget_timestamps) def _fget_data(self): "Returns a list of the series data" return list(self.series.values) data=property(_fget_data) def date_vs_TOD(self): "Returns a DataFrame of self.series with index=times and columns=dates" s=self.series dates=s.index.date times=s.index.time s1=pd.Series(index=[dates,times],data=s.values) df=s1.unstack(level=0) return df def lookup(self,ts): """Returns the data value as time ts If there is no timestamp ts in self.series, then returns None If there are two timestamps with value ts, then the value of the lower one in the series is returned. Arguments: - ts (pd.Timestamp): """ try: v=self.series[ts] # single value or new pd.Series if isinstance(v,pd.Series): # if there is more than one timestamp with value ts v1=v[-1] # returns the value of the last timestamp if not np.isnan(v1): return v1 else: return None else: return v except KeyError: return None def nearest_timestamps(self,ts): """Returns the two nearest timestamps and their values Returns a tuple of length 4. First value is the timestamp which is nearest to and <= than ts, otherwise None Second value is the data value at this timestamp Third value is the next timestamp after the first value, otherwise None Fourth value is the data value at this timestamp """ series=self.series index=series.index if len(index)==0: return None, None, None, None a=sum(index<=ts) # set lower if a==0: lower_ts=None lower_v=None else: lower_ts=index[a-1] lower_v=series[a-1] if np.isnan(lower_v): lower_v=None # set upper if a==len(index): upper_ts=None upper_v=None else: upper_ts=index[a] upper_v=series[a] if np.isnan(upper_v): upper_v=None # return tuple return lower_ts,lower_v,upper_ts,upper_v def plot(self): "a simple plot of the data" self.series.plot(style='o') def plot_colormap(self,ax): "plots a colormap of self.series" ax.set_xlabel('Date') ax.set_ylabel('Time') df=self.date_vs_TOD() x=df.columns y=df.index cmap = plt.get_cmap('plasma') im = ax.pcolormesh(x,y,df,cmap=cmap) ax.set_yticks(np.arange(0,3600*24,3600*3)) return im def sample(self): """ Look through all index and data values If any values have a 'sample' attribute then replace with value.sample() """ i_l=[] v_l=[] for i,v in self.series.iteritems(): if hasattr(i,'sample'): i_l.append(i.sample()) else: i_l.append(i) if hasattr(v,'sample'): v_l.append(v.sample()) else: v_l.append(v) s=pd.Series(data=v_l, index=i_l) return TimeSeries(series=s) class DiscreteTimeSeries(TimeSeries): """A discrete time series data object """ def __init__(self,series=None): TimeSeries.__init__(self,series) def __repr__(self): st='start_date={}'.format(self.timestamps[0]) st+=',len={}'.format(len(self.series)) return 'DiscreteTimeSeries({})'.format(st) def sample(self): dts=DiscreteTimeSeries() dts.series=TimeSeries.sample(self).series return dts class IntervalTimeSeries(TimeSeries): """A fixed interval time series class The DatetimeIndex in self.series is the start of the intervals Attributes: - method (str): the aggregation method for the interval, either 'mean' or 'sum' """ def __init__(self,series=None,interval=None,method=None): TimeSeries.__init__(self,series) self.interval=interval self.method=method def __repr__(self): st='start_date="{}"'.format(self.timestamps[0] if self.timestamps else None) st+=', interval="{}"'.format(self.interval) st+=', method="{}"'.format(self.method) st+=', len={}'.format(len(self.series)) return 'IntervalTimeSeries({})'.format(st) def lookup(self,ts): """Returns the data value at time ts. This will return the data value of an interval if: start_of_interval <= ts < end_of_interval Arguments: - ts (pd.Timestamp): """ v=TimeSeries.lookup(self,ts) if v: return v else: lower_ts,lower_v=self.nearest_timestamps(ts)[0:2] if lower_ts is None: return None upper_ts=lower_ts+self.interval if ts>=lower_ts and ts<upper_ts: return lower_v else: return None def json(self): "Returns a value for JSON serialization" d={ 'class':'IntervalTimeSeries', 'interval':self.interval, 'method':self.method } return d def plot(self,ax,name,units): ax.set_xlabel('Date') ax.set_ylabel('{} {} {} ({})'.format(self.interval, self.method, name, units)) x=self.series.index y=self.series.values ax.plot(x,y,linewidth=0.5) def hist(self,ax,bins=10,name=None,units=None): ax.set_xlabel( '{} bins ({}) (n={})'.format( name, units, bins) ) ax.set_ylabel('Probability density') y=self.series.values ax.hist(y,bins=bins,density=True) def chist(self,ax,bins=10,name=None,units=None): ax.set_xlabel( '{} bins ({}) (n={})'.format( name, units, bins) ) ax.set_ylabel('Cumulative probability density') y=self.series.values ax.hist(y, bins=bins, density=True, cumulative=True, histtype='step' ) class ContinuousTimeSeries(DiscreteTimeSeries): """A continuous interval time series class The values between data points are considered to be on a straight line between the two nearest data points The DatetimeIndex in self.series can should be in time order, but it can hold a repeat of the same timestamp to represent a step change. If there are two data points at the same timestamp, then the later values in the series is chosen. """ def __init__(self,series=None): TimeSeries.__init__(self,series) def __repr__(self): st='start_date={}'.format(self.timestamps[0]) st+=',len={}'.format(len(self.series)) return 'ContinuousTimeSeries({})'.format(st) def lookup(self,ts): """Returns the data value at time ts. Arguments: - ts (pd.Timestamp): """ v=TimeSeries.lookup(self,ts) if v: return v else: lower_ts,lower_v,upper_ts,upper_v=self.nearest_timestamps(ts) print(lower_ts,lower_v,upper_ts,upper_v) if lower_ts is None or lower_v is None or \ upper_ts is None or upper_v is None: return None else: interval_ts=upper_ts-lower_ts ts_proportion=(ts-lower_ts)/(interval_ts) interval_v=upper_v-lower_v v=lower_v+(interval_v)*(ts_proportion) return v def plot(self): "a simple plot of the data" self.series.plot(style='-o') class Variable(): """Represents a variable which holds time series data """ def __init__(self, name='', ts=None, units=''): self.name=name self.ts=ts self.units=units def __repr__(self): d={ 'name':self.name, 'ts':self.ts, 'units':self.units } return 'Variable({})'.format(d) def json(self): d={ 'name':self.name, 'units':self.units } if self.ts: d['ts']=self.ts.json() return d def plot(self,ax=None): if not ax: fig=plt.figure(figsize=(13,4)) ax=fig.add_axes([0, 0, 1, 1]) self.ts.plot(ax, self.name, self.units) def plot_colormap(self,ax=None): if not ax: fig=plt.figure(figsize=(13,4)) ax=fig.add_axes([0, 0, 1, 1]) im=self.ts.plot_colormap(ax) cbar=plt.colorbar(im, ax=ax) st='{} ({})'.format(self.name, self.units) cbar.ax.set_ylabel(st) def hist(self,ax=None,bins=None): if not ax: fig=plt.figure(figsize=(13,4)) ax=fig.add_axes([0, 0, 1, 1]) self.ts.hist(ax, bins, self.name, self.units) def chist(self,ax=None,bins=None): if not ax: fig=plt.figure(figsize=(13,4)) ax=fig.add_axes([0, 0, 1, 1]) self.ts.chist(ax, bins, self.name, self.units) from pprint import pprint if __name__=='__main__': from bim_graph import BimGraph bim=BimGraph() bim.read_pickle(r'../tests/timeseries/refit_ext_temp.pickle') climate=bim.Climate[0] sensor=[n for n in climate.Sensor if n.air_temperature][0] var=sensor.air_temperature print(var)
[ "pandas.Series", "numpy.arange", "matplotlib.pyplot.colorbar", "matplotlib.pyplot.figure", "numpy.isnan", "bim_graph.BimGraph", "matplotlib.pyplot.get_cmap" ]
[((10928, 10938), 'bim_graph.BimGraph', 'BimGraph', ([], {}), '()\n', (10936, 10938), False, 'from bim_graph import BimGraph\n'), ((977, 1023), 'pandas.Series', 'pd.Series', ([], {'index': '[dates, times]', 'data': 's.values'}), '(index=[dates, times], data=s.values)\n', (986, 1023), True, 'import pandas as pd\n'), ((3414, 3436), 'matplotlib.pyplot.get_cmap', 'plt.get_cmap', (['"""plasma"""'], {}), "('plasma')\n", (3426, 3436), True, 'import matplotlib.pyplot as plt\n'), ((4069, 4099), 'pandas.Series', 'pd.Series', ([], {'data': 'v_l', 'index': 'i_l'}), '(data=v_l, index=i_l)\n', (4078, 4099), True, 'import pandas as pd\n'), ((10167, 10190), 'matplotlib.pyplot.colorbar', 'plt.colorbar', (['im'], {'ax': 'ax'}), '(im, ax=ax)\n', (10179, 10190), True, 'import matplotlib.pyplot as plt\n'), ((446, 457), 'pandas.Series', 'pd.Series', ([], {}), '()\n', (455, 457), True, 'import pandas as pd\n'), ((2753, 2770), 'numpy.isnan', 'np.isnan', (['lower_v'], {}), '(lower_v)\n', (2761, 2770), True, 'import numpy as np\n'), ((2971, 2988), 'numpy.isnan', 'np.isnan', (['upper_v'], {}), '(upper_v)\n', (2979, 2988), True, 'import numpy as np\n'), ((3504, 3537), 'numpy.arange', 'np.arange', (['(0)', '(3600 * 24)', '(3600 * 3)'], {}), '(0, 3600 * 24, 3600 * 3)\n', (3513, 3537), True, 'import numpy as np\n'), ((9799, 9826), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(13, 4)'}), '(figsize=(13, 4))\n', (9809, 9826), True, 'import matplotlib.pyplot as plt\n'), ((10048, 10075), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(13, 4)'}), '(figsize=(13, 4))\n', (10058, 10075), True, 'import matplotlib.pyplot as plt\n'), ((10348, 10375), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(13, 4)'}), '(figsize=(13, 4))\n', (10358, 10375), True, 'import matplotlib.pyplot as plt\n'), ((10626, 10653), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(13, 4)'}), '(figsize=(13, 4))\n', (10636, 10653), True, 'import matplotlib.pyplot as plt\n'), ((1704, 1716), 'numpy.isnan', 'np.isnan', (['v1'], {}), '(v1)\n', (1712, 1716), True, 'import numpy as np\n')]
# ______________________________________________________________________________ # ****************************************************************************** # # The simplest robot task: Just go and reach a point # # ______________________________________________________________________________ # ****************************************************************************** #----------------------------------------------------------------------------- #SET THE PATH TO THE URDF AND MESHES #Define robotName, urdfpath and initialConfig #Make sure talos_description is in the ROS_PACKAGE_PATH #from rospkg import RosPack #rospack = RosPack() #urdfPath = rospack.get_path('talos_description')+"/robots/talos_full_collision.urdf" #urdfDir = [rospack.get_path('talos_description')+"/../"] URDFPATH = "~/git/pyrene/talos-data"+"/robots/talos_reduced.urdf" URDFDIR = ["~/git/pyrene/talos-data"+"/../"] MOTION_SEQUENCE = "~/git/pyrene/pyrene-motions/grabHandrail15/stairs_15cm_handrail_grab_actuated" DISPLAY = True dt = 1e-3 robotName = 'TALOS' OperationalPointsMap = {'left-wrist' : 'arm_left_7_joint', 'right-wrist' : 'arm_right_7_joint', 'left-ankle' : 'leg_left_6_joint', 'right-ankle' : 'leg_right_6_joint', 'gaze' : 'head_2_joint', 'waist' : 'root_joint', 'chest' : 'torso_2_joint'} halfSitting = (0.0, 0.0, 1.018213, 0.00 , 0.0, 0.0, #Free flyer 0.0, 0.0, -0.411354, 0.859395, -0.448041, -0.001708, #Left Leg 0.0, 0.0, -0.411354, 0.859395, -0.448041, -0.001708, #Right Leg 0.0 , 0.006761, #Chest 0.25847 , 0.173046, -0.0002, -0.525366, 0.0, -0.0, 0.1, 0.1, #Left Arm -0.25847 , -0.173046, 0.0002 , -0.525366, 0.0, 0.0, 0.1, 0.1, #Right Arm 0., 0. #Head ) #----------------------------------------------------------------------------- #---- ROBOT SPECIFICATIONS---------------------------------------------------- #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- #---- DYN -------------------------------------------------------------------- #----------------------------------------------------------------------------- from pinocchio.robot_wrapper import RobotWrapper import pinocchio as se3 from dynamic_graph.sot.dynamics_pinocchio import fromSotToPinocchio pinocchioRobot = RobotWrapper(URDFPATH, URDFDIR, se3.JointModelFreeFlyer()) pinocchioRobot.initDisplay(loadModel=DISPLAY) if DISPLAY: pinocchioRobot.display(fromSotToPinocchio(halfSitting)) from dynamic_graph.sot.dynamics_pinocchio.humanoid_robot import HumanoidRobot robot = HumanoidRobot(robotName, pinocchioRobot.model, pinocchioRobot.data, halfSitting, OperationalPointsMap) # ------------------------------------------------------------------------------ # ---- Kinematic Stack of Tasks (SoT) ----------------------------------------- # ------------------------------------------------------------------------------ from dynamic_graph import plug from dynamic_graph.sot.core import SOT sot = SOT('sot') sot.setSize(robot.dynamic.getDimension()) plug(sot.control,robot.device.control) # DEFINE POSTURE TASK from dynamic_graph.sot.core import Task, FeatureGeneric, GainAdaptive from dynamic_graph.sot.core.meta_tasks import setGain from dynamic_graph.sot.core.matrix_util import matrixToTuple from numpy import identity, hstack, zeros task_name = "posture_task" taskPosture = Task(task_name) taskPosture.dyn = robot.dynamic taskPosture.feature = FeatureGeneric('feature_'+task_name) taskPosture.featureDes = FeatureGeneric('feature_des_'+task_name) taskPosture.gain = GainAdaptive("gain_"+task_name) robotDim = robot.dynamic.getDimension() first_6 = zeros((32,6)) other_dof = identity(robotDim-6) jacobian_posture = hstack([first_6, other_dof]) taskPosture.feature.jacobianIN.value = matrixToTuple( jacobian_posture ) taskPosture.feature.setReference(taskPosture.featureDes.name) taskPosture.add(taskPosture.feature.name) #DEFINE SEQUENCE PLAYER from dynamic_graph.sot.tools import SimpleSeqPlay seqplay = SimpleSeqPlay("seq_play") seqplay.load(MOTION_SEQUENCE) #MAKE CONNECTIONS from dynamic_graph.sot.core import Selec_of_vector plug(seqplay.posture, taskPosture.featureDes.errorIN) getPostureValue = Selec_of_vector("current_posture") getPostureValue.selec(6,robotDim) plug(robot.dynamic.position, getPostureValue.sin) plug(getPostureValue.sout, taskPosture.feature.errorIN) plug(getPostureValue.sout, seqplay.currentPosture) setGain(taskPosture.gain,(4.9,0.9,0.01,0.9)) plug(taskPosture.gain.gain, taskPosture.controlGain) plug(taskPosture.error, taskPosture.gain.error) #START SEQUENCE PLAYER seqplay.start() taskPosture.featureDes.errorIN.recompute(0) #PUSH TO SOLVER sot.push(taskPosture.name) #------------------------------------------------------------------------------- #----- MAIN LOOP --------------------------------------------------------------- #------------------------------------------------------------------------------- def runner(n): for i in xrange(n): robot.device.increment(dt) pinocchioRobot.display(fromSotToPinocchio(robot.device.state.value)) runner(3000)
[ "dynamic_graph.plug", "numpy.identity", "dynamic_graph.sot.core.GainAdaptive", "dynamic_graph.sot.dynamics_pinocchio.fromSotToPinocchio", "dynamic_graph.sot.core.Task", "numpy.hstack", "dynamic_graph.sot.core.meta_tasks.setGain", "dynamic_graph.sot.core.FeatureGeneric", "pinocchio.JointModelFreeFlye...
[((3002, 3108), 'dynamic_graph.sot.dynamics_pinocchio.humanoid_robot.HumanoidRobot', 'HumanoidRobot', (['robotName', 'pinocchioRobot.model', 'pinocchioRobot.data', 'halfSitting', 'OperationalPointsMap'], {}), '(robotName, pinocchioRobot.model, pinocchioRobot.data,\n halfSitting, OperationalPointsMap)\n', (3015, 3108), False, 'from dynamic_graph.sot.dynamics_pinocchio.humanoid_robot import HumanoidRobot\n'), ((3448, 3458), 'dynamic_graph.sot.core.SOT', 'SOT', (['"""sot"""'], {}), "('sot')\n", (3451, 3458), False, 'from dynamic_graph.sot.core import SOT\n'), ((3501, 3540), 'dynamic_graph.plug', 'plug', (['sot.control', 'robot.device.control'], {}), '(sot.control, robot.device.control)\n', (3505, 3540), False, 'from dynamic_graph import plug\n'), ((3836, 3851), 'dynamic_graph.sot.core.Task', 'Task', (['task_name'], {}), '(task_name)\n', (3840, 3851), False, 'from dynamic_graph.sot.core import Task, FeatureGeneric, GainAdaptive\n'), ((3906, 3944), 'dynamic_graph.sot.core.FeatureGeneric', 'FeatureGeneric', (["('feature_' + task_name)"], {}), "('feature_' + task_name)\n", (3920, 3944), False, 'from dynamic_graph.sot.core import Task, FeatureGeneric, GainAdaptive\n'), ((3968, 4010), 'dynamic_graph.sot.core.FeatureGeneric', 'FeatureGeneric', (["('feature_des_' + task_name)"], {}), "('feature_des_' + task_name)\n", (3982, 4010), False, 'from dynamic_graph.sot.core import Task, FeatureGeneric, GainAdaptive\n'), ((4028, 4061), 'dynamic_graph.sot.core.GainAdaptive', 'GainAdaptive', (["('gain_' + task_name)"], {}), "('gain_' + task_name)\n", (4040, 4061), False, 'from dynamic_graph.sot.core import Task, FeatureGeneric, GainAdaptive\n'), ((4110, 4124), 'numpy.zeros', 'zeros', (['(32, 6)'], {}), '((32, 6))\n', (4115, 4124), False, 'from numpy import identity, hstack, zeros\n'), ((4136, 4158), 'numpy.identity', 'identity', (['(robotDim - 6)'], {}), '(robotDim - 6)\n', (4144, 4158), False, 'from numpy import identity, hstack, zeros\n'), ((4176, 4204), 'numpy.hstack', 'hstack', (['[first_6, other_dof]'], {}), '([first_6, other_dof])\n', (4182, 4204), False, 'from numpy import identity, hstack, zeros\n'), ((4244, 4275), 'dynamic_graph.sot.core.matrix_util.matrixToTuple', 'matrixToTuple', (['jacobian_posture'], {}), '(jacobian_posture)\n', (4257, 4275), False, 'from dynamic_graph.sot.core.matrix_util import matrixToTuple\n'), ((4468, 4493), 'dynamic_graph.sot.tools.SimpleSeqPlay', 'SimpleSeqPlay', (['"""seq_play"""'], {}), "('seq_play')\n", (4481, 4493), False, 'from dynamic_graph.sot.tools import SimpleSeqPlay\n'), ((4597, 4650), 'dynamic_graph.plug', 'plug', (['seqplay.posture', 'taskPosture.featureDes.errorIN'], {}), '(seqplay.posture, taskPosture.featureDes.errorIN)\n', (4601, 4650), False, 'from dynamic_graph import plug\n'), ((4669, 4703), 'dynamic_graph.sot.core.Selec_of_vector', 'Selec_of_vector', (['"""current_posture"""'], {}), "('current_posture')\n", (4684, 4703), False, 'from dynamic_graph.sot.core import Selec_of_vector\n'), ((4738, 4787), 'dynamic_graph.plug', 'plug', (['robot.dynamic.position', 'getPostureValue.sin'], {}), '(robot.dynamic.position, getPostureValue.sin)\n', (4742, 4787), False, 'from dynamic_graph import plug\n'), ((4788, 4843), 'dynamic_graph.plug', 'plug', (['getPostureValue.sout', 'taskPosture.feature.errorIN'], {}), '(getPostureValue.sout, taskPosture.feature.errorIN)\n', (4792, 4843), False, 'from dynamic_graph import plug\n'), ((4844, 4894), 'dynamic_graph.plug', 'plug', (['getPostureValue.sout', 'seqplay.currentPosture'], {}), '(getPostureValue.sout, seqplay.currentPosture)\n', (4848, 4894), False, 'from dynamic_graph import plug\n'), ((4895, 4943), 'dynamic_graph.sot.core.meta_tasks.setGain', 'setGain', (['taskPosture.gain', '(4.9, 0.9, 0.01, 0.9)'], {}), '(taskPosture.gain, (4.9, 0.9, 0.01, 0.9))\n', (4902, 4943), False, 'from dynamic_graph.sot.core.meta_tasks import setGain\n'), ((4940, 4992), 'dynamic_graph.plug', 'plug', (['taskPosture.gain.gain', 'taskPosture.controlGain'], {}), '(taskPosture.gain.gain, taskPosture.controlGain)\n', (4944, 4992), False, 'from dynamic_graph import plug\n'), ((4993, 5040), 'dynamic_graph.plug', 'plug', (['taskPosture.error', 'taskPosture.gain.error'], {}), '(taskPosture.error, taskPosture.gain.error)\n', (4997, 5040), False, 'from dynamic_graph import plug\n'), ((2769, 2794), 'pinocchio.JointModelFreeFlyer', 'se3.JointModelFreeFlyer', ([], {}), '()\n', (2792, 2794), True, 'import pinocchio as se3\n'), ((2881, 2912), 'dynamic_graph.sot.dynamics_pinocchio.fromSotToPinocchio', 'fromSotToPinocchio', (['halfSitting'], {}), '(halfSitting)\n', (2899, 2912), False, 'from dynamic_graph.sot.dynamics_pinocchio import fromSotToPinocchio\n'), ((5519, 5563), 'dynamic_graph.sot.dynamics_pinocchio.fromSotToPinocchio', 'fromSotToPinocchio', (['robot.device.state.value'], {}), '(robot.device.state.value)\n', (5537, 5563), False, 'from dynamic_graph.sot.dynamics_pinocchio import fromSotToPinocchio\n')]
# generated bbox ground truth from pixel-wise segmentation # it currently only generate one bbox from __future__ import print_function import numpy as np import h5py import os import pdb mask_path = 'data/socket' #f = h5py.File(os.path.join(mask_path, "seg_mask.h5"), 'r') #bbox_path = 'data/socket/seg_bbox' #f = h5py.File(os.path.join(mask_path, "seg_band_mask.h5"), 'r') f = h5py.File(os.path.join(mask_path, "train_socket_label_u.h5"), 'r') testf = h5py.File(os.path.join(mask_path, "test_socket_label_u.h5"), 'r') #bbox_path = 'data/socket/seg_band_bbox' bbox_path = 'data/socket/cropped_seg_band_bbox' if not os.path.exists(bbox_path): os.mkdir(bbox_path) # dim: shape (391, 192, 256), height, width, slices for k in f.keys(): #pdb.set_trace() data = np.array(f[k]) # convert to numpy k = k.rsplit('_',1)[0] # strip the '_mask' from the vol name with open( os.path.join(bbox_path, k)+'_bbox.txt', 'w') as bbox_file: # iterate through each slice for idx in range(data.shape[2]): mask = data[:, :, idx] # get the mask i,j = np.where(mask) # find positive mask if not i.size: # no positive mask print("{}_{},{}".format(k, idx, 0), file=bbox_file) else: h_min,w_min = np.min(zip(i,j), axis=0) h_max,w_max = np.max(zip(i,j), axis=0) print("{}_{},{},{},{},{},{}".format(k, idx, 1, w_min, h_min, w_max, h_max), file=bbox_file) for k in testf.keys(): data = np.array(testf[k]) # convert to numpy k = k.rsplit('_',1)[0] # strip the '_mask' from the vol name with open( os.path.join(bbox_path, k)+'_bbox.txt', 'w') as bbox_file: # iterate through each slice for idx in range(data.shape[2]): mask = data[:, :, idx] # get the mask i,j = np.where(mask) # find positive mask if not i.size: # no positive mask print("{}_{},{}".format(k, idx, 0), file=bbox_file) else: h_min,w_min = np.min(zip(i,j), axis=0) h_max,w_max = np.max(zip(i,j), axis=0) print("{}_{},{},{},{},{},{}".format(k, idx, 1, w_min, h_min, w_max, h_max), file=bbox_file) f.close() testf.close()
[ "os.path.exists", "numpy.where", "os.path.join", "numpy.array", "os.mkdir" ]
[((389, 439), 'os.path.join', 'os.path.join', (['mask_path', '"""train_socket_label_u.h5"""'], {}), "(mask_path, 'train_socket_label_u.h5')\n", (401, 439), False, 'import os\n'), ((464, 513), 'os.path.join', 'os.path.join', (['mask_path', '"""test_socket_label_u.h5"""'], {}), "(mask_path, 'test_socket_label_u.h5')\n", (476, 513), False, 'import os\n'), ((616, 641), 'os.path.exists', 'os.path.exists', (['bbox_path'], {}), '(bbox_path)\n', (630, 641), False, 'import os\n'), ((647, 666), 'os.mkdir', 'os.mkdir', (['bbox_path'], {}), '(bbox_path)\n', (655, 666), False, 'import os\n'), ((772, 786), 'numpy.array', 'np.array', (['f[k]'], {}), '(f[k])\n', (780, 786), True, 'import numpy as np\n'), ((1532, 1550), 'numpy.array', 'np.array', (['testf[k]'], {}), '(testf[k])\n', (1540, 1550), True, 'import numpy as np\n'), ((1091, 1105), 'numpy.where', 'np.where', (['mask'], {}), '(mask)\n', (1099, 1105), True, 'import numpy as np\n'), ((1855, 1869), 'numpy.where', 'np.where', (['mask'], {}), '(mask)\n', (1863, 1869), True, 'import numpy as np\n'), ((886, 912), 'os.path.join', 'os.path.join', (['bbox_path', 'k'], {}), '(bbox_path, k)\n', (898, 912), False, 'import os\n'), ((1650, 1676), 'os.path.join', 'os.path.join', (['bbox_path', 'k'], {}), '(bbox_path, k)\n', (1662, 1676), False, 'import os\n')]
# Copyright (C) 2015-2019 <NAME> # SPDX-License-Identifier: Apache-2.0 import dolfin import numpy from matplotlib import pyplot from ocellaris.utils import gather_lines_on_root, timeit, ocellaris_error from . import Probe, register_probe INCLUDE_BOUNDARY = False WRITE_INTERVAL = 1 SHOW_INTERVAL = 0 @register_probe('IsoSurface') class IsoSurface(Probe): def __init__(self, simulation, probe_input): self.simulation = simulation self.cells_with_surface = None inp = probe_input assert ( self.simulation.ndim == 2 ), 'IsoSurface only implemented in 2D (contour line)' assert not self.simulation.mesh_morpher.active, 'IsoSurface does not support ALE yet' # Read input self.name = inp.get_value('name', required_type='string') self.field_name = inp.get_value('field', required_type='string') self.value = inp.get_value('value', required_type='float') self.custom_hook_point = inp.get_value( 'custom_hook', None, required_type='string' ) self.field = simulation.data[self.field_name] self.include_boundary = inp.get_value( 'include_boundary', INCLUDE_BOUNDARY, 'bool' ) # Should we write the data to a file prefix = simulation.input.get_value('output/prefix', None, 'string') file_name = inp.get_value('file_name', None, 'string') self.write_file = file_name is not None if self.write_file: if prefix is not None: self.file_name = prefix + file_name else: self.file_name = file_name self.write_interval = inp.get_value('write_interval', WRITE_INTERVAL, 'int') # Should we pop up a matplotlib window when running? self.show_interval = inp.get_value('show_interval', SHOW_INTERVAL, 'int') self.show = self.show_interval != 0 and simulation.rank == 0 self.xlim = inp.get_value('xlim', (None, None), 'list(float)') self.ylim = inp.get_value('ylim', (None, None), 'list(float)') if not len(self.xlim) == 2: ocellaris_error( 'Plot xlim must be two numbers', 'IsoSurface probe "%s" contains invalid xlim specification' % self.name, ) if not len(self.ylim) == 2: ocellaris_error( 'Plot ylim must be two numbers', 'IsoSurface probe "%s" contains invalid ylim specification' % self.name, ) if self.write_file and simulation.rank == 0: self.output_file = open(self.file_name, 'wt') self.output_file.write( '# Ocellaris iso surface of the %s field\n' % self.field_name ) self.output_file.write('# value = %15.5e\n' % self.value) self.output_file.write('# dim = %d\n' % self.simulation.ndim) if self.show and simulation.rank == 0: pyplot.ion() self.fig = pyplot.figure() self.ax = self.fig.add_subplot(111) self.ax.set_title('Iso surface %s' % self.name) # The class that finds the contour line if self.field_name == 'height_function': self.locator = HeightFunctionLocator(simulation) else: self.locator = IsoSurfaceLocator(simulation, self.field.function_space()) if self.custom_hook_point is not None: simulation.hooks.add_custom_hook( self.custom_hook_point, self.run, 'Probe "%s"' % self.name ) else: self.end_of_timestep = self.run # Flush output file self.simulation.hooks.add_custom_hook('flush', self.flush, 'Flush log file') def run(self, force_active=False): """ Find and output the line probe """ it = self.simulation.timestep # Should we update the plot? update_plot = False if self.show and (it == 1 or it % self.show_interval == 0): update_plot = True # Should we update the file? update_file = False if self.write_file and (it == 1 or it % self.write_interval == 0): update_file = True # Do not do any postprocessing for non-requested time steps if not (update_file or update_plot or force_active): return # Get the iso surfaces surfaces, cells = self.locator.get_iso_surface(self.field, self.value) self.cells_with_surface = cells # Get the boundary surfaces for cells with values above the given value if self.include_boundary: surfaces += get_boundary_surface(self.simulation, self.field, self.value) # Create lines (this assumes 2D and throws away the z-component) lines = [] for surface in surfaces: x = numpy.array([pos[0] for pos in surface], float) y = numpy.array([pos[1] for pos in surface], float) lines.append((x, y)) # Communicate lines to the root process in case we are running in parallel gather_lines_on_root(lines) if update_file and self.simulation.rank == 0: self.output_file.write( 'Time %10.5f nsurf %d\n' % (self.simulation.time, len(lines)) ) for x, y in lines: self.output_file.write(' '.join('%10.5f' % v for v in x) + '\n') self.output_file.write(' '.join('%10.5f' % v for v in y) + '\n') self.output_file.write(' '.join('%10.5f' % 0 for v in x) + '\n') if update_plot and self.simulation.rank == 0: with dolfin.Timer('Ocellaris plot iso surface'): self.ax.clear() for x, y in lines: self.ax.plot(x, y) self.ax.set_xlabel('x') self.ax.set_ylabel('y') self.ax.relim() self.ax.autoscale_view() if self.xlim != (None, None): self.ax.set_xlim(*self.xlim) if self.ylim != (None, None): self.ax.set_ylim(*self.ylim) self.fig.canvas.draw() # self.fig.canvas.flush_events() # Return value only used in unit testing return lines def flush(self): if ( self.write_file and self.simulation.rank == 0 and not self.output_file.closed ): self.output_file.flush() def end_of_simulation(self): """ The simulation is done. Close the output file """ if self.write_file and self.simulation.rank == 0: self.output_file.close() class IsoSurfaceLocatorCache: pass class IsoSurfaceLocator: def __init__(self, simulation, V): self.simulation = simulation self.degree = V.ufl_element().degree() self.cache = IsoSurfaceLocatorCache() if self.degree in (1, 2): return prepare_DG1_DG2(self.cache, simulation, V) @timeit def get_iso_surface(self, field, value): """ Find the iso-surfaces (contour lines) of the given field with the given scalar value """ sim = self.simulation if self.degree == 0: return get_iso_surfaces_picewice_constants(sim, field, value) elif self.degree in (1, 2): return get_iso_surface_DG1_DG2(sim, self.cache, field, value) else: return get_iso_surfaces(sim, field, value) class HeightFunctionLocator: def __init__(self, simulation): self.simulation = simulation @timeit def get_iso_surface(self, field, value): """ Find the iso-surfaces (contour lines) of the given field with the given scalar value """ sim = self.simulation xpos = sim.data['height_function_x'] ypos = ( sim.data['height_function'].vector().get_local() ) # only needs the first elements line = [(x, h) for x, h in zip(xpos, ypos)] return [line], None def get_iso_surfaces(simulation, field, value): """ Slow fallback version that uses vertex values only """ assert simulation.ndim == 2 mesh = simulation.data['mesh'] all_values = field.compute_vertex_values() # We will collect the cells containing the iso surface cells_with_surface = numpy.zeros(mesh.num_cells(), bool) connectivity_FC = simulation.data['connectivity_FC'] # Find the crossing points where the contour crosses a facet crossing_points = {} for facet in dolfin.facets(mesh): fid = facet.index() # Get connected vertices and the field values there vertex_coords = [] vertex_values = [] for vertex in dolfin.vertices(facet): pt = vertex.point() vertex_coords.append((pt.x(), pt.y(), pt.z())) vertex_values.append(all_values[vertex.index()]) assert len(vertex_coords) == 2 # Check for iso surface crossing b1, b2 = vertex_values[0] < value, vertex_values[1] < value if (b1 and b2) or not (b1 or b2): # Facet not crossed by contour continue # Find the location where the contour line crosses the facet v1, v2 = vertex_values fac = (v1 - value) / (v1 - v2) x = (1 - fac) * vertex_coords[0][0] + fac * vertex_coords[1][0] y = (1 - fac) * vertex_coords[0][1] + fac * vertex_coords[1][1] z = (1 - fac) * vertex_coords[0][2] + fac * vertex_coords[1][2] crossing_points[fid] = (x, y, z) # Find the cells connected to this facet for cid in connectivity_FC(fid): cells_with_surface[cid] = True # Get facet-facet connectivity via cells conFC = simulation.data['connectivity_FC'] conCF = simulation.data['connectivity_CF'] # Find facet to facet connections connections = {} for facet_id in crossing_points: connections[facet_id] = [] for cell_id in conFC(facet_id): for facet_neighbour_id in conCF(cell_id): if ( facet_neighbour_id != facet_id and facet_neighbour_id in crossing_points ): connections[facet_id].append(facet_neighbour_id) # Make continous contour lines # Find end points of contour lines and start with these end_points = [ facet_id for facet_id, neighbours in connections.items() if len(neighbours) == 1 ] contours_from_endpoints = contour_lines_from_endpoints( end_points, crossing_points, connections ) # Include crossing points without neighbours or joined circles without end points other_points = crossing_points.keys() contours_from_singles_and_loops = contour_lines_from_endpoints( other_points, crossing_points, connections ) assert len(crossing_points) == 0 return contours_from_endpoints + contours_from_singles_and_loops, cells_with_surface def get_iso_surfaces_picewice_constants(simulation, field, value): """ Find the iso-surfaces (contour lines) of the given field with the given scalar value The field is assumed to be piecewice constant (DG0) """ assert simulation.ndim == 2 mesh = simulation.data['mesh'] all_values = field.vector().get_local() dofmap = field.function_space().dofmap() # Mesh connectivities conFC = simulation.data['connectivity_FC'] conVF = simulation.data['connectivity_VF'] conFV = simulation.data['connectivity_FV'] # We will collect the cells containing the iso surface cells_with_surface = numpy.zeros(mesh.num_cells(), bool) # We define acronym LCCM: line connecting cell midpoints # - We restrinct ourselves to LCCMs that cross only ONE facet # - We number LLCMs by the index of the crossed facet # Find the crossing points where the contour crosses a LCCM vertex_coords = numpy.zeros((2, 3), float) vertex_values = numpy.zeros(2, float) crossing_points = {} for facet in dolfin.facets(mesh): fid = facet.index() cell_ids = conFC(fid) if len(cell_ids) != 2: continue has_ghost_cell = False for i, cell_id in enumerate(cell_ids): cell = dolfin.Cell(mesh, cell_id) if cell.is_ghost(): has_ghost_cell = True break # LCCM endpoint coordinates pt = cell.midpoint() vertex_coords[i, 0] = pt.x() vertex_coords[i, 1] = pt.y() vertex_coords[i, 2] = pt.z() # LCCM endpoint values dofs = dofmap.cell_dofs(cell_id) assert len(dofs) == 1 vertex_values[i] = all_values[dofs[0]] if has_ghost_cell: continue b1, b2 = vertex_values[0] < value, vertex_values[1] < value if (b1 and b2) or not (b1 or b2): # LCCM not crossed by contour continue # Find the location where the contour line crosses the LCCM v1, v2 = vertex_values fac = (v1 - value) / (v1 - v2) crossing_points[fid] = tuple( (1 - fac) * vertex_coords[0] + fac * vertex_coords[1] ) # Find the cell containing the contour line surf_cid = cell_ids[0] if fac <= 0.5 else cell_ids[1] cells_with_surface[surf_cid] = True # Find facet to facet connections connections = {} for facet_id in crossing_points: connections[facet_id] = [] for vertex_id in conFV(facet_id): for facet_neighbour_id in conVF(vertex_id): if ( facet_neighbour_id != facet_id and facet_neighbour_id in crossing_points ): connections[facet_id].append(facet_neighbour_id) # Make continous contour lines # Find end points of contour lines and start with these end_points = [ facet_id for facet_id, neighbours in connections.items() if len(neighbours) == 1 ] contours_from_endpoints = contour_lines_from_endpoints( end_points, crossing_points, connections ) # Include crossing points without neighbours or joined circles without end points other_points = crossing_points.keys() contours_from_singles_and_loops = contour_lines_from_endpoints( other_points, crossing_points, connections ) assert len(crossing_points) == 0 return contours_from_endpoints + contours_from_singles_and_loops, cells_with_surface def prepare_DG1_DG2(cache, simulation, V): """ Prepare to find iso surfaces of the given field. Caches geometry and topology data of the mesh and must be rerun if this data changes! This is rather slow, but it runs only once and the results are cached """ mesh = simulation.data['mesh'] gdim = mesh.geometry().dim() degree = V.ufl_element().degree() dofmap = V.dofmap() dofs_x = V.tabulate_dof_coordinates().reshape((-1, gdim)) N = dofs_x.shape[0] assert degree in (1, 2) assert gdim == 2 # Map location to dof x_to_dof = {} for dof, pos in enumerate(dofs_x): x_to_dof.setdefault(tuple(pos), []).append(dof) # Create mapping from dof to other dofs at the same coordinate same_loc = [[] for _ in range(N)] for dofs in x_to_dof.values(): for d0 in dofs: for d1 in dofs: if d0 != d1: same_loc[d0].append(d1) # Find the immediate neighbours for all dofs where # immediate neighbour is defined as # either 1) sits in the same location (but different cell) # or 2) sits next to each other on the same facet immediate_neighbours = [None] * N connected_cells = [None] * N for cell in dolfin.cells(mesh): cid = cell.index() dofs = dofmap.cell_dofs(cid) if degree == 1: for dof in dofs: # Immediate neighbours nbs = list(same_loc[dof]) immediate_neighbours[dof] = nbs nbs.extend(d for d in dofs if dof != d) # The first connected cell is the cell owning the dof connected_cells[dof] = [cid] else: for i, dof in enumerate(dofs): # Immediate neighbours nbs = list(same_loc[dof]) immediate_neighbours[dof] = nbs if i == 0: nbs.extend((dofs[4], dofs[5])) elif i == 1: nbs.extend((dofs[3], dofs[5])) elif i == 2: nbs.extend((dofs[3], dofs[4])) elif i == 3: nbs.extend((dofs[1], dofs[2])) elif i == 4: nbs.extend((dofs[0], dofs[2])) elif i == 5: nbs.extend((dofs[0], dofs[1])) # The first connected cell is the cell owning the dof connected_cells[dof] = [cid] # Extend list of connected cells for dof, pos in enumerate(dofs_x): p = tuple(pos) for nb in x_to_dof[p]: if nb != dof: # Get the first connected cell (the cell containing the dof) nb_cid = connected_cells[nb][0] connected_cells[dof].append(nb_cid) # Find the extended neighbour dofs of all dofs. An extended neighbbour is # a dof that can be the next point on a contour line. The line between a # dof and its extended neighbour can hence not cut through a facet, but it # can be parallell/incident with a facet extended_neighbours = [None] * N for dof, cell_ids in enumerate(connected_cells): extended_neighbours[dof] = enbs = [] for cid in cell_ids: # Add dofs in conneced cell as neighbours for d in dofmap.cell_dofs(cid): if d != dof and d not in enbs: enbs.append(d) # Add other dofs at the same location for d2 in same_loc[d]: if d2 != dof and d2 not in enbs: enbs.append(d2) # Sort extended neighbours by distance for dof in range(N): enbs = extended_neighbours[dof] p = dofs_x[dof] tmp = [] for n in enbs: pn = dofs_x[n] d = p - pn tmp.append((d.dot(d), n)) tmp.sort(reverse=True) extended_neighbours[dof] = [n for _dist, n in tmp] cache.N = N cache.degree = degree cache.dofs_x = dofs_x cache.x_to_dof = x_to_dof cache.immediate_neighbours = immediate_neighbours cache.extended_neighbours = extended_neighbours cache.connected_cells = connected_cells def get_iso_surface_DG1_DG2(simulation, cache, field, value): """ Find the iso-surfaces (contour lines) of the given field with the given scalar value. The field is assumed to be linear or quadratic We assume that the field is discontinuous at internal facets. This means that the iso surface could be incident with a facet since the scalar field is dual valued there """ all_values = field.vector().get_local() assert simulation.ndim == 2 assert len(all_values) == cache.N # We will collect the cells containing the iso surface mesh = simulation.data['mesh'] cells_with_surface = numpy.zeros(mesh.num_cells(), bool) # Find where the iso surface crosses between two dofs # Could be right at the same location, in the jump # between two cells crossing_points = {} for dof, nbs in enumerate(cache.immediate_neighbours): p0 = tuple(cache.dofs_x[dof]) v0 = all_values[dof] for n in nbs: v1 = all_values[n] b0 = v0 <= value and v1 >= value b1 = v0 >= value and v1 <= value if not (b0 or b1): continue p1 = tuple(cache.dofs_x[n]) # Check for surface at jump if p0 == p1: if dof == cache.x_to_dof[p0][0]: crossing_points[dof] = p0 # Mark cell as surface cell cid = cache.connected_cells[dof][0] cells_with_surface[cid] = True # Check for surface crossing a facet elif b0: fac = (v0 - value) / (v0 - v1) cp = ((1 - fac) * p0[0] + fac * p1[0], (1 - fac) * p0[1] + fac * p1[1]) # Select the dof with the fewest connections to avoid # the iso surface line crossing a facet (the dof with # the most extended neighbours will be the corner dof) num_enbs0 = len(cache.extended_neighbours[dof]) num_enbs1 = len(cache.extended_neighbours[n]) if num_enbs0 < num_enbs1: crossing_points[dof] = cp else: crossing_points[n] = cp # Mark cell as surface cell cid = cache.connected_cells[dof][0] cells_with_surface[cid] = True # Get connections between crossing points using the extended # dof neighbourhood to look for possible connections connections = {} for dof, pos in crossing_points.items(): tmp = [] for n in cache.extended_neighbours[dof]: if n not in crossing_points: continue p2 = crossing_points[n] d = (pos[0] - p2[0]) ** 2 + (pos[1] - p2[1]) ** 2 tmp.append((d, n)) tmp.sort(reverse=True) connections[dof] = [n for _, n in tmp] # Make continous contour lines possible_starting_points = crossing_points.keys() contours = contour_lines_from_endpoints( possible_starting_points, crossing_points, connections, min_length=3 * cache.degree, backtrack_from_end=True, extend_endpoints=False, ) return contours, cells_with_surface @timeit def get_boundary_surface(simulation, field, value): """ Find the boundary surface consisting of facets with scalar field values greater than the given iso value """ assert simulation.ndim == 2 mesh = simulation.data['mesh'] all_values = field.compute_vertex_values() connectivity_FC = simulation.data['connectivity_FC'] # Find the crossing points where the contour crosses a facet connections = {} for facet in dolfin.facets(mesh): fid = facet.index() # Skip facets that are not on the boundary connected_cells = connectivity_FC(fid) if not len(connected_cells) == 1: continue # Get connected vertices and the field values there vertex_coords = [] vertex_values = [] for vertex in dolfin.vertices(facet): pt = vertex.point() vertex_coords.append((pt.x(), pt.y(), pt.z())) vertex_values.append(all_values[vertex.index()]) assert len(vertex_coords) == 2 # Check if all values are above the iso value if vertex_values[0] < value or vertex_values[1] < value: continue connections.setdefault(vertex_coords[0], []).append(vertex_coords[1]) connections.setdefault(vertex_coords[1], []).append(vertex_coords[0]) # Map coord to coord, just to be able to use the generic functionality in # contour_lines_from_endpoints which works on facet_id <-> coord mappings available_coords = {vc: vc for vc in connections} # Make continous contour lines # Find end points of contour lines and start with these end_points = [vc for vc, neighbours in connections.items() if len(neighbours) < 2] contours_from_endpoints = contour_lines_from_endpoints( end_points, available_coords, connections ) # Include crossing points without neighbours or joined circles without end points other_points = available_coords.keys() contours_from_singles_and_loops = contour_lines_from_endpoints( other_points, available_coords, connections ) assert len(available_coords) == 0 return contours_from_endpoints + contours_from_singles_and_loops def contour_lines_from_endpoints( endpoints, crossing_points, connections, min_length=3, backtrack_from_end=False, extend_endpoints=True, ): """ Follow contour lines and create contours - endpoints: an iterable of crossing point IDs (could be facet ids) - crossing_points: a mapping from crossing point ID to position coordinates - connections: a mapping from ID to IDs """ contours = [] endpoint_ids = list(endpoints) while endpoint_ids: end_id = endpoint_ids.pop() if not end_id in crossing_points: # This has been taken by the other end continue # Make a new contour line contour = [crossing_points.pop(end_id)] # Loop over neighbours to the end of the contour queue = list(connections[end_id]) prev = end_id has_backtracked = False while queue: nb_id = queue.pop() # Is this neighbour a possible next part of the contour line? if nb_id in crossing_points: # Found connection to use as next in contour cpoint = crossing_points.pop(nb_id) if cpoint != contour[-1]: contour.append(cpoint) # Unused connections may be new end points (more than two connections) if extend_endpoints: for candidate in queue: if candidate in crossing_points: endpoint_ids.append(candidate) queue = list(connections[nb_id]) prev = nb_id # Is this the end of a loop? if ( nb_id == end_id and prev in connections[end_id] and len(contour) > min_length - 1 and not has_backtracked ): contour.append(contour[0]) break # Backtrack from endpoint in case it was not a true endpoint if backtrack_from_end and not queue and not has_backtracked: contour = contour[::-1] queue = list(connections[end_id]) has_backtracked = True contours.append(contour) return contours
[ "ocellaris.utils.ocellaris_error", "dolfin.Timer", "numpy.array", "numpy.zeros", "matplotlib.pyplot.figure", "dolfin.vertices", "dolfin.cells", "matplotlib.pyplot.ion", "dolfin.Cell", "ocellaris.utils.gather_lines_on_root", "dolfin.facets" ]
[((8623, 8642), 'dolfin.facets', 'dolfin.facets', (['mesh'], {}), '(mesh)\n', (8636, 8642), False, 'import dolfin\n'), ((12020, 12046), 'numpy.zeros', 'numpy.zeros', (['(2, 3)', 'float'], {}), '((2, 3), float)\n', (12031, 12046), False, 'import numpy\n'), ((12067, 12088), 'numpy.zeros', 'numpy.zeros', (['(2)', 'float'], {}), '(2, float)\n', (12078, 12088), False, 'import numpy\n'), ((12131, 12150), 'dolfin.facets', 'dolfin.facets', (['mesh'], {}), '(mesh)\n', (12144, 12150), False, 'import dolfin\n'), ((15889, 15907), 'dolfin.cells', 'dolfin.cells', (['mesh'], {}), '(mesh)\n', (15901, 15907), False, 'import dolfin\n'), ((22571, 22590), 'dolfin.facets', 'dolfin.facets', (['mesh'], {}), '(mesh)\n', (22584, 22590), False, 'import dolfin\n'), ((5097, 5124), 'ocellaris.utils.gather_lines_on_root', 'gather_lines_on_root', (['lines'], {}), '(lines)\n', (5117, 5124), False, 'from ocellaris.utils import gather_lines_on_root, timeit, ocellaris_error\n'), ((8809, 8831), 'dolfin.vertices', 'dolfin.vertices', (['facet'], {}), '(facet)\n', (8824, 8831), False, 'import dolfin\n'), ((22919, 22941), 'dolfin.vertices', 'dolfin.vertices', (['facet'], {}), '(facet)\n', (22934, 22941), False, 'import dolfin\n'), ((2135, 2261), 'ocellaris.utils.ocellaris_error', 'ocellaris_error', (['"""Plot xlim must be two numbers"""', '(\'IsoSurface probe "%s" contains invalid xlim specification\' % self.name)'], {}), '(\'Plot xlim must be two numbers\', \n \'IsoSurface probe "%s" contains invalid xlim specification\' % self.name)\n', (2150, 2261), False, 'from ocellaris.utils import gather_lines_on_root, timeit, ocellaris_error\n'), ((2352, 2478), 'ocellaris.utils.ocellaris_error', 'ocellaris_error', (['"""Plot ylim must be two numbers"""', '(\'IsoSurface probe "%s" contains invalid ylim specification\' % self.name)'], {}), '(\'Plot ylim must be two numbers\', \n \'IsoSurface probe "%s" contains invalid ylim specification\' % self.name)\n', (2367, 2478), False, 'from ocellaris.utils import gather_lines_on_root, timeit, ocellaris_error\n'), ((2965, 2977), 'matplotlib.pyplot.ion', 'pyplot.ion', ([], {}), '()\n', (2975, 2977), False, 'from matplotlib import pyplot\n'), ((3001, 3016), 'matplotlib.pyplot.figure', 'pyplot.figure', ([], {}), '()\n', (3014, 3016), False, 'from matplotlib import pyplot\n'), ((4860, 4907), 'numpy.array', 'numpy.array', (['[pos[0] for pos in surface]', 'float'], {}), '([pos[0] for pos in surface], float)\n', (4871, 4907), False, 'import numpy\n'), ((4924, 4971), 'numpy.array', 'numpy.array', (['[pos[1] for pos in surface]', 'float'], {}), '([pos[1] for pos in surface], float)\n', (4935, 4971), False, 'import numpy\n'), ((12360, 12386), 'dolfin.Cell', 'dolfin.Cell', (['mesh', 'cell_id'], {}), '(mesh, cell_id)\n', (12371, 12386), False, 'import dolfin\n'), ((5654, 5696), 'dolfin.Timer', 'dolfin.Timer', (['"""Ocellaris plot iso surface"""'], {}), "('Ocellaris plot iso surface')\n", (5666, 5696), False, 'import dolfin\n')]
# -*- coding: utf-8 -*- import glob import jiagu import numpy as np from random import random def normalize(vec): total = sum(vec) assert(abs(total) > 1e-6) for i in range(len(vec)): assert(vec[i] >= 0) vec[i] = float(vec[i]) / total def get_prob(vec, prob): assert (len(vec) == len(prob)) # 归一化分布 normalize(prob) r = random() index = -1 while r > 0: index = index + 1 r = r - prob[index] return vec[index] class Document(object): def __init__(self, filename): self.doc_name = filename[:-4] self.__load_document(filename) def __load_document(self, filename): """ 读取一篇文章,默认一个file里面包含一篇文章 :param filename: filename 为 *.txt :return: self.document 文章 self.words_list 文章中所有的词 """ try: doc_file = open(filename, "r", encoding="utf-8") self.document = "" self.words_list = [] for line in doc_file: if line: line = line.strip().replace("\t", "") self.document += line self.words_list.extend(jiagu.seg(line)) except Exception as e: print("无法加载文件,错误信息 : {}".format(e)) class Corpus(object): def __init__(self, filepath): self.Documents = [] self.filepath = filepath self._build_corpus() def _build_corpus(self): """ 把所有的文章加载进来 :return: """ vocabulary = set() files = glob.glob(self.filepath + "/*.txt") if len(files) > 0: for each in files: target = Document(each) self.Documents.append(target) for word in target.words_list: vocabulary.add(word) self.vocabulary = list(vocabulary) return True else: print("目标文件夹下没有文件!!!") return False class LdaModel(object): def __init__(self, filepath, number_of_topics, alpha=50, beta=0.1, iteration=3): self.alpha = alpha self.beta = beta self.iteration = iteration self.corpus = Corpus(filepath) self.number_of_topics = number_of_topics self.__initialize_all() def __initialize_all(self): print("LDA Initializing... \nnumber of topics : {}, iteration : {}".format(self.number_of_topics, self.iteration)) self.number_of_documents = len(self.corpus.Documents) assert(self.number_of_documents > self.number_of_topics) self.document_topic_counts = np.zeros([self.number_of_documents, self.number_of_topics], dtype=np.int) self.topic_word_counts = np.zeros([self.number_of_topics, len(self.corpus.vocabulary)], dtype=np.int) self.current_word_topic_assignments = [] self.topic_counts = np.zeros(self.number_of_topics) self.doc_name = dict() for d_index, document in enumerate(self.corpus.Documents): self.doc_name.setdefault(d_index, document.doc_name) word_topic_assignments = [] for word in document.words_list: if word in self.corpus.vocabulary: w_index = self.corpus.vocabulary.index(word) starting_topic_index = np.random.randint(self.number_of_topics) word_topic_assignments.append(starting_topic_index) self.document_topic_counts[d_index, starting_topic_index] += 1 self.topic_word_counts[starting_topic_index, w_index] += 1 self.topic_counts[starting_topic_index] += 1 self.current_word_topic_assignments.append(np.array(word_topic_assignments)) for iteration in range(self.iteration): print("Iteration #" + str(iteration + 1) + "...") for d_index, document in enumerate(self.corpus.Documents): for w, word in enumerate(document.words_list): if word in self.corpus.vocabulary: w_index = self.corpus.vocabulary.index(word) current_topic_index = self.current_word_topic_assignments[d_index][w] self.document_topic_counts[d_index, current_topic_index] -= 1 self.topic_word_counts[current_topic_index, w_index] -= 1 self.topic_counts[current_topic_index] -= 1 topic_distribution = (self.topic_word_counts[:, w_index] + self.beta) * \ (self.document_topic_counts[d_index] + self.alpha) / \ (self.topic_counts + self.beta) new_topic_index = get_prob(range(self.number_of_topics), topic_distribution) self.current_word_topic_assignments[d_index][w] = new_topic_index self.document_topic_counts[d_index, new_topic_index] += 1 self.topic_word_counts[new_topic_index, w_index] += 1 self.topic_counts[new_topic_index] += 1 print("LDA Initializing finished !\n") def get_document_topic(self): for d_index, topic in enumerate(np.argmax(self.document_topic_counts, axis=1)): print("this is file {}, topic : #{}".format(self.doc_name.get(d_index), topic)) def get_word_topic(self, topN=10): for row in (self.topic_word_counts.argsort(axis=1)[:, -topN:]): print(list(map(lambda x: self.corpus.vocabulary[x], row))) if __name__ == "__main__": filepath = "documents" number_of_topics = 3 test = LdaModel(filepath, number_of_topics) test.get_document_topic() test.get_word_topic()
[ "numpy.argmax", "numpy.array", "numpy.zeros", "numpy.random.randint", "jiagu.seg", "random.random", "glob.glob" ]
[((367, 375), 'random.random', 'random', ([], {}), '()\n', (373, 375), False, 'from random import random\n'), ((1567, 1602), 'glob.glob', 'glob.glob', (["(self.filepath + '/*.txt')"], {}), "(self.filepath + '/*.txt')\n", (1576, 1602), False, 'import glob\n'), ((2618, 2691), 'numpy.zeros', 'np.zeros', (['[self.number_of_documents, self.number_of_topics]'], {'dtype': 'np.int'}), '([self.number_of_documents, self.number_of_topics], dtype=np.int)\n', (2626, 2691), True, 'import numpy as np\n'), ((2879, 2910), 'numpy.zeros', 'np.zeros', (['self.number_of_topics'], {}), '(self.number_of_topics)\n', (2887, 2910), True, 'import numpy as np\n'), ((5224, 5269), 'numpy.argmax', 'np.argmax', (['self.document_topic_counts'], {'axis': '(1)'}), '(self.document_topic_counts, axis=1)\n', (5233, 5269), True, 'import numpy as np\n'), ((3713, 3745), 'numpy.array', 'np.array', (['word_topic_assignments'], {}), '(word_topic_assignments)\n', (3721, 3745), True, 'import numpy as np\n'), ((3318, 3358), 'numpy.random.randint', 'np.random.randint', (['self.number_of_topics'], {}), '(self.number_of_topics)\n', (3335, 3358), True, 'import numpy as np\n'), ((1186, 1201), 'jiagu.seg', 'jiagu.seg', (['line'], {}), '(line)\n', (1195, 1201), False, 'import jiagu\n')]
import logging import math from collections import defaultdict from enum import Enum from itertools import chain from random import randint, random from typing import List import numpy as np from scipy import optimize import util.optimizer_utils as utils class Algorithm(Enum): """The currently possible algorithms.""" fifty_fifty = 'fifty_fifty' L_BFGS_B = 'L-BFGS-B' SLSQP = 'SLSQP' TNC = 'TNC' class Optimizer: def __init__(self, producer, options): self.producer = producer self.options = options self.logger = logging.getLogger("src.Optimizer") self.differentiated_loads = [] self.min_objective_value = float('inf') self.penalty_factor = float(self.options["pen"]) if "pen" in self.options else 1.0 self.algorithm = Algorithm[options["algo"]] # The estimated total produced energy is the last entry of the producer's prediction profile self.objection_value_offset = 0 self.cache = defaultdict(lambda: np.inf) def optimize(self): if self.algorithm in [Algorithm.L_BFGS_B, Algorithm.SLSQP, Algorithm.TNC]: schedule_times, should_keep = self.basinhopping() elif self.algorithm == Algorithm.fifty_fifty: schedule_times, should_keep = self.fifty_fifty() else: should_keep = [True] * len(self.producer.schedule) schedule_times = [s['job'].scheduled_time for s in self.producer.schedule] self._reset_cache() return schedule_times, should_keep def basinhopping(self): self.reset_and_differentiate_loads() self.objection_value_offset = self.producer.prediction.values[-1] tol = self.options["tol"] if "tol" in self.options else 1000.0 eps = self.options["eps"] if "eps" in self.options else 0.001 now = self.producer.manager.clock.now bounds = [(max(s['job'].est, now), s['job'].lst) for s in self.producer.schedule] x0 = np.array([randint(b[0], b[1]) for b in bounds]) kwargs = dict(method=self.algorithm.value, bounds=bounds, options=dict(eps=eps), tol=tol) # The Basin-hopping algorithm is good at finding global minimums. result = optimize.basinhopping(func=self.objective_function, x0=x0, minimizer_kwargs=kwargs) objective_value = result.fun schedule_times = list([int(round(e)) for e in result.x]) should_keep = [True] * len(self.producer.schedule) strictly_positive = self.strictly_positive() if np.isinf(self.min_objective_value) and not strictly_positive: should_keep[-1] = False elif objective_value < self.min_objective_value or strictly_positive: self.min_objective_value = objective_value else: should_keep[-1] = False return schedule_times, should_keep def fifty_fifty(self): should_keep = [True] * len(self.producer.schedule) need_grid_power = not self.strictly_positive() if random() < 0.5 or need_grid_power: should_keep[-1] = False schedule_times = [s['job'].scheduled_time for s in self.producer.schedule] return schedule_times, should_keep def objective_function(self, s: List[float]): """The function we want to minimize. schedule is a List of start times for the jobs in the schedule.""" schedule = [utils.round_to_nearest_60(x) for x in s] cache = self._get_cached_value(schedule) if cache < np.inf: return cache consumed = defaultdict(float) for i, load in enumerate(self.differentiated_loads): for t, p in load.items(): if not math.isnan(schedule[i]): start_time = schedule[i] # Add power, p(t), to consumed at time 'start_time' plus 't' consumed[int(round(start_time + t))] += p # Differentiate and interpolate production profile on the indices found in consumer ts = list(consumed.keys()) produced = utils.differentiate_and_interpolate(self.producer.prediction, ts) ts = sorted(list(set(ts))) diff = 0 penalty = 0 for i, t in enumerate(ts): if i == len(ts) - 1: delta = 0 else: delta = abs(ts[i + 1] - ts[i]) p = produced[t] c = consumed[t] # Multiply difference between produced and consumed in time 't' by the distance to the previous time index. # This way, differences are weighted based on their time span. diff += abs((p - c) * delta) # If consumed is greater than produced, we have negative amount of production power. if c > p: diff_t = abs(p - c) * delta penalty += diff_t # Return the difference between produced and consumed energy, in addition to the penalty for having negative # power levels. Finally, subtract this from the objection_value_offset, i.e. the sum of the produced power. This # is so that the theoretically minimal value is equal to zero (if we consume all produced energy). score = diff + penalty * self.penalty_factor self._cache_value(schedule, score) return score def strictly_positive(self): """Checks if the current schedules yields positive power in every time step (i.e. we always have more produced energy than consumed energy. Mostly the same as the objective function, but terminates faster, and returns a boolean value indicating whether the excess energy function is always positive, given the current schedule.""" schedule = [s['job'].scheduled_time for s in self.producer.schedule] self.reset_and_differentiate_loads() consumed = defaultdict(float) for i, load in enumerate(self.differentiated_loads): for t, p in load.items(): offset = schedule[i] consumed[int(round(t + offset))] += p ts = list(consumed.keys()) produced = utils.differentiate_and_interpolate(self.producer.prediction, ts) ts.extend(list(produced.index.values)) ts = sorted(ts) for i, t in enumerate(ts): if consumed[t] > produced[t]: return False return True # def reset_and_differentiate_loads(self): """Re-compute the differentiated and interpolated load profiles""" indices = list(set(chain.from_iterable( map(lambda x: self.producer.schedule[x]['job'].load_profile.index.values.tolist(), range(0, len(self.producer.schedule)))))) indices.sort() # Interpolate and differentiate load profiles before optimization. self.differentiated_loads = [] for s in self.producer.schedule: self.differentiated_loads.append(utils.differentiate(s['job'].load_profile)) def _reset_cache(self): self.cache = defaultdict(lambda: np.inf) def _key(self, schedule): return "".join([str(int(round(f))) + ";" for f in schedule]) def _get_cached_value(self, schedule): return self.cache[self._key(schedule)] def _cache_value(self, schedule, value): self.cache[self._key(schedule)] = value
[ "logging.getLogger", "util.optimizer_utils.round_to_nearest_60", "math.isnan", "util.optimizer_utils.differentiate_and_interpolate", "scipy.optimize.basinhopping", "collections.defaultdict", "random.random", "numpy.isinf", "random.randint", "util.optimizer_utils.differentiate" ]
[((568, 602), 'logging.getLogger', 'logging.getLogger', (['"""src.Optimizer"""'], {}), "('src.Optimizer')\n", (585, 602), False, 'import logging\n'), ((996, 1024), 'collections.defaultdict', 'defaultdict', (['(lambda : np.inf)'], {}), '(lambda : np.inf)\n', (1007, 1024), False, 'from collections import defaultdict\n'), ((2224, 2312), 'scipy.optimize.basinhopping', 'optimize.basinhopping', ([], {'func': 'self.objective_function', 'x0': 'x0', 'minimizer_kwargs': 'kwargs'}), '(func=self.objective_function, x0=x0, minimizer_kwargs\n =kwargs)\n', (2245, 2312), False, 'from scipy import optimize\n'), ((3555, 3573), 'collections.defaultdict', 'defaultdict', (['float'], {}), '(float)\n', (3566, 3573), False, 'from collections import defaultdict\n'), ((4056, 4121), 'util.optimizer_utils.differentiate_and_interpolate', 'utils.differentiate_and_interpolate', (['self.producer.prediction', 'ts'], {}), '(self.producer.prediction, ts)\n', (4091, 4121), True, 'import util.optimizer_utils as utils\n'), ((5840, 5858), 'collections.defaultdict', 'defaultdict', (['float'], {}), '(float)\n', (5851, 5858), False, 'from collections import defaultdict\n'), ((6104, 6169), 'util.optimizer_utils.differentiate_and_interpolate', 'utils.differentiate_and_interpolate', (['self.producer.prediction', 'ts'], {}), '(self.producer.prediction, ts)\n', (6139, 6169), True, 'import util.optimizer_utils as utils\n'), ((7014, 7042), 'collections.defaultdict', 'defaultdict', (['(lambda : np.inf)'], {}), '(lambda : np.inf)\n', (7025, 7042), False, 'from collections import defaultdict\n'), ((2535, 2569), 'numpy.isinf', 'np.isinf', (['self.min_objective_value'], {}), '(self.min_objective_value)\n', (2543, 2569), True, 'import numpy as np\n'), ((3393, 3421), 'util.optimizer_utils.round_to_nearest_60', 'utils.round_to_nearest_60', (['x'], {}), '(x)\n', (3418, 3421), True, 'import util.optimizer_utils as utils\n'), ((1996, 2015), 'random.randint', 'randint', (['b[0]', 'b[1]'], {}), '(b[0], b[1])\n', (2003, 2015), False, 'from random import randint, random\n'), ((3013, 3021), 'random.random', 'random', ([], {}), '()\n', (3019, 3021), False, 'from random import randint, random\n'), ((6920, 6962), 'util.optimizer_utils.differentiate', 'utils.differentiate', (["s['job'].load_profile"], {}), "(s['job'].load_profile)\n", (6939, 6962), True, 'import util.optimizer_utils as utils\n'), ((3696, 3719), 'math.isnan', 'math.isnan', (['schedule[i]'], {}), '(schedule[i])\n', (3706, 3719), False, 'import math\n')]
# 可以自己import我们平台支持的第三方python模块,比如pandas、numpy等。 from rqalpha.api import * import pandas as pd import numpy as np from datetime import timedelta from pybrain.datasets import SequentialDataSet from pybrain.tools.shortcuts import buildNetwork from pybrain.structure.networks import Network from pybrain.structure.modules import LSTMLayer from pybrain.supervised import RPropMinusTrainer # 训练trainX和trainY,并返回神经网络net def train(context, trainX, trainY): ds = SequentialDataSet(4, 1) for dataX, dataY in zip(trainX, trainY): ds.addSample(dataX, dataY) net = buildNetwork(4, 1, 1, hiddenclass=LSTMLayer, outputbias=False, recurrent=True) trainer = RPropMinusTrainer(net, dataset=ds) EPOCHS_PER_CYCLE = 5 CYCLES = 5 for i in range(CYCLES): trainer.trainEpochs(EPOCHS_PER_CYCLE) return net, trainer.testOnData() # 更新数据集data def load(context, ticker): close = history(90, '1d', 'close')[ticker] high = history(90, '1d', 'high')[ticker] low = history(90, '1d', 'low')[ticker] volume = history(90, '1d', 'volume')[ticker] data = pd.DataFrame({'close': close.values, 'high': high.values, 'low': low.values, 'volume': volume.values}, index=close.index) context.position_ratio.append([data['close'].mean(), data['high'].mean(), data['low'].mean(), data['volume'].mean()]) context.shape_ratio.append([data['close'].std(), data['high'].std(), data['low'].std(), data['volume'].std()]) data['close'] = (data['close'] - context.position_ratio[-1][0]) / context.shape_ratio[-1][0] data['high'] = (data['high'] - context.position_ratio[-1][1]) / context.shape_ratio[-1][1] data['low'] = (data['low'] - context.position_ratio[-1][2]) / context.shape_ratio[-1][2] data['volume'] = (data['volume'] - context.position_ratio[-1][3]) / context.shape_ratio[-1][3] return data # 剔除情况特殊的黑名单股,只看策略效果,排除个体问题 def filter_blacklist(context, stock_list): return [ticker for ticker in stock_list if ticker not in context.blacklist] def filter_stlist(stock_list): return [ticker for ticker in stock_list if not is_st_stock(ticker)] # 建模,每3个月运行一次,用过去6个月训练 def modelize(context, bar_dict): if context.every_3_months % 3 != 0: context.every_3_months += 1 return 0 print('-' * 65) print('------' + '{:-^59}'.format('modelizing')) context.position_ratio = [] context.shape_ratio = [] context.data = [] context.net = [] context.list = [] templist = list(get_fundamentals(query(fundamentals.eod_derivative_indicator.market_cap) .order_by(fundamentals.eod_derivative_indicator.market_cap.asc()) .limit(context.num * 5)).columns) context.list = filter_blacklist(context, filter_stlist(templist))[:context.num] names = [] scores = [] for ticker in context.list: names.append('{:<11}'.format(ticker)) data = load(context, ticker) trainX = data.ix[:-1, :].values trainY = data.ix[1:, 0].values net, mse = train(context, trainX, trainY) context.data.append(data) context.net.append(net) scores.append('{:<11}'.format(str(mse)[:6])) if np.isnan(mse): context.blacklist.append(ticker) context.mflag = 0 return 0 context.pct = [0] * context.num print('------' + '{:-^59}'.format('finished')) print('-' * 65) print(' nm | ' + ' '.join(names)) print('mse | ' + ' '.join(scores)) context.mflag = 1 # 标记已经建模 context.tflag = 0 context.every_3_months += 1 def mkt_panic(): # 连续两天大盘跌破3个点,或者大盘跌破5个点 mkt = history(3, '1d', 'close')['000001.XSHG'] panic = (mkt[-1] / mkt[-2] < 0.97 and mkt[-2] / mkt[-3] < 0.97) or mkt[-1] / mkt[-2] < 0.95 if panic: print('!!!!!!' + '{:!^59}'.format('panic')) return 1 return 0 # 最后利用每3个月更新的模型,每天进行交易,预测涨幅超过a就买入,预测跌幅超过b则卖出 def trade(context, bar_dict): while context.mflag == 0: modelize(context, bar_dict) trash_bin = [ticker for ticker in context.portfolio.positions if ticker not in context.list] for ticker in trash_bin: order_target_percent(ticker, 0) actual_close = [] actual_high = [] actual_low = [] actual_vol = [] actual_open = [] actual_data = [] predict_close = [] for i in range(context.num): actual_close.append( (history(1, '1d', 'close')[context.list[i]][0] - context.position_ratio[i][0]) / context.shape_ratio[i][0]) actual_high.append( (history(1, '1d', 'high')[context.list[i]][0] - context.position_ratio[i][1]) / context.shape_ratio[i][1]) actual_low.append( (history(1, '1d', 'low')[context.list[i]][0] - context.position_ratio[i][2]) / context.shape_ratio[i][2]) actual_vol.append( (history(1, '1d', 'volume')[context.list[i]][0] - context.position_ratio[i][3]) / context.shape_ratio[i][3]) actual_open.append( (history(1, '1m', 'close')[context.list[i]][0] - context.position_ratio[i][0]) / context.shape_ratio[i][0]) actual_data.append([actual_close[i], actual_high[i], actual_low[i], actual_vol[i]]) predict_close.append(context.net[i].activate(actual_data[i])[0]) if context.tflag == 0: context.temp_pc = predict_close r = [float((pc * shape_ratio[0] + position_ratio[0]) / (ao * shape_ratio[0] + position_ratio[0]) - 1) for pc, ao, shape_ratio, position_ratio in zip(predict_close, actual_open, context.shape_ratio, context.position_ratio)] temp_r = [float((pc * shape_ratio[0] + position_ratio[0]) / (tpc * shape_ratio[0] + position_ratio[0]) - 1) for pc, tpc, shape_ratio, position_ratio in zip(predict_close, context.temp_pc, context.shape_ratio, context.position_ratio)] # The essence of this strategy hybrid_r = [max(ri, temp_ri, ri + temp_ri) for ri, temp_ri in zip(r, temp_r)] bad_hybrid_signal = sum([x <= 0 for x in hybrid_r]) a, b = 0.00, -0.01 panic = mkt_panic() for i in range(context.num): if panic or 0 < context.post_panic < 22 * context.num: context.pct[i] = 0 context.post_panic = (1 - panic) * (context.post_panic + 1) + panic elif hybrid_r[i] > a: context.pct[i] = min(context.pct[i] + .5 / context.num, 2 / context.num) context.post_panic = 0 elif hybrid_r[i] < b or bad_hybrid_signal > 3 * context.num // 5: context.pct[i] = max(context.pct[i] - .5 / context.num, 0) context.post_panic = 0 if context.tflag == 1: print(' ac | ' + ' '.join(['{:<11}'.format(str(ac)[:6]) for ac in actual_close])) print('-' * 65) print(' ao | ' + ' '.join(['{:<11}'.format(str(ao)[:6]) for ao in actual_open])) print(' pc | ' + ' '.join(['{:<11}'.format(str(pc)[:6]) for pc in predict_close])) print(' r | ' + ' '.join(['{:<11}'.format(str(ri)[:6]) for ri in hybrid_r])) pct = sum([context.portfolio.positions[ticker].market_value for ticker in context.portfolio.positions]) / ( context.portfolio.market_value + context.portfolio.cash) tot_pct = max(sum(context.pct), 1) context.pct = list(map(lambda x: x / tot_pct, context.pct)) print(' % | ' + ' '.join(['{:<11}'.format(str(p)[:6]) for p in context.pct])) plot('total position', pct * 100) for i in range(context.num): order_target_percent(context.list[i], context.pct[i]) context.tflag = 1 context.temp_pc = predict_close # 在这个方法中编写任何的初始化逻辑。context对象将会在你的算法策略的任何方法之间做传递。 def init(context): context.temp_pc = [] context.every_3_months = 0 context.tflag = 0 context.mflag = 0 context.position_ratio = [] context.shape_ratio = [] context.num = 20 context.list = [] context.pct = [0] * context.num context.net = [] context.data = [] context.post_panic = 0 context.blacklist = [ '000004.XSHE', '000546.XSHE', '000594.XSHE', '002352.XSHE', '300176.XSHE', '300260.XSHE', '300372.XSHE', '600137.XSHG', '600306.XSHG', '600656.XSHG', ] scheduler.run_monthly(modelize, 1) scheduler.run_daily(trade, time_rule=market_open(minute=1)) # before_trading此函数会在每天交易开始前被调用,当天只会被调用一次 def before_trading(context): pass # 你选择的证券的数据更新将会触发此段逻辑,例如日或分钟历史数据切片或者是实时数据切片更新 def handle_bar(context, bar_dict): pass
[ "pybrain.tools.shortcuts.buildNetwork", "pybrain.datasets.SequentialDataSet", "numpy.isnan", "pandas.DataFrame", "pybrain.supervised.RPropMinusTrainer" ]
[((460, 483), 'pybrain.datasets.SequentialDataSet', 'SequentialDataSet', (['(4)', '(1)'], {}), '(4, 1)\n', (477, 483), False, 'from pybrain.datasets import SequentialDataSet\n'), ((574, 652), 'pybrain.tools.shortcuts.buildNetwork', 'buildNetwork', (['(4)', '(1)', '(1)'], {'hiddenclass': 'LSTMLayer', 'outputbias': '(False)', 'recurrent': '(True)'}), '(4, 1, 1, hiddenclass=LSTMLayer, outputbias=False, recurrent=True)\n', (586, 652), False, 'from pybrain.tools.shortcuts import buildNetwork\n'), ((667, 701), 'pybrain.supervised.RPropMinusTrainer', 'RPropMinusTrainer', (['net'], {'dataset': 'ds'}), '(net, dataset=ds)\n', (684, 701), False, 'from pybrain.supervised import RPropMinusTrainer\n'), ((1089, 1214), 'pandas.DataFrame', 'pd.DataFrame', (["{'close': close.values, 'high': high.values, 'low': low.values, 'volume':\n volume.values}"], {'index': 'close.index'}), "({'close': close.values, 'high': high.values, 'low': low.values,\n 'volume': volume.values}, index=close.index)\n", (1101, 1214), True, 'import pandas as pd\n'), ((3489, 3502), 'numpy.isnan', 'np.isnan', (['mse'], {}), '(mse)\n', (3497, 3502), True, 'import numpy as np\n')]
#!/usr/bin/env python3 import sys import os import biopac_preproc as bio import numpy as np sub = sys.argv[1] ses = sys.argv[2] ftype = sys.argv[3] wdir = '/data' SET_DPI = 100 cwd = os.getcwd() os.chdir(wdir) filename = f'sub-{sub}/ses-{ses}/func_phys/sub-{sub}_ses-{ses}_task-breathhold_physio' npidx = np.genfromtxt(f'{filename}_manualpeaks.1D').astype('int') co = np.genfromtxt(f'{filename}_co_orig.1D') GM_name = f'CVR/sub-{sub}_ses-{ses}_GM_{ftype}_avg' bio.parttwo(co, npidx, filename, GM_name) os.chdir(cwd)
[ "os.chdir", "biopac_preproc.parttwo", "numpy.genfromtxt", "os.getcwd" ]
[((187, 198), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (196, 198), False, 'import os\n'), ((200, 214), 'os.chdir', 'os.chdir', (['wdir'], {}), '(wdir)\n', (208, 214), False, 'import os\n'), ((374, 413), 'numpy.genfromtxt', 'np.genfromtxt', (['f"""{filename}_co_orig.1D"""'], {}), "(f'{filename}_co_orig.1D')\n", (387, 413), True, 'import numpy as np\n'), ((467, 508), 'biopac_preproc.parttwo', 'bio.parttwo', (['co', 'npidx', 'filename', 'GM_name'], {}), '(co, npidx, filename, GM_name)\n', (478, 508), True, 'import biopac_preproc as bio\n'), ((510, 523), 'os.chdir', 'os.chdir', (['cwd'], {}), '(cwd)\n', (518, 523), False, 'import os\n'), ((311, 354), 'numpy.genfromtxt', 'np.genfromtxt', (['f"""{filename}_manualpeaks.1D"""'], {}), "(f'{filename}_manualpeaks.1D')\n", (324, 354), True, 'import numpy as np\n')]
""" Provides analysis of site symmetries. """ import numpy as np from pymatgen.symmetry.analyzer import SpacegroupAnalyzer as sga from pymatgen.core.operations import SymmOp def get_site_symmetries(struc, precision=0.1): """ Get all the point group operations centered on each atomic site in the form [[point operations of site index 1]...[[point operations of site index N]]] Args: struc: Pymatgen structure precision (float): tolerance to find symmetry operaitons Return: list of lists of point operations for each atomic site """ pointops = [] # Point symmetries of each atom for site1 in range(len(struc.sites)): tempstruc = struc.copy() # Place the origin of the cell at each atomic site pointops.append([]) for site2 in range(len(struc.sites)): tempstruc.replace( site2, tempstruc.sites[site2].specie, tempstruc.frac_coords[site2] - struc.frac_coords[site1], ) sgastruc = sga(tempstruc, symprec=precision) ops = sgastruc.get_symmetry_operations(cartesian=True) for site2 in range(len(ops)): if all(ops[site2].translation_vector == [0, 0, 0]): pointops[site1].append(ops[site2]) return pointops def get_shared_symmetry_operations(struc, pointops, tol=0.1): """ Get all the point group operations shared by a pair of atomic sites in the form [[point operations of site index 1],[],...,[]] Args: struc: Pymatgen structure pointops: list of point group operations from get_site_symmetries method Return: list of lists of shared point operations for each pair of atomic sites """ numsites = len(struc) sharedops = [[0 for x in range(numsites)] for y in range(numsites)] for site1 in range(numsites): for site2 in range(numsites): sharedops[site1][site2] = [] for op1 in range(len(pointops[site1])): for op2 in range(len(pointops[site2])): if np.allclose( pointops[site1][op1].rotation_matrix, pointops[site2][op2].rotation_matrix, ): sharedops[site1][site2].append(pointops[site1][op1]) for site1 in range(len(sharedops)): for site2 in range(len(sharedops[site1])): uniqueops = [] for ops in range(len(sharedops[site1][site2])): op = SymmOp.from_rotation_and_translation( rotation_matrix=sharedops[site1][site2][ops].rotation_matrix, translation_vec=(0, 0, 0), tol=tol, ) if op in uniqueops: continue else: uniqueops.append(op) sharedops[site1][site2] = uniqueops return sharedops
[ "pymatgen.symmetry.analyzer.SpacegroupAnalyzer", "numpy.allclose", "pymatgen.core.operations.SymmOp.from_rotation_and_translation" ]
[((1060, 1093), 'pymatgen.symmetry.analyzer.SpacegroupAnalyzer', 'sga', (['tempstruc'], {'symprec': 'precision'}), '(tempstruc, symprec=precision)\n', (1063, 1093), True, 'from pymatgen.symmetry.analyzer import SpacegroupAnalyzer as sga\n'), ((2570, 2709), 'pymatgen.core.operations.SymmOp.from_rotation_and_translation', 'SymmOp.from_rotation_and_translation', ([], {'rotation_matrix': 'sharedops[site1][site2][ops].rotation_matrix', 'translation_vec': '(0, 0, 0)', 'tol': 'tol'}), '(rotation_matrix=sharedops[site1][site2\n ][ops].rotation_matrix, translation_vec=(0, 0, 0), tol=tol)\n', (2606, 2709), False, 'from pymatgen.core.operations import SymmOp\n'), ((2133, 2225), 'numpy.allclose', 'np.allclose', (['pointops[site1][op1].rotation_matrix', 'pointops[site2][op2].rotation_matrix'], {}), '(pointops[site1][op1].rotation_matrix, pointops[site2][op2].\n rotation_matrix)\n', (2144, 2225), True, 'import numpy as np\n')]
""" helpers.py for RiskPaths """ import numpy as np from bisect import bisect_left def partition(start, finish, step=1): """ Helper function to return an inclusive equal-spaced range, i.e. finish will be the last element """ return np.linspace(start, finish, (finish-start)/step + 1) def interp(range, value): """ Equivalent to self-scheduling split """ # TODO check behaviour outside range is same idx = bisect_left(range, value) # if idx == len(range) # idx = idx - 1 return idx
[ "numpy.linspace", "bisect.bisect_left" ]
[((238, 293), 'numpy.linspace', 'np.linspace', (['start', 'finish', '((finish - start) / step + 1)'], {}), '(start, finish, (finish - start) / step + 1)\n', (249, 293), True, 'import numpy as np\n'), ((418, 443), 'bisect.bisect_left', 'bisect_left', (['range', 'value'], {}), '(range, value)\n', (429, 443), False, 'from bisect import bisect_left\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 pyiron_atomistics import Project as ProjectCore from pyiron_feal.factories.structure import StructureFactory from pyiron_feal.factories.job import JobFactory from pyiron_base import DataContainer from pyiron_feal.subroutines import ZeroK, MCMDSRO import numpy as np __author__ = "<NAME>" __copyright__ = ( "Copyright 2021, Max-Planck-Institut für Eisenforschung GmbH - " "Computational Materials Design (CM) Department" ) __version__ = "0.1" __maintainer__ = "<NAME>" __email__ = "<EMAIL>" __status__ = "development" __date__ = "Jun 10, 2021" class ProjectInput(DataContainer): def __init__(self, init=None, table_name=None): super().__init__(init=init, table_name=table_name) self.potentials_eam = np.array([ '2005--Mendelev-M-I--Al-Fe--LAMMPS--ipr1', '2020--Farkas-D--Fe-Ni-Cr-Co-Al--LAMMPS--ipr1', ]) self.potentials_meam = np.array([ '2010--Lee-E--Fe-Al--LAMMPS--ipr1', '2012--Jelinek-B--Al-Si-Mg-Cu-Fe--LAMMPS--ipr2', ]) self.experimental_data = { 'c_Al': 0.18, 'T': 523, 'SS': 1 - (0.0042 + 0.1232), 'B2': 0.0042, 'D03': 0.1232 } @property def potentials(self): return np.append(self.potentials_eam, self.potentials_meam) class Project(ProjectCore): def __init__(self, path="", user=None, sql_query=None, default_working_directory=False): super(Project, self).__init__( path=path, user=user, sql_query=sql_query, default_working_directory=default_working_directory ) self.create._structure = StructureFactory() self.create._job_factory = JobFactory(self) self._zerok = ZeroK(self) self._mcmd_sro = MCMDSRO(self) @property def input(self) -> ProjectInput: # A workaround since we can't populate the data field in `__init__` try: return self.data.input except AttributeError: self.data.input = ProjectInput() return self.data.input @property def zerok(self): return self._zerok @property def mcmd_sro(self): return self._mcmd_sro def lammps_potl_to_string(self, potl_name): return ' '.join(potl_name.split('--')[:2]).replace('-', ' ')
[ "pyiron_feal.factories.structure.StructureFactory", "pyiron_feal.subroutines.ZeroK", "numpy.append", "numpy.array", "pyiron_feal.factories.job.JobFactory", "pyiron_feal.subroutines.MCMDSRO" ]
[((936, 1041), 'numpy.array', 'np.array', (["['2005--Mendelev-M-I--Al-Fe--LAMMPS--ipr1',\n '2020--Farkas-D--Fe-Ni-Cr-Co-Al--LAMMPS--ipr1']"], {}), "(['2005--Mendelev-M-I--Al-Fe--LAMMPS--ipr1',\n '2020--Farkas-D--Fe-Ni-Cr-Co-Al--LAMMPS--ipr1'])\n", (944, 1041), True, 'import numpy as np\n'), ((1104, 1203), 'numpy.array', 'np.array', (["['2010--Lee-E--Fe-Al--LAMMPS--ipr1',\n '2012--Jelinek-B--Al-Si-Mg-Cu-Fe--LAMMPS--ipr2']"], {}), "(['2010--Lee-E--Fe-Al--LAMMPS--ipr1',\n '2012--Jelinek-B--Al-Si-Mg-Cu-Fe--LAMMPS--ipr2'])\n", (1112, 1203), True, 'import numpy as np\n'), ((1477, 1529), 'numpy.append', 'np.append', (['self.potentials_eam', 'self.potentials_meam'], {}), '(self.potentials_eam, self.potentials_meam)\n', (1486, 1529), True, 'import numpy as np\n'), ((1879, 1897), 'pyiron_feal.factories.structure.StructureFactory', 'StructureFactory', ([], {}), '()\n', (1895, 1897), False, 'from pyiron_feal.factories.structure import StructureFactory\n'), ((1933, 1949), 'pyiron_feal.factories.job.JobFactory', 'JobFactory', (['self'], {}), '(self)\n', (1943, 1949), False, 'from pyiron_feal.factories.job import JobFactory\n'), ((1972, 1983), 'pyiron_feal.subroutines.ZeroK', 'ZeroK', (['self'], {}), '(self)\n', (1977, 1983), False, 'from pyiron_feal.subroutines import ZeroK, MCMDSRO\n'), ((2009, 2022), 'pyiron_feal.subroutines.MCMDSRO', 'MCMDSRO', (['self'], {}), '(self)\n', (2016, 2022), False, 'from pyiron_feal.subroutines import ZeroK, MCMDSRO\n')]
from __future__ import absolute_import, division, print_function import os import re import pickle import warnings import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from rlssm import plotting from .utils import list_individual_variables from .stan_utility import check_all_diagnostics from .random import random_ddm, random_rdm_2A class FittedModel(object): def __init__(self, stan_model, data, hierarchical_levels, model_label, family, n_parameters_individual, n_parameters_trial, print_diagnostics, priors): self.stan_model = stan_model self.model_label = model_label self.family = family self.priors = priors # Print mcmc diagnostics... if print_diagnostics: check_all_diagnostics(self.stan_model) self.data_info = {'N': data.shape[0], 'data':data} n_samples_after_warmup = self.stan_model.stan_args[0]['iter'] - self.stan_model.stan_args[0]['warmup'] n_posterior_samples = n_samples_after_warmup / self.stan_model.stan_args[0]['thin']*len(self.stan_model.stan_args) self.parameters_info = {'hierarchical_levels': hierarchical_levels, 'n_parameters_individual':n_parameters_individual, 'n_parameters_trial': n_parameters_trial, 'n_posterior_samples': int(n_posterior_samples)} if self.parameters_info['hierarchical_levels'] == 2: self.data_info.update({'L': len(pd.unique(data.participant))}) self.parameters_info.update({'n_parameters_group': n_parameters_individual*2, 'n_parameters_hierarchical': n_parameters_individual*2 + n_parameters_individual*self.data_info['L']}) r = re.compile("transf_.+") parameters_names_transf = list(filter(r.match, self.stan_model.flatnames)) individual_parameters_names = [name[10:] for name in parameters_names_transf] r = re.compile("mu_.+") group_parameters_mu = list(filter(r.match, self.stan_model.flatnames)) r = re.compile("sd_.+") group_parameters_sd = list(filter(r.match, self.stan_model.flatnames)) group_parameters_names_transf = parameters_names_transf + group_parameters_sd # add transformed par names for plotting group_parameters_names = group_parameters_mu + group_parameters_sd r = re.compile("z_.+_trial.+") trials_deviations = list(filter(r.match, self.stan_model.flatnames)) r = re.compile("z_.+") individual_deviations = list(filter(r.match, self.stan_model.flatnames)) if len(trials_deviations) > 0: [individual_deviations.remove(el) for el in trials_deviations] parameters_names = group_parameters_names + individual_deviations parameters_names_all = parameters_names + trials_deviations self.parameters_info.update({'parameters_names': parameters_names, # group parameters and individual deviations 'group_parameters_names': group_parameters_names, # group parameters 'individual_parameters_names': individual_parameters_names, # names of individual parameters 'group_parameters_names_transf': parameters_names_transf, # group parameters for plotting 'parameters_names_all': parameters_names_all}) # all parameters for the rhat calculations else: self.data_info.update({'L': 1}) r = re.compile("transf_.+") parameters_names_transf = list(filter(r.match, self.stan_model.flatnames)) parameters_names = [name[7:] for name in parameters_names_transf] r = re.compile("z_.+_trial.+") parameters_names_all = parameters_names + list(filter(r.match, self.stan_model.flatnames)) self.parameters_info.update({'parameters_names': parameters_names}) self.parameters_info.update({'parameters_names_transf': parameters_names_transf}) # add transformed par names for plotting self.parameters_info.update({'parameters_names_all': parameters_names_all}) # for the rhat calculations def get_rhat(self): """Extracts rhat from stan model's summary as a pandas dataframe. Only considers parameters (Not all variables specified in stan's model). Note that, when DDM parameters are estimated at a trial level, these are included in the rhat stats. Returns ------- convergence: DataFrame Data frame with rows the parameters and columns the rhat and variable names. """ summary = self.stan_model.summary(pars=self.parameters_info['parameters_names_all']) convergence = pd.DataFrame({'rhat': np.array(summary['summary'])[:, 9], 'variable': summary['summary_rownames']}) return convergence def calculate_waic(self, pointwise=False): """Calculates the Watanabe-Akaike information criteria. Calculates pWAIC1 and pWAIC2 according to http://www.stat.columbia.edu/~gelman/research/published/waic_understand3.pdf Parameters ---------- pointwise : bool, default to False By default, gives the averaged waic. Set to True is you want additional waic per observation. Returns ------- out: dict Dictionary containing lppd (log pointwise predictive density), p_waic, waic, waic_se (standard error of the waic), and pointwise_waic (when `pointwise` is True). """ log_likelihood = self.stan_model['log_lik'] # n_samples X N observations likelihood = np.exp(log_likelihood) mean_l = np.mean(likelihood, axis=0) # N observations pointwise_lppd = np.log(mean_l) lppd = np.sum(pointwise_lppd) pointwise_var_l = np.var(log_likelihood, axis=0) # N observations var_l = np.sum(pointwise_var_l) pointwise_waic = - 2*pointwise_lppd + 2*pointwise_var_l waic = -2*lppd + 2*var_l waic_se = np.sqrt(self.data_info['N'] * np.var(pointwise_waic)) if pointwise: out = {'lppd':lppd, 'p_waic':var_l, 'waic':waic, 'waic_se':waic_se, 'pointwise_waic':pointwise_waic} else: out = {'lppd':lppd, 'p_waic':var_l, 'waic':waic, 'waic_se':waic_se} return out def get_last_values(self): """Extracts the last posterior estimates values in each chain. Returns ------- starting_points: DataFrame Data frame with as many rows as number of chains that were run. Parameter values are in separate columns. """ samplesChains = self.stan_model.to_dataframe(pars=self.parameters_info['parameters_names_all'], permuted=False, diagnostics=False) starting_points = samplesChains[samplesChains['draw'] == max(samplesChains['draw'])] return starting_points class ModelResults(object): def __init__(self, model_label, data_info, parameters_info, priors, rhat, waic, last_values, samples, trial_samples): """Initiates a ModelResults object. Parameters ---------- Attributes ---------- """ self.model_label = model_label self.data_info = data_info self.parameters_info = parameters_info self.priors = priors self.rhat = rhat self.waic = waic self.last_values = last_values self.samples = samples self.trial_samples = trial_samples def to_pickle(self, filename=None): """Pickle the fitted model's results object to file. This can be used to store the model's result and read them and inspect them at a later stage, without having to refit the model. Parameters ---------- filename : str, optional File path where the pickled object will be stored. If not specified, is set to """ dir_path = os.getcwd()#os.path.dirname(os.path.realpath(__file__)) if filename is None: filename = os.path.join(dir_path, '{}.pkl'.format(self.model_label)) print("Saving file as: {}".format(filename)) with open(filename, 'wb') as f: pickle.dump(self, f) f.close() def plot_posteriors(self, gridsize=100, clip=None, show_intervals="HDI", alpha_intervals=.05, intervals_kws=None, **kwargs): """Plots posterior predictives of the model's parameters. If the model is hierarchical, then only the group parameters are plotted. In particular, group means are plotted in the first row and group standard deviations are plotted in the second row. By default, 95 percent HDI are shown. The kernel density estimation is calculated using scipy.stats.gaussian_kde. Parameters ---------- gridsize : int, default to 100 Resolution of the kernel density estimation function, default to 100. clip : tuple of (float, float), optional Range for the kernel density estimation function. Default is min and max values of the distribution. show_intervals : str, default to "HDI" Either "HDI", "BCI", or None. HDI is better when the distribution is not simmetrical. If None, then no intervals are shown. alpha_intervals : float, default to .05 Alpha level for the intervals. Default is 5 percent which gives 95 percent BCIs and HDIs. intervals_kws : dict Additional arguments for `matplotlib.axes.Axes.fill_between` that shows shaded intervals. By default, they are 50 percent transparent. Other Parameters ---------------- **kwargs Additional parameters for seaborn.FacetGrid. Returns ------- g : seaborn.FacetGrid """ if self.parameters_info['hierarchical_levels'] == 2: cols = self.parameters_info['group_parameters_names_transf'] else: cols = self.parameters_info['parameters_names_transf'] dfm = pd.melt(self.samples[cols], value_vars=cols) g = sns.FacetGrid(dfm, col="variable", col_wrap=self.parameters_info['n_parameters_individual'], sharex=False, **kwargs) g.map(plotting.plot_posterior, "value", gridsize=gridsize, clip=clip, show_intervals=show_intervals, alpha_intervals=alpha_intervals, intervals_kws=intervals_kws) return g
[ "numpy.mean", "pickle.dump", "re.compile", "numpy.log", "os.getcwd", "numpy.exp", "numpy.sum", "numpy.array", "pandas.unique", "pandas.melt", "numpy.var", "seaborn.FacetGrid" ]
[((6053, 6075), 'numpy.exp', 'np.exp', (['log_likelihood'], {}), '(log_likelihood)\n', (6059, 6075), True, 'import numpy as np\n'), ((6094, 6121), 'numpy.mean', 'np.mean', (['likelihood'], {'axis': '(0)'}), '(likelihood, axis=0)\n', (6101, 6121), True, 'import numpy as np\n'), ((6165, 6179), 'numpy.log', 'np.log', (['mean_l'], {}), '(mean_l)\n', (6171, 6179), True, 'import numpy as np\n'), ((6195, 6217), 'numpy.sum', 'np.sum', (['pointwise_lppd'], {}), '(pointwise_lppd)\n', (6201, 6217), True, 'import numpy as np\n'), ((6245, 6275), 'numpy.var', 'np.var', (['log_likelihood'], {'axis': '(0)'}), '(log_likelihood, axis=0)\n', (6251, 6275), True, 'import numpy as np\n'), ((6309, 6332), 'numpy.sum', 'np.sum', (['pointwise_var_l'], {}), '(pointwise_var_l)\n', (6315, 6332), True, 'import numpy as np\n'), ((8790, 8801), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (8799, 8801), False, 'import os\n'), ((11137, 11181), 'pandas.melt', 'pd.melt', (['self.samples[cols]'], {'value_vars': 'cols'}), '(self.samples[cols], value_vars=cols)\n', (11144, 11181), True, 'import pandas as pd\n'), ((11194, 11315), 'seaborn.FacetGrid', 'sns.FacetGrid', (['dfm'], {'col': '"""variable"""', 'col_wrap': "self.parameters_info['n_parameters_individual']", 'sharex': '(False)'}), "(dfm, col='variable', col_wrap=self.parameters_info[\n 'n_parameters_individual'], sharex=False, **kwargs)\n", (11207, 11315), True, 'import seaborn as sns\n'), ((1961, 1984), 're.compile', 're.compile', (['"""transf_.+"""'], {}), "('transf_.+')\n", (1971, 1984), False, 'import re\n'), ((2179, 2198), 're.compile', 're.compile', (['"""mu_.+"""'], {}), "('mu_.+')\n", (2189, 2198), False, 'import re\n'), ((2298, 2317), 're.compile', 're.compile', (['"""sd_.+"""'], {}), "('sd_.+')\n", (2308, 2317), False, 'import re\n'), ((2629, 2655), 're.compile', 're.compile', (['"""z_.+_trial.+"""'], {}), "('z_.+_trial.+')\n", (2639, 2655), False, 'import re\n'), ((2754, 2772), 're.compile', 're.compile', (['"""z_.+"""'], {}), "('z_.+')\n", (2764, 2772), False, 'import re\n'), ((3838, 3861), 're.compile', 're.compile', (['"""transf_.+"""'], {}), "('transf_.+')\n", (3848, 3861), False, 'import re\n'), ((4043, 4069), 're.compile', 're.compile', (['"""z_.+_trial.+"""'], {}), "('z_.+_trial.+')\n", (4053, 4069), False, 'import re\n'), ((9067, 9087), 'pickle.dump', 'pickle.dump', (['self', 'f'], {}), '(self, f)\n', (9078, 9087), False, 'import pickle\n'), ((6480, 6502), 'numpy.var', 'np.var', (['pointwise_waic'], {}), '(pointwise_waic)\n', (6486, 6502), True, 'import numpy as np\n'), ((5098, 5126), 'numpy.array', 'np.array', (["summary['summary']"], {}), "(summary['summary'])\n", (5106, 5126), True, 'import numpy as np\n'), ((1679, 1706), 'pandas.unique', 'pd.unique', (['data.participant'], {}), '(data.participant)\n', (1688, 1706), True, 'import pandas as pd\n')]
import torch import random import torchvision.transforms as transforms import numpy as np import cv2 from poissonblending import blend from multiprocessing import Process, Queue, Pool import time import sys def gen_input_mask(shape, position, w_h): """ * inputs: - shape (sequence, required): Shape of a mask tensor to be generated. A sequence of length 4 (N, C, H, W) is assumed. - hole_size (sequence or int, required): Size of holes created in a mask. If a sequence of length 4 is provided, holes of size (W, H) = ( hole_size[0][0] <= hole_size[0][1], hole_size[1][0] <= hole_size[1][1], ) are generated. All the pixel values within holes are filled with 1.0. - hole_area (sequence, optional): This argument constraints the area where holes are generated. hole_area[0] is the left corner (X, Y) of the area, while hole_area[1] is its width and height (W, H). This area is used as the input region of Local discriminator. The default value is None. - max_holes (int, optional): This argument specifies how many holes are generated. The number of holes is randomly chosen from [1, max_holes]. The default value is 1. * returns: A mask tensor of shape [N, C, H, W] with holes. All the pixel values within holes are filled with 1.0, while the other pixel values are zeros. """ mask = torch.zeros(shape) bsize, _, mask_h, mask_w = mask.shape # for i in range(bsize): # n_holes = random.choice(list(range(1, max_holes+1))) # for _ in range(n_holes): # # choose patch width # if isinstance(hole_size[0], tuple) and len(hole_size[0]) == 2: # hole_w = random.randint(hole_size[0][0], hole_size[0][1]) # else: # hole_w = hole_size[0] # # choose patch height # if isinstance(hole_size[1], tuple) and len(hole_size[1]) == 2: # hole_h = random.randint(hole_size[1][0], hole_size[1][1]) # else: # hole_h = hole_size[1] # # choose offset upper-left coordinate # if hole_area: # harea_xmin, harea_ymin = hole_area[0] # harea_w, harea_h = hole_area[1] # offset_x = random.randint(harea_xmin, harea_xmin + harea_w - hole_w) # offset_y = random.randint(harea_ymin, harea_ymin + harea_h - hole_h) # else: # offset_x = random.randint(0, mask_w - hole_w) # offset_y = random.randint(0, mask_h - hole_h) # mask[i, :, offset_y : offset_y + hole_h, offset_x : offset_x + hole_w] = 1.0 # return mask def gen_hole_area(size, mask_size): """ * inputs: - size (sequence, required) A sequence of length 2 (W, H) is assumed. (W, H) is the size of hole area. - mask_size (sequence, required) A sequence of length 2 (W, H) is assumed. (W, H) is the size of input mask. * returns: A sequence used for the input argument 'hole_area' for function 'gen_input_mask'. """ mask_w, mask_h = mask_size harea_w, harea_h = size offset_x = random.randint(0, mask_w - harea_w) offset_y = random.randint(0, mask_h - harea_h) return ((offset_x, offset_y), (harea_w, harea_h)) def crop(x, area): """ * inputs: - x (torch.Tensor, required) A torch tensor of shape (N, C, H, W) is assumed. - area (sequence, required) A sequence of length 2 ((X, Y), (W, H)) is assumed. sequence[0] (X, Y) is the left corner of an area to be cropped. sequence[1] (W, H) is its width and height. * returns: A torch tensor of shape (N, C, H, W) cropped in the specified area. """ xmin, ymin = area[0] w, h = area[1] return x[:, :, ymin : ymin + h, xmin : xmin + w] def sample_random_batch(dataset, batch_size=32): """ * inputs: - dataset (torch.utils.data.Dataset, required) An instance of torch.utils.data.Dataset. - batch_size (int, optional) Batch size. * returns: A mini-batch randomly sampled from the input dataset. """ num_samples = len(dataset) batch1 = [] batch2 = [] batch3 = [] for _ in range(min(batch_size, num_samples)): index = random.choice(range(0, num_samples)) x1 = torch.unsqueeze(dataset[index][0], dim=0) x2 = torch.unsqueeze(dataset[index][1], dim=0) x3 = torch.unsqueeze(dataset[index][2], dim=0) batch1.append(x1) batch2.append(x2) batch3.append(x3) return torch.cat(batch1, dim=0), torch.cat(batch2, dim=0), torch.cat(batch3, dim=0) def poisson_blend(x, output, mask): """ * inputs: - x (torch.Tensor, required) Input image tensor of shape (N, 3, H, W). - output (torch.Tensor, required) Output tensor from Completion Network of shape (N, 3, H, W). - mask (torch.Tensor, required) Input mask tensor of shape (N, 1, H, W). * returns: An image tensor of shape (N, 3, H, W) inpainted using poisson image editing method. """ x = x.clone().cpu() output = output.clone().cpu() mask = mask.clone().cpu() #mask = torch.cat((mask,mask,mask), dim=1) # convert to 3-channel format num_samples = x.shape[0] ret = [] for i in range(num_samples): dstimg = transforms.functional.to_pil_image(x[i]) dstimg = np.array(dstimg)[:, :, [2, 1, 0]] srcimg = transforms.functional.to_pil_image(output[i]) srcimg = np.array(srcimg)[:, :, [2, 1, 0]] msk = transforms.functional.to_pil_image(mask[i]) msk = np.array(msk)[:, :, [2, 1, 0]] # compute mask's center # xs, ys = [], [] # for i in range(msk.shape[0]): # for j in range(msk.shape[1]): # if msk[i,j,0] == 255: # ys.append(i) # xs.append(j) # xmin, xmax = min(xs), max(xs) # ymin, ymax = min(ys), max(ys) # center = ((xmax + xmin) // 2, (ymax + ymin) // 2) center = (320,240) out = cv2.seamlessClone(srcimg, dstimg, msk, center, cv2.NORMAL_CLONE) out = out[:, :, [2, 1, 0]] out = transforms.functional.to_tensor(out) out = torch.unsqueeze(out, dim=0) ret.append(out) ret = torch.cat(ret, dim=0) return ret ######################################################################################## def pb(data): print("mm") x, output, mask = data dstimg = transforms.functional.to_pil_image(x) print("mmm") dstimg = np.array(dstimg)[:, :, [2, 1, 0]] srcimg = transforms.functional.to_pil_image(output) print("mmmm") srcimg = np.array(srcimg)[:, :, [2, 1, 0]] msk = transforms.functional.to_pil_image(mask) msk = np.array(msk)[:, :, [2, 1, 0]] print("mmm") center = (320,240) out = cv2.seamlessClone(srcimg, dstimg, msk, center, cv2.NORMAL_CLONE) out = out[:, :, [2, 1, 0]] out = transforms.functional.to_tensor(out) out = torch.unsqueeze(out, dim=0) print("kk") #q.put([i, out]) return out def poisson_blend_m(x, output, mask): q_input = Queue() q_output = Queue() x = x.clone().cpu() output = output.clone().cpu() mask = mask.clone().cpu() #mask = torch.cat((mask,mask,mask), dim=1) # convert to 3-channel format num_samples = x.shape[0] ret = [] # for i in range(num_samples): # #print('>>>', x[i]) # p = Process(target=pb, args=(q_output, [i, x[i], output[i], mask[i]])) # p.daemon = True # p.start() # p.join() # print("join") # print("Done") # for i in range(num_samples): # print("<in") # ret.append(q_output.get()) # print("in") # print(ret) # ret = sorted(ret, key=lambda x: x[0]) # ret = [i[1:] for i in ret] # with Pool(4) as p: # ret = p.map(pb, ([[x[i], output[i], mask[i] ] for i in range(num_samples)])) # ret = [result[0] for result in ret] # print(ret) pool = Pool(4) results = pool.map_async(pb, [[x[i], output[i], mask[i]] for i in range(num_samples)], chunksize=1) #pool.close() #pool.join() ret = results.get() ret = torch.cat(ret, dim=0) return ret # def reader_proc(queue): # ## Read from the queue; this will be spawned as a separate Process # while True: # msg = queue.get() # Read from the queue and do nothing # if (msg == 'DONE'): # break # def writer(count, queue): # ## Write to the queue # for ii in range(0, count): # queue.put(ii) # Write 'count' numbers into the queue # queue.put('DONE') # if __name__=='__main__': # pqueue = Queue() # writer() writes to pqueue from _this_ process # for count in [10**4, 10**5, 10**6]: # ### reader_proc() reads from pqueue as a separate process # reader_p = Process(target=reader_proc, args=((pqueue),)) # reader_p.daemon = True # reader_p.start() # Launch reader_proc() as a separate python process # _start = time.time() # writer(count, pqueue) # Send a lot of stuff to reader() # reader_p.join() # Wait for the reader to finish # print("Sending {0} numbers to Queue() took {1} seconds".format(count, # (time.time() - _start))) ######################################################################################## def poisson_blend_old(input, output, mask): """ * inputs: - input (torch.Tensor, required) Input tensor of Completion Network. - output (torch.Tensor, required) Output tensor of Completion Network. - mask (torch.Tensor, required) Input mask tensor of Completion Network. * returns: Image tensor inpainted using poisson image editing method. """ num_samples = input.shape[0] ret = [] # convert torch array to numpy array followed by # converting 'channel first' format to 'channel last' format. input_np = np.transpose(np.copy(input.cpu().numpy()), axes=(0, 2, 3, 1)) output_np = np.transpose(np.copy(output.cpu().numpy()), axes=(0, 2, 3, 1)) mask_np = np.transpose(np.copy(mask.cpu().numpy()), axes=(0, 2, 3, 1)) # apply poisson image editing method for each input/output image and mask. for i in range(num_samples): inpainted_np = blend(input_np[i], output_np[i], mask_np[i]) inpainted = torch.from_numpy(np.transpose(inpainted_np, axes=(2, 0, 1))) inpainted = torch.unsqueeze(inpainted, dim=0) ret.append(inpainted) ret = torch.cat(ret, dim=0) return ret
[ "torchvision.transforms.functional.to_tensor", "torchvision.transforms.functional.to_pil_image", "cv2.seamlessClone", "torch.unsqueeze", "numpy.array", "multiprocessing.Pool", "torch.zeros", "multiprocessing.Queue", "numpy.transpose", "random.randint", "torch.cat", "poissonblending.blend" ]
[((1654, 1672), 'torch.zeros', 'torch.zeros', (['shape'], {}), '(shape)\n', (1665, 1672), False, 'import torch\n'), ((3503, 3538), 'random.randint', 'random.randint', (['(0)', '(mask_w - harea_w)'], {}), '(0, mask_w - harea_w)\n', (3517, 3538), False, 'import random\n'), ((3554, 3589), 'random.randint', 'random.randint', (['(0)', '(mask_h - harea_h)'], {}), '(0, mask_h - harea_h)\n', (3568, 3589), False, 'import random\n'), ((6821, 6842), 'torch.cat', 'torch.cat', (['ret'], {'dim': '(0)'}), '(ret, dim=0)\n', (6830, 6842), False, 'import torch\n'), ((7019, 7056), 'torchvision.transforms.functional.to_pil_image', 'transforms.functional.to_pil_image', (['x'], {}), '(x)\n', (7053, 7056), True, 'import torchvision.transforms as transforms\n'), ((7134, 7176), 'torchvision.transforms.functional.to_pil_image', 'transforms.functional.to_pil_image', (['output'], {}), '(output)\n', (7168, 7176), True, 'import torchvision.transforms as transforms\n'), ((7252, 7292), 'torchvision.transforms.functional.to_pil_image', 'transforms.functional.to_pil_image', (['mask'], {}), '(mask)\n', (7286, 7292), True, 'import torchvision.transforms as transforms\n'), ((7384, 7448), 'cv2.seamlessClone', 'cv2.seamlessClone', (['srcimg', 'dstimg', 'msk', 'center', 'cv2.NORMAL_CLONE'], {}), '(srcimg, dstimg, msk, center, cv2.NORMAL_CLONE)\n', (7401, 7448), False, 'import cv2\n'), ((7490, 7526), 'torchvision.transforms.functional.to_tensor', 'transforms.functional.to_tensor', (['out'], {}), '(out)\n', (7521, 7526), True, 'import torchvision.transforms as transforms\n'), ((7537, 7564), 'torch.unsqueeze', 'torch.unsqueeze', (['out'], {'dim': '(0)'}), '(out, dim=0)\n', (7552, 7564), False, 'import torch\n'), ((7675, 7682), 'multiprocessing.Queue', 'Queue', ([], {}), '()\n', (7680, 7682), False, 'from multiprocessing import Process, Queue, Pool\n'), ((7698, 7705), 'multiprocessing.Queue', 'Queue', ([], {}), '()\n', (7703, 7705), False, 'from multiprocessing import Process, Queue, Pool\n'), ((8604, 8611), 'multiprocessing.Pool', 'Pool', (['(4)'], {}), '(4)\n', (8608, 8611), False, 'from multiprocessing import Process, Queue, Pool\n'), ((8803, 8824), 'torch.cat', 'torch.cat', (['ret'], {'dim': '(0)'}), '(ret, dim=0)\n', (8812, 8824), False, 'import torch\n'), ((11259, 11280), 'torch.cat', 'torch.cat', (['ret'], {'dim': '(0)'}), '(ret, dim=0)\n', (11268, 11280), False, 'import torch\n'), ((4767, 4808), 'torch.unsqueeze', 'torch.unsqueeze', (['dataset[index][0]'], {'dim': '(0)'}), '(dataset[index][0], dim=0)\n', (4782, 4808), False, 'import torch\n'), ((4822, 4863), 'torch.unsqueeze', 'torch.unsqueeze', (['dataset[index][1]'], {'dim': '(0)'}), '(dataset[index][1], dim=0)\n', (4837, 4863), False, 'import torch\n'), ((4877, 4918), 'torch.unsqueeze', 'torch.unsqueeze', (['dataset[index][2]'], {'dim': '(0)'}), '(dataset[index][2], dim=0)\n', (4892, 4918), False, 'import torch\n'), ((5008, 5032), 'torch.cat', 'torch.cat', (['batch1'], {'dim': '(0)'}), '(batch1, dim=0)\n', (5017, 5032), False, 'import torch\n'), ((5034, 5058), 'torch.cat', 'torch.cat', (['batch2'], {'dim': '(0)'}), '(batch2, dim=0)\n', (5043, 5058), False, 'import torch\n'), ((5060, 5084), 'torch.cat', 'torch.cat', (['batch3'], {'dim': '(0)'}), '(batch3, dim=0)\n', (5069, 5084), False, 'import torch\n'), ((5852, 5892), 'torchvision.transforms.functional.to_pil_image', 'transforms.functional.to_pil_image', (['x[i]'], {}), '(x[i])\n', (5886, 5892), True, 'import torchvision.transforms as transforms\n'), ((5961, 6006), 'torchvision.transforms.functional.to_pil_image', 'transforms.functional.to_pil_image', (['output[i]'], {}), '(output[i])\n', (5995, 6006), True, 'import torchvision.transforms as transforms\n'), ((6072, 6115), 'torchvision.transforms.functional.to_pil_image', 'transforms.functional.to_pil_image', (['mask[i]'], {}), '(mask[i])\n', (6106, 6115), True, 'import torchvision.transforms as transforms\n'), ((6594, 6658), 'cv2.seamlessClone', 'cv2.seamlessClone', (['srcimg', 'dstimg', 'msk', 'center', 'cv2.NORMAL_CLONE'], {}), '(srcimg, dstimg, msk, center, cv2.NORMAL_CLONE)\n', (6611, 6658), False, 'import cv2\n'), ((6708, 6744), 'torchvision.transforms.functional.to_tensor', 'transforms.functional.to_tensor', (['out'], {}), '(out)\n', (6739, 6744), True, 'import torchvision.transforms as transforms\n'), ((6759, 6786), 'torch.unsqueeze', 'torch.unsqueeze', (['out'], {'dim': '(0)'}), '(out, dim=0)\n', (6774, 6786), False, 'import torch\n'), ((7087, 7103), 'numpy.array', 'np.array', (['dstimg'], {}), '(dstimg)\n', (7095, 7103), True, 'import numpy as np\n'), ((7208, 7224), 'numpy.array', 'np.array', (['srcimg'], {}), '(srcimg)\n', (7216, 7224), True, 'import numpy as np\n'), ((7303, 7316), 'numpy.array', 'np.array', (['msk'], {}), '(msk)\n', (7311, 7316), True, 'import numpy as np\n'), ((11039, 11083), 'poissonblending.blend', 'blend', (['input_np[i]', 'output_np[i]', 'mask_np[i]'], {}), '(input_np[i], output_np[i], mask_np[i])\n', (11044, 11083), False, 'from poissonblending import blend\n'), ((11185, 11218), 'torch.unsqueeze', 'torch.unsqueeze', (['inpainted'], {'dim': '(0)'}), '(inpainted, dim=0)\n', (11200, 11218), False, 'import torch\n'), ((5910, 5926), 'numpy.array', 'np.array', (['dstimg'], {}), '(dstimg)\n', (5918, 5926), True, 'import numpy as np\n'), ((6024, 6040), 'numpy.array', 'np.array', (['srcimg'], {}), '(srcimg)\n', (6032, 6040), True, 'import numpy as np\n'), ((6130, 6143), 'numpy.array', 'np.array', (['msk'], {}), '(msk)\n', (6138, 6143), True, 'import numpy as np\n'), ((11121, 11163), 'numpy.transpose', 'np.transpose', (['inpainted_np'], {'axes': '(2, 0, 1)'}), '(inpainted_np, axes=(2, 0, 1))\n', (11133, 11163), True, 'import numpy as np\n')]
"""Train spoken word classifier and test on Flickr-Audio one-shot speech task. Author: <NAME> Contact: <EMAIL> Date: October 2019 """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import datetime import functools import os import time from absl import app from absl import flags from absl import logging import numpy as np import tensorflow as tf from sklearn.preprocessing import LabelBinarizer from tqdm import tqdm from moonshot.baselines import base from moonshot.baselines import dataset from moonshot.baselines import davenet from moonshot.baselines import experiment from moonshot.baselines import losses from moonshot.baselines import model_utils from moonshot.experiments.flickr_speech import flickr_speech from moonshot.utils import file_io from moonshot.utils import logging as logging_utils FLAGS = flags.FLAGS # model options (default if not loaded) DEFAULT_OPTIONS = { # training data "features": "mfcc", # one of ["mfcc", "fbank"] "one_shot_validation": True, # preprocessing "max_length": 140, # length to pad/crop segments "scaling": None, # one of ["global", "features", "segment", "segment_mean"] # data pipeline "batch_size": 32, # DAVEnet spoken word classifier "batch_norm_spectrogram": True, "batch_norm_conv": True, "downsample": True, "embedding_dim": 1024, "padding": "same", "dense_units": [2048], # hidden layers on top of DAVEnet base network (followed by logits) "dropout_rate": 0.2, # objective "cross_entropy_label_smoothing": 0.1, # training "learning_rate": 3e-4, "decay_steps": 4000, # TODO # slightly less than two epochs "decay_rate": 0.96, "gradient_clip_norm": 5., "epochs": 100, # that magic number "seed": 42 } # one-shot evaluation options flags.DEFINE_integer("episodes", 400, "number of L-way K-shot learning episodes") flags.DEFINE_integer("L", 10, "number of classes to sample in a task episode (L-way)") flags.DEFINE_integer("K", 1, "number of task learning samples per class (K-shot)") flags.DEFINE_integer("N", 15, "number of task evaluation samples") flags.DEFINE_integer("k_neighbours", 1, "number of nearest neighbours to consider") flags.DEFINE_string("metric", "cosine", "distance metric to use for DTW nearest neighbours") flags.DEFINE_integer("fine_tune_steps", None, "number of fine-tune gradient steps on one-shot data") flags.DEFINE_float("fine_tune_lr", 1e-3, "learning rate for gradient descent fine-tune") flags.DEFINE_bool("classification", False, "whether to use softmax predictions as match function" "(requires fine-tuning of new logits layer)") flags.DEFINE_enum("speaker_mode", "baseline", ["baseline", "difficult", "distractor"], "type of speakers selected in a task episode") # model train/test options flags.DEFINE_enum("embed_layer", "dense", ["avg_pool", "dense", "logits", "softmax"], "model layer to extract embeddings from") flags.DEFINE_bool("load_best", False, "load previous best model for resumed training or testing") flags.DEFINE_bool("mc_dropout", False, "make embedding predictions with MC Dropout") # logging and target options flags.DEFINE_enum("target", "train", ["train", "validate", "embed", "test"], "train or load and test a model") flags.DEFINE_string("output_dir", None, "directory where logs and checkpoints will be stored" "(defaults to logs/<unique run id>)") flags.DEFINE_bool("resume", True, "resume training if a checkpoint is found at output directory") flags.DEFINE_bool("tensorboard", True, "log train and test summaries to TensorBoard") flags.DEFINE_bool("debug", False, "log with debug verbosity level") def get_training_objective(model_options): """Get training loss for spoken word classification.""" loss = tf.keras.losses.CategoricalCrossentropy( from_logits=True, label_smoothing=model_options["cross_entropy_label_smoothing"]) return loss def get_data_preprocess_func(model_options): """Create data batch preprocessing function for input to the speech network. Returns function `data_preprocess_func` that takes a batch of file paths, loads speech features and preprocesses the features. """ def data_preprocess_func(speech_paths): speech_features = [] for speech_path in speech_paths: speech_features.append( dataset.load_and_preprocess_speech( speech_path, features=model_options["features"], max_length=model_options["max_length"], scaling=model_options["scaling"])) return np.stack(speech_features) return data_preprocess_func def create_speech_network(model_options, build_model=True): """Create spoken word classification model from model options.""" # get input shape input_shape = None if build_model: input_shape = model_options["input_shape"] # train DAVEnet audio base network from scratch davenet_audio_network = davenet.create_davenet_audio_network( input_shape=input_shape, batch_norm_spectrogram=model_options["batch_norm_spectrogram"], batch_norm_conv=model_options["batch_norm_conv"], downsample=model_options["downsample"], embedding_dim=model_options["embedding_dim"], padding=model_options["padding"]) model_layers = [ davenet_audio_network, tf.keras.layers.GlobalAveragePooling1D() ] if model_options["dropout_rate"] is not None: model_layers.append( tf.keras.layers.Dropout(model_options["dropout_rate"])) # add top layer hidden units if model_options["dense_units"] is not None: for dense_units in model_options["dense_units"]: model_layers.append(tf.keras.layers.Dense(dense_units)) model_layers.append(tf.keras.layers.ReLU()) if model_options["dropout_rate"] is not None: model_layers.append( tf.keras.layers.Dropout(model_options["dropout_rate"])) # add final class logits layer model_layers.append(tf.keras.layers.Dense(model_options["n_classes"])) speech_network = tf.keras.Sequential(model_layers) if build_model: speech_network.summary() return speech_network def create_embedding_model(model_options, speech_network): """Create embedding model from speech network.""" # slice embedding model from specified layer if FLAGS.embed_layer == "avg_pool": # global average pool layer slice_index = 1 elif FLAGS.embed_layer == "dense": # dense layer before relu & logits layer slice_index = -3 if model_options["dropout_rate"] is None else -4 elif FLAGS.embed_layer == "logits": # unnormalised log probabilities slice_index = -1 elif FLAGS.embed_layer == "softmax": slice_index = -1 model_input = ( speech_network.layers[0].input if slice_index == 0 else speech_network.input) model_output = speech_network.layers[slice_index].output if FLAGS.embed_layer == "softmax": # softmax class probabilities model_output = tf.nn.softmax(model_output) embedding_network = tf.keras.Model(inputs=model_input, outputs=model_output) embedding_model = base.BaseModel( embedding_network, None, mc_dropout=FLAGS.mc_dropout) return embedding_model def create_fine_tune_model(model_options, speech_network, num_classes): """Create classification model for fine-tuning on unseen classes.""" # create clone of the speech network (so that it remains unchanged) speech_network_clone = model_utils.create_and_copy_model( speech_network, create_speech_network, model_options=model_options, build_model=True) # TODO: figure out how to get this working without build (for MAML inner loop) # freeze model layers up to dense layer before relu & logits layer if FLAGS.embed_layer == "dense": freeze_index = -3 if model_options["dropout_rate"] is None else -4 # freeze all model layers for transfer learning (except final logits) else: freeze_index = -1 for layer in speech_network_clone.layers[:freeze_index]: layer.trainable = False # replace the logits layer with categorical logits layer for unseen classes model_outputs = speech_network_clone.layers[-2].output model_outputs = tf.keras.layers.Dense(num_classes)(model_outputs) fine_tune_network = tf.keras.Model( inputs=speech_network_clone.input, outputs=model_outputs) fine_tune_loss = tf.keras.losses.SparseCategoricalCrossentropy( from_logits=True) few_shot_model = base.BaseModel( fine_tune_network, fine_tune_loss, mc_dropout=FLAGS.mc_dropout) return few_shot_model def train(model_options, output_dir, model_file=None, model_step_file=None, tf_writer=None): """Create and train spoken word classification model for one-shot learning.""" # load training data train_exp, dev_exp = dataset.create_flickr_audio_train_data( model_options["features"], speaker_mode=FLAGS.speaker_mode) train_labels = [] for keyword in train_exp.keywords_set[3]: label = train_exp.keyword_labels[keyword] train_labels.append(label) train_labels = np.asarray(train_labels) dev_labels = [] for keyword in dev_exp.keywords_set[3]: label = train_exp.keyword_labels[keyword] dev_labels.append(label) dev_labels = np.asarray(dev_labels) train_paths = train_exp.audio_paths dev_paths = dev_exp.audio_paths lb = LabelBinarizer() train_labels_one_hot = lb.fit_transform(train_labels) dev_labels_one_hot = lb.transform(dev_labels) # define preprocessing for speech features preprocess_speech_func = functools.partial( dataset.load_and_preprocess_speech, features=model_options["features"], max_length=model_options["max_length"], scaling=model_options["scaling"]) preprocess_speech_ds_func = lambda path: tf.py_function( func=preprocess_speech_func, inp=[path], Tout=tf.float32) # create standard training dataset pipeline background_train_ds = tf.data.Dataset.zip(( tf.data.Dataset.from_tensor_slices(train_paths), tf.data.Dataset.from_tensor_slices(train_labels_one_hot))) # map data preprocessing function across training data background_train_ds = background_train_ds.map( lambda path, label: (preprocess_speech_ds_func(path), label), num_parallel_calls=tf.data.experimental.AUTOTUNE) # shuffle and batch train data background_train_ds = background_train_ds.shuffle(1000) background_train_ds = background_train_ds.batch( model_options["batch_size"]) background_train_ds = background_train_ds.prefetch( tf.data.experimental.AUTOTUNE) # create dev set pipeline for classification validation background_dev_ds = tf.data.Dataset.zip(( tf.data.Dataset.from_tensor_slices( dev_paths).map(preprocess_speech_ds_func), tf.data.Dataset.from_tensor_slices(dev_labels_one_hot))) background_dev_ds = background_dev_ds.batch( batch_size=model_options["batch_size"]) # write example batch to TensorBoard if tf_writer is not None: logging.log(logging.INFO, "Writing example features to TensorBoard") with tf_writer.as_default(): for x_batch, y_batch in background_train_ds.take(1): speech_feats = [] for feats in x_batch[:30]: feats = np.transpose(feats) speech_feats.append( (feats - np.min(feats)) / np.max(feats)) tf.summary.image( f"Example train speech {model_options['features']}", np.expand_dims(speech_feats, axis=-1), max_outputs=30, step=0) labels = "" for i, label in enumerate(y_batch[:30]): labels += f"{i}: {np.asarray(train_exp.keywords)[label]} " tf.summary.text("Example train labels", labels, step=0) # get training objective loss = get_training_objective(model_options) # get model input shape if model_options["features"] == "mfcc": model_options["input_shape"] = [model_options["max_length"], 39] else: model_options["input_shape"] = [model_options["max_length"], 40] # load or create model if model_file is not None: assert model_options["n_classes"] == len(train_exp.keywords) speech_network, train_state = model_utils.load_model( model_file=os.path.join(output_dir, model_file), model_step_file=os.path.join(output_dir, model_step_file), loss=loss) # get previous tracking variables initial_model = False global_step, model_epochs, _, best_val_score = train_state else: model_options["n_classes"] = len(train_exp.keywords) speech_network = create_speech_network(model_options) # create tracking variables initial_model = True global_step = 0 model_epochs = 0 if model_options["one_shot_validation"]: best_val_score = -np.inf else: best_val_score = np.inf # load or create Adam optimizer with decayed learning rate lr_schedule = tf.keras.optimizers.schedules.ExponentialDecay( model_options["learning_rate"], decay_rate=model_options["decay_rate"], decay_steps=model_options["decay_steps"], staircase=True) if model_file is not None: logging.log(logging.INFO, "Restoring optimizer state") optimizer = speech_network.optimizer else: optimizer = tf.keras.optimizers.Adam(learning_rate=lr_schedule) # compile model to store optimizer with model when saving speech_network.compile(optimizer=optimizer, loss=loss) # create few-shot model from speech network for background training speech_few_shot_model = base.BaseModel(speech_network, loss) # test model on one-shot validation task prior to training if model_options["one_shot_validation"]: one_shot_dev_exp = flickr_speech.FlickrSpeech( features=model_options["features"], keywords_split="background_dev", preprocess_func=get_data_preprocess_func(model_options), speaker_mode=FLAGS.speaker_mode) embedding_model_func = lambda speech_network: create_embedding_model( model_options, speech_network) classification = False if FLAGS.classification: assert FLAGS.embed_layer in ["logits", "softmax"] classification = True # create few-shot model from speech network for one-shot validation if FLAGS.fine_tune_steps is not None: test_few_shot_model = create_fine_tune_model( model_options, speech_few_shot_model.model, num_classes=FLAGS.L) else: test_few_shot_model = base.BaseModel( speech_few_shot_model.model, None, mc_dropout=FLAGS.mc_dropout) val_task_accuracy, _, conf_interval_95 = experiment.test_l_way_k_shot( one_shot_dev_exp, FLAGS.K, FLAGS.L, n=FLAGS.N, num_episodes=FLAGS.episodes, k_neighbours=FLAGS.k_neighbours, metric=FLAGS.metric, classification=classification, model=test_few_shot_model, embedding_model_func=embedding_model_func, fine_tune_steps=FLAGS.fine_tune_steps, fine_tune_lr=FLAGS.fine_tune_lr) logging.log( logging.INFO, f"Base model: {FLAGS.L}-way {FLAGS.K}-shot accuracy after " f"{FLAGS.episodes} episodes: {val_task_accuracy:.3%} +- " f"{conf_interval_95*100:.4f}") # create training metrics accuracy_metric = tf.keras.metrics.CategoricalAccuracy() loss_metric = tf.keras.metrics.Mean() best_model = False # store model options on first run if initial_model: file_io.write_json( os.path.join(output_dir, "model_options.json"), model_options) # train model for epoch in range(model_epochs, model_options["epochs"]): logging.log(logging.INFO, f"Epoch {epoch:03d}") accuracy_metric.reset_states() loss_metric.reset_states() # train on epoch of training data step_pbar = tqdm(background_train_ds, bar_format="{desc} [{elapsed},{rate_fmt}{postfix}]") for step, (x_batch, y_batch) in enumerate(step_pbar): loss_value, y_predict = speech_few_shot_model.train_step( x_batch, y_batch, optimizer, clip_norm=model_options["gradient_clip_norm"]) accuracy_metric.update_state(y_batch, y_predict) loss_metric.update_state(loss_value) step_loss = tf.reduce_mean(loss_value) train_loss = loss_metric.result().numpy() train_accuracy = accuracy_metric.result().numpy() step_pbar.set_description_str( f"\tStep {step:03d}: " f"Step loss: {step_loss:.6f}, " f"Loss: {train_loss:.6f}, " f"Categorical accuracy: {train_accuracy:.3%}") if tf_writer is not None: with tf_writer.as_default(): tf.summary.scalar( "Train step loss", step_loss, step=global_step) global_step += 1 # validate classification model accuracy_metric.reset_states() loss_metric.reset_states() for x_batch, y_batch in background_dev_ds: y_predict = speech_few_shot_model.predict(x_batch, training=False) loss_value = speech_few_shot_model.loss(y_batch, y_predict) accuracy_metric.update_state(y_batch, y_predict) loss_metric.update_state(loss_value) dev_loss = loss_metric.result().numpy() dev_accuracy = accuracy_metric.result().numpy() # validate model on one-shot dev task if specified if model_options["one_shot_validation"]: if FLAGS.fine_tune_steps is not None: test_few_shot_model = create_fine_tune_model( model_options, speech_few_shot_model.model, num_classes=FLAGS.L) else: test_few_shot_model = base.BaseModel( speech_few_shot_model.model, None, mc_dropout=FLAGS.mc_dropout) val_task_accuracy, _, conf_interval_95 = experiment.test_l_way_k_shot( one_shot_dev_exp, FLAGS.K, FLAGS.L, n=FLAGS.N, num_episodes=FLAGS.episodes, k_neighbours=FLAGS.k_neighbours, metric=FLAGS.metric, classification=classification, model=test_few_shot_model, embedding_model_func=embedding_model_func, fine_tune_steps=FLAGS.fine_tune_steps, fine_tune_lr=FLAGS.fine_tune_lr) val_score = val_task_accuracy val_metric = f"{FLAGS.L}-way {FLAGS.K}-shot accuracy" # otherwise, validate on classification task else: val_score = dev_accuracy val_metric = "categorical accuracy" if val_score >= best_val_score: best_val_score = val_score best_model = True # log results logging.log( logging.INFO, f"Train: Loss: {train_loss:.6f}, Categorical accuracy: " f"{train_accuracy:.3%}") logging.log( logging.INFO, f"Validation: Loss: {dev_loss:.6f}, Categorical accuracy: " f"{dev_accuracy:.3%} {'*' if best_model else ''}") if model_options["one_shot_validation"]: logging.log( logging.INFO, f"Validation: {FLAGS.L}-way {FLAGS.K}-shot accuracy after " f"{FLAGS.episodes} episodes: {val_task_accuracy:.3%} +- " f"{conf_interval_95*100:.4f} {'*' if best_model else ''}") if tf_writer is not None: with tf_writer.as_default(): tf.summary.scalar( "Train step loss", train_loss, step=global_step) tf.summary.scalar( "Train categorical accuracy", train_accuracy, step=global_step) tf.summary.scalar( "Validation loss", dev_loss, step=global_step) tf.summary.scalar( "Validation categorical accuracy", dev_accuracy, step=global_step) if model_options["one_shot_validation"]: tf.summary.scalar( f"Validation {FLAGS.L}-way {FLAGS.K}-shot accuracy", val_task_accuracy, step=global_step) # store model and results model_utils.save_model( speech_few_shot_model.model, output_dir, epoch + 1, global_step, val_metric, val_score, best_val_score, name="model") if best_model: best_model = False model_utils.save_model( speech_few_shot_model.model, output_dir, epoch + 1, global_step, val_metric, val_score, best_val_score, name="best_model") def embed(model_options, output_dir, model_file, model_step_file): """Load spoken word classification model and extract embeddings.""" # load model speech_network, _ = model_utils.load_model( model_file=os.path.join(output_dir, model_file), model_step_file=os.path.join(output_dir, model_step_file), loss=get_training_objective(model_options)) # get embedding model and data preprocessing embedding_model = create_embedding_model(model_options, speech_network) data_preprocess_func = get_data_preprocess_func(model_options) # load Flickr Audio dataset and compute embeddings one_shot_exp = flickr_speech.FlickrSpeech( features=model_options["features"], keywords_split="one_shot_evaluation") background_train_exp = flickr_speech.FlickrSpeech( features=model_options["features"], keywords_split="background_train") background_dev_exp = flickr_speech.FlickrSpeech( features=model_options["features"], keywords_split="background_dev") subset_exp = { "one_shot_evaluation": one_shot_exp, "background_train": background_train_exp, "background_dev": background_dev_exp, } for subset, exp in subset_exp.items(): embed_dir = os.path.join( output_dir, "embed", FLAGS.embed_layer, "flickr_audio", subset) file_io.check_create_dir(embed_dir) unique_paths = np.unique(exp.audio_paths) # batch audio paths for faster embedding inference path_ds = tf.data.Dataset.from_tensor_slices(unique_paths) path_ds = path_ds.batch(model_options["batch_size"]) path_ds = path_ds.prefetch(tf.data.experimental.AUTOTUNE) num_samples = int( np.ceil(len(unique_paths) / model_options["batch_size"])) start_time = time.time() paths, embeddings = [], [] for path_batch in tqdm(path_ds, total=num_samples): path_embeddings = embedding_model.predict( data_preprocess_func(path_batch)) paths.extend(path_batch.numpy()) embeddings.extend(path_embeddings.numpy()) end_time = time.time() logging.log( logging.INFO, f"Computed embeddings ({FLAGS.embed_layer}) for Flickr Audio " f"{subset} in {end_time - start_time:.4f} seconds") # serialize and write embeddings to TFRecord files for path, embedding in zip(paths, embeddings): example_proto = dataset.embedding_to_example_protobuf(embedding) path = path.decode("utf-8") path = os.path.join( embed_dir, f"{os.path.split(path)[1]}.tfrecord") with tf.io.TFRecordWriter(path, options="ZLIB") as writer: writer.write(example_proto.SerializeToString()) logging.log(logging.INFO, f"Embeddings stored at: {embed_dir}") def test(model_options, output_dir, model_file, model_step_file): """Load and test spoken word classification model for one-shot learning.""" # load Flickr Audio one-shot experiment one_shot_exp = flickr_speech.FlickrSpeech( features=model_options["features"], keywords_split="one_shot_evaluation", preprocess_func=get_data_preprocess_func(model_options), speaker_mode=FLAGS.speaker_mode) # load model speech_network, _ = model_utils.load_model( model_file=os.path.join(output_dir, model_file), model_step_file=os.path.join(output_dir, model_step_file), loss=get_training_objective(model_options)) embedding_model_func = lambda speech_network: create_embedding_model( model_options, speech_network) # create few-shot model from speech network for one-shot testing if FLAGS.fine_tune_steps is not None: test_few_shot_model = create_fine_tune_model( model_options, speech_network, num_classes=FLAGS.L) else: test_few_shot_model = base.BaseModel( speech_network, None, mc_dropout=FLAGS.mc_dropout) classification = False if FLAGS.classification: assert FLAGS.embed_layer in ["logits", "softmax"] classification = True logging.log(logging.INFO, "Created few-shot model from speech network") test_few_shot_model.model.summary() # test model on L-way K-shot task task_accuracy, _, conf_interval_95 = experiment.test_l_way_k_shot( one_shot_exp, FLAGS.K, FLAGS.L, n=FLAGS.N, num_episodes=FLAGS.episodes, k_neighbours=FLAGS.k_neighbours, metric=FLAGS.metric, classification=classification, model=test_few_shot_model, embedding_model_func=embedding_model_func, fine_tune_steps=FLAGS.fine_tune_steps, fine_tune_lr=FLAGS.fine_tune_lr) logging.log( logging.INFO, f"{FLAGS.L}-way {FLAGS.K}-shot accuracy after {FLAGS.episodes} " f"episodes: {task_accuracy:.3%} +- {conf_interval_95*100:.4f}") def main(argv): del argv # unused logging.log(logging.INFO, "Logging application {}".format(__file__)) if FLAGS.debug: logging.set_verbosity(logging.DEBUG) logging.log(logging.DEBUG, "Running in debug mode") physical_devices = tf.config.experimental.list_physical_devices("GPU") tf.config.experimental.set_memory_growth(physical_devices[0], True) model_found = False # no prior run specified, train model if FLAGS.output_dir is None: if FLAGS.target != "train": raise ValueError( "Target `{FLAGS.target}` requires --output_dir to be specified.") output_dir = os.path.join( "logs", __file__, datetime.datetime.now().strftime("%Y%m%d-%H%M%S")) file_io.check_create_dir(output_dir) model_options = DEFAULT_OPTIONS # prior run specified, resume training or test model else: output_dir = FLAGS.output_dir # load current or best model model_file = "best_model.h5" if FLAGS.load_best else "model.h5" model_step_file = "best_model.step" if FLAGS.load_best else "model.step" if os.path.exists(os.path.join(output_dir, model_file)): model_found = True model_options = file_io.read_json( os.path.join(output_dir, "model_options.json")) elif FLAGS.target != "train": raise ValueError( f"Target `{FLAGS.target}` specified but `{model_file}` not " f"found in {output_dir}.") # gather flag options flag_options = {} for flag in FLAGS.get_key_flags_for_module(__file__): flag_options[flag.name] = flag.value # logging logging_utils.absl_file_logger(output_dir, f"log.{FLAGS.target}") logging.log(logging.INFO, f"Model directory: {output_dir}") logging.log(logging.INFO, f"Model options: {model_options}") logging.log(logging.INFO, f"Flag options: {flag_options}") tf_writer = None if FLAGS.tensorboard and FLAGS.target == "train": tf_writer = tf.summary.create_file_writer(output_dir) # set seeds for reproducibility np.random.seed(model_options["seed"]) tf.random.set_seed(model_options["seed"]) # run target if FLAGS.target == "train": if model_found and FLAGS.resume: train(model_options, output_dir, model_file=model_file, model_step_file=model_step_file, tf_writer=tf_writer) else: train(model_options, output_dir, tf_writer=tf_writer) elif FLAGS.target == "validate": # TODO raise NotImplementedError elif FLAGS.target == "embed": embed(model_options, output_dir, model_file, model_step_file) else: test(model_options, output_dir, model_file, model_step_file) if __name__ == "__main__": app.run(main)
[ "tensorflow.keras.layers.Dense", "absl.logging.log", "tensorflow.nn.softmax", "moonshot.baselines.model_utils.save_model", "tensorflow.keras.losses.CategoricalCrossentropy", "tensorflow.reduce_mean", "absl.flags.DEFINE_enum", "absl.flags.DEFINE_float", "moonshot.utils.logging.absl_file_logger", "s...
[((1873, 1958), 'absl.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""episodes"""', '(400)', '"""number of L-way K-shot learning episodes"""'], {}), "('episodes', 400,\n 'number of L-way K-shot learning episodes')\n", (1893, 1958), False, 'from absl import flags\n'), ((1955, 2045), 'absl.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""L"""', '(10)', '"""number of classes to sample in a task episode (L-way)"""'], {}), "('L', 10,\n 'number of classes to sample in a task episode (L-way)')\n", (1975, 2045), False, 'from absl import flags\n'), ((2042, 2128), 'absl.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""K"""', '(1)', '"""number of task learning samples per class (K-shot)"""'], {}), "('K', 1,\n 'number of task learning samples per class (K-shot)')\n", (2062, 2128), False, 'from absl import flags\n'), ((2125, 2191), 'absl.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""N"""', '(15)', '"""number of task evaluation samples"""'], {}), "('N', 15, 'number of task evaluation samples')\n", (2145, 2191), False, 'from absl import flags\n'), ((2192, 2279), 'absl.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""k_neighbours"""', '(1)', '"""number of nearest neighbours to consider"""'], {}), "('k_neighbours', 1,\n 'number of nearest neighbours to consider')\n", (2212, 2279), False, 'from absl import flags\n'), ((2276, 2372), 'absl.flags.DEFINE_string', 'flags.DEFINE_string', (['"""metric"""', '"""cosine"""', '"""distance metric to use for DTW nearest neighbours"""'], {}), "('metric', 'cosine',\n 'distance metric to use for DTW nearest neighbours')\n", (2295, 2372), False, 'from absl import flags\n'), ((2369, 2473), 'absl.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""fine_tune_steps"""', 'None', '"""number of fine-tune gradient steps on one-shot data"""'], {}), "('fine_tune_steps', None,\n 'number of fine-tune gradient steps on one-shot data')\n", (2389, 2473), False, 'from absl import flags\n'), ((2470, 2563), 'absl.flags.DEFINE_float', 'flags.DEFINE_float', (['"""fine_tune_lr"""', '(0.001)', '"""learning rate for gradient descent fine-tune"""'], {}), "('fine_tune_lr', 0.001,\n 'learning rate for gradient descent fine-tune')\n", (2488, 2563), False, 'from absl import flags\n'), ((2559, 2708), 'absl.flags.DEFINE_bool', 'flags.DEFINE_bool', (['"""classification"""', '(False)', '"""whether to use softmax predictions as match function(requires fine-tuning of new logits layer)"""'], {}), "('classification', False,\n 'whether to use softmax predictions as match function(requires fine-tuning of new logits layer)'\n )\n", (2576, 2708), False, 'from absl import flags\n'), ((2721, 2858), 'absl.flags.DEFINE_enum', 'flags.DEFINE_enum', (['"""speaker_mode"""', '"""baseline"""', "['baseline', 'difficult', 'distractor']", '"""type of speakers selected in a task episode"""'], {}), "('speaker_mode', 'baseline', ['baseline', 'difficult',\n 'distractor'], 'type of speakers selected in a task episode')\n", (2738, 2858), False, 'from absl import flags\n'), ((2901, 3032), 'absl.flags.DEFINE_enum', 'flags.DEFINE_enum', (['"""embed_layer"""', '"""dense"""', "['avg_pool', 'dense', 'logits', 'softmax']", '"""model layer to extract embeddings from"""'], {}), "('embed_layer', 'dense', ['avg_pool', 'dense', 'logits',\n 'softmax'], 'model layer to extract embeddings from')\n", (2918, 3032), False, 'from absl import flags\n'), ((3047, 3148), 'absl.flags.DEFINE_bool', 'flags.DEFINE_bool', (['"""load_best"""', '(False)', '"""load previous best model for resumed training or testing"""'], {}), "('load_best', False,\n 'load previous best model for resumed training or testing')\n", (3064, 3148), False, 'from absl import flags\n'), ((3145, 3233), 'absl.flags.DEFINE_bool', 'flags.DEFINE_bool', (['"""mc_dropout"""', '(False)', '"""make embedding predictions with MC Dropout"""'], {}), "('mc_dropout', False,\n 'make embedding predictions with MC Dropout')\n", (3162, 3233), False, 'from absl import flags\n'), ((3260, 3374), 'absl.flags.DEFINE_enum', 'flags.DEFINE_enum', (['"""target"""', '"""train"""', "['train', 'validate', 'embed', 'test']", '"""train or load and test a model"""'], {}), "('target', 'train', ['train', 'validate', 'embed', 'test'],\n 'train or load and test a model')\n", (3277, 3374), False, 'from absl import flags\n'), ((3389, 3526), 'absl.flags.DEFINE_string', 'flags.DEFINE_string', (['"""output_dir"""', 'None', '"""directory where logs and checkpoints will be stored(defaults to logs/<unique run id>)"""'], {}), "('output_dir', None,\n 'directory where logs and checkpoints will be stored(defaults to logs/<unique run id>)'\n )\n", (3408, 3526), False, 'from absl import flags\n'), ((3541, 3642), 'absl.flags.DEFINE_bool', 'flags.DEFINE_bool', (['"""resume"""', '(True)', '"""resume training if a checkpoint is found at output directory"""'], {}), "('resume', True,\n 'resume training if a checkpoint is found at output directory')\n", (3558, 3642), False, 'from absl import flags\n'), ((3639, 3728), 'absl.flags.DEFINE_bool', 'flags.DEFINE_bool', (['"""tensorboard"""', '(True)', '"""log train and test summaries to TensorBoard"""'], {}), "('tensorboard', True,\n 'log train and test summaries to TensorBoard')\n", (3656, 3728), False, 'from absl import flags\n'), ((3725, 3792), 'absl.flags.DEFINE_bool', 'flags.DEFINE_bool', (['"""debug"""', '(False)', '"""log with debug verbosity level"""'], {}), "('debug', False, 'log with debug verbosity level')\n", (3742, 3792), False, 'from absl import flags\n'), ((3910, 4036), 'tensorflow.keras.losses.CategoricalCrossentropy', 'tf.keras.losses.CategoricalCrossentropy', ([], {'from_logits': '(True)', 'label_smoothing': "model_options['cross_entropy_label_smoothing']"}), "(from_logits=True, label_smoothing=\n model_options['cross_entropy_label_smoothing'])\n", (3949, 4036), True, 'import tensorflow as tf\n'), ((5130, 5443), 'moonshot.baselines.davenet.create_davenet_audio_network', 'davenet.create_davenet_audio_network', ([], {'input_shape': 'input_shape', 'batch_norm_spectrogram': "model_options['batch_norm_spectrogram']", 'batch_norm_conv': "model_options['batch_norm_conv']", 'downsample': "model_options['downsample']", 'embedding_dim': "model_options['embedding_dim']", 'padding': "model_options['padding']"}), "(input_shape=input_shape,\n batch_norm_spectrogram=model_options['batch_norm_spectrogram'],\n batch_norm_conv=model_options['batch_norm_conv'], downsample=\n model_options['downsample'], embedding_dim=model_options[\n 'embedding_dim'], padding=model_options['padding'])\n", (5166, 5443), False, 'from moonshot.baselines import davenet\n'), ((6302, 6335), 'tensorflow.keras.Sequential', 'tf.keras.Sequential', (['model_layers'], {}), '(model_layers)\n', (6321, 6335), True, 'import tensorflow as tf\n'), ((7319, 7375), 'tensorflow.keras.Model', 'tf.keras.Model', ([], {'inputs': 'model_input', 'outputs': 'model_output'}), '(inputs=model_input, outputs=model_output)\n', (7333, 7375), True, 'import tensorflow as tf\n'), ((7399, 7467), 'moonshot.baselines.base.BaseModel', 'base.BaseModel', (['embedding_network', 'None'], {'mc_dropout': 'FLAGS.mc_dropout'}), '(embedding_network, None, mc_dropout=FLAGS.mc_dropout)\n', (7413, 7467), False, 'from moonshot.baselines import base\n'), ((7752, 7875), 'moonshot.baselines.model_utils.create_and_copy_model', 'model_utils.create_and_copy_model', (['speech_network', 'create_speech_network'], {'model_options': 'model_options', 'build_model': '(True)'}), '(speech_network, create_speech_network,\n model_options=model_options, build_model=True)\n', (7785, 7875), False, 'from moonshot.baselines import model_utils\n'), ((8592, 8664), 'tensorflow.keras.Model', 'tf.keras.Model', ([], {'inputs': 'speech_network_clone.input', 'outputs': 'model_outputs'}), '(inputs=speech_network_clone.input, outputs=model_outputs)\n', (8606, 8664), True, 'import tensorflow as tf\n'), ((8696, 8759), 'tensorflow.keras.losses.SparseCategoricalCrossentropy', 'tf.keras.losses.SparseCategoricalCrossentropy', ([], {'from_logits': '(True)'}), '(from_logits=True)\n', (8741, 8759), True, 'import tensorflow as tf\n'), ((8791, 8869), 'moonshot.baselines.base.BaseModel', 'base.BaseModel', (['fine_tune_network', 'fine_tune_loss'], {'mc_dropout': 'FLAGS.mc_dropout'}), '(fine_tune_network, fine_tune_loss, mc_dropout=FLAGS.mc_dropout)\n', (8805, 8869), False, 'from moonshot.baselines import base\n'), ((9145, 9247), 'moonshot.baselines.dataset.create_flickr_audio_train_data', 'dataset.create_flickr_audio_train_data', (["model_options['features']"], {'speaker_mode': 'FLAGS.speaker_mode'}), "(model_options['features'],\n speaker_mode=FLAGS.speaker_mode)\n", (9183, 9247), False, 'from moonshot.baselines import dataset\n'), ((9426, 9450), 'numpy.asarray', 'np.asarray', (['train_labels'], {}), '(train_labels)\n', (9436, 9450), True, 'import numpy as np\n'), ((9616, 9638), 'numpy.asarray', 'np.asarray', (['dev_labels'], {}), '(dev_labels)\n', (9626, 9638), True, 'import numpy as np\n'), ((9726, 9742), 'sklearn.preprocessing.LabelBinarizer', 'LabelBinarizer', ([], {}), '()\n', (9740, 9742), False, 'from sklearn.preprocessing import LabelBinarizer\n'), ((9928, 10100), 'functools.partial', 'functools.partial', (['dataset.load_and_preprocess_speech'], {'features': "model_options['features']", 'max_length': "model_options['max_length']", 'scaling': "model_options['scaling']"}), "(dataset.load_and_preprocess_speech, features=\n model_options['features'], max_length=model_options['max_length'],\n scaling=model_options['scaling'])\n", (9945, 10100), False, 'import functools\n'), ((13531, 13717), 'tensorflow.keras.optimizers.schedules.ExponentialDecay', 'tf.keras.optimizers.schedules.ExponentialDecay', (["model_options['learning_rate']"], {'decay_rate': "model_options['decay_rate']", 'decay_steps': "model_options['decay_steps']", 'staircase': '(True)'}), "(model_options[\n 'learning_rate'], decay_rate=model_options['decay_rate'], decay_steps=\n model_options['decay_steps'], staircase=True)\n", (13577, 13717), True, 'import tensorflow as tf\n'), ((14170, 14206), 'moonshot.baselines.base.BaseModel', 'base.BaseModel', (['speech_network', 'loss'], {}), '(speech_network, loss)\n', (14184, 14206), False, 'from moonshot.baselines import base\n'), ((16021, 16059), 'tensorflow.keras.metrics.CategoricalAccuracy', 'tf.keras.metrics.CategoricalAccuracy', ([], {}), '()\n', (16057, 16059), True, 'import tensorflow as tf\n'), ((16078, 16101), 'tensorflow.keras.metrics.Mean', 'tf.keras.metrics.Mean', ([], {}), '()\n', (16099, 16101), True, 'import tensorflow as tf\n'), ((22113, 22217), 'moonshot.experiments.flickr_speech.flickr_speech.FlickrSpeech', 'flickr_speech.FlickrSpeech', ([], {'features': "model_options['features']", 'keywords_split': '"""one_shot_evaluation"""'}), "(features=model_options['features'],\n keywords_split='one_shot_evaluation')\n", (22139, 22217), False, 'from moonshot.experiments.flickr_speech import flickr_speech\n'), ((22259, 22360), 'moonshot.experiments.flickr_speech.flickr_speech.FlickrSpeech', 'flickr_speech.FlickrSpeech', ([], {'features': "model_options['features']", 'keywords_split': '"""background_train"""'}), "(features=model_options['features'],\n keywords_split='background_train')\n", (22285, 22360), False, 'from moonshot.experiments.flickr_speech import flickr_speech\n'), ((22392, 22491), 'moonshot.experiments.flickr_speech.flickr_speech.FlickrSpeech', 'flickr_speech.FlickrSpeech', ([], {'features': "model_options['features']", 'keywords_split': '"""background_dev"""'}), "(features=model_options['features'],\n keywords_split='background_dev')\n", (22418, 22491), False, 'from moonshot.experiments.flickr_speech import flickr_speech\n'), ((25649, 25720), 'absl.logging.log', 'logging.log', (['logging.INFO', '"""Created few-shot model from speech network"""'], {}), "(logging.INFO, 'Created few-shot model from speech network')\n", (25660, 25720), False, 'from absl import logging\n'), ((25841, 26186), 'moonshot.baselines.experiment.test_l_way_k_shot', 'experiment.test_l_way_k_shot', (['one_shot_exp', 'FLAGS.K', 'FLAGS.L'], {'n': 'FLAGS.N', 'num_episodes': 'FLAGS.episodes', 'k_neighbours': 'FLAGS.k_neighbours', 'metric': 'FLAGS.metric', 'classification': 'classification', 'model': 'test_few_shot_model', 'embedding_model_func': 'embedding_model_func', 'fine_tune_steps': 'FLAGS.fine_tune_steps', 'fine_tune_lr': 'FLAGS.fine_tune_lr'}), '(one_shot_exp, FLAGS.K, FLAGS.L, n=FLAGS.N,\n num_episodes=FLAGS.episodes, k_neighbours=FLAGS.k_neighbours, metric=\n FLAGS.metric, classification=classification, model=test_few_shot_model,\n embedding_model_func=embedding_model_func, fine_tune_steps=FLAGS.\n fine_tune_steps, fine_tune_lr=FLAGS.fine_tune_lr)\n', (25869, 26186), False, 'from moonshot.baselines import experiment\n'), ((26215, 26376), 'absl.logging.log', 'logging.log', (['logging.INFO', 'f"""{FLAGS.L}-way {FLAGS.K}-shot accuracy after {FLAGS.episodes} episodes: {task_accuracy:.3%} +- {conf_interval_95 * 100:.4f}"""'], {}), "(logging.INFO,\n f'{FLAGS.L}-way {FLAGS.K}-shot accuracy after {FLAGS.episodes} episodes: {task_accuracy:.3%} +- {conf_interval_95 * 100:.4f}'\n )\n", (26226, 26376), False, 'from absl import logging\n'), ((26659, 26710), 'tensorflow.config.experimental.list_physical_devices', 'tf.config.experimental.list_physical_devices', (['"""GPU"""'], {}), "('GPU')\n", (26703, 26710), True, 'import tensorflow as tf\n'), ((26715, 26782), 'tensorflow.config.experimental.set_memory_growth', 'tf.config.experimental.set_memory_growth', (['physical_devices[0]', '(True)'], {}), '(physical_devices[0], True)\n', (26755, 26782), True, 'import tensorflow as tf\n'), ((28100, 28165), 'moonshot.utils.logging.absl_file_logger', 'logging_utils.absl_file_logger', (['output_dir', 'f"""log.{FLAGS.target}"""'], {}), "(output_dir, f'log.{FLAGS.target}')\n", (28130, 28165), True, 'from moonshot.utils import logging as logging_utils\n'), ((28171, 28230), 'absl.logging.log', 'logging.log', (['logging.INFO', 'f"""Model directory: {output_dir}"""'], {}), "(logging.INFO, f'Model directory: {output_dir}')\n", (28182, 28230), False, 'from absl import logging\n'), ((28235, 28295), 'absl.logging.log', 'logging.log', (['logging.INFO', 'f"""Model options: {model_options}"""'], {}), "(logging.INFO, f'Model options: {model_options}')\n", (28246, 28295), False, 'from absl import logging\n'), ((28300, 28358), 'absl.logging.log', 'logging.log', (['logging.INFO', 'f"""Flag options: {flag_options}"""'], {}), "(logging.INFO, f'Flag options: {flag_options}')\n", (28311, 28358), False, 'from absl import logging\n'), ((28538, 28575), 'numpy.random.seed', 'np.random.seed', (["model_options['seed']"], {}), "(model_options['seed'])\n", (28552, 28575), True, 'import numpy as np\n'), ((28580, 28621), 'tensorflow.random.set_seed', 'tf.random.set_seed', (["model_options['seed']"], {}), "(model_options['seed'])\n", (28598, 28621), True, 'import tensorflow as tf\n'), ((29228, 29241), 'absl.app.run', 'app.run', (['main'], {}), '(main)\n', (29235, 29241), False, 'from absl import app\n'), ((4741, 4766), 'numpy.stack', 'np.stack', (['speech_features'], {}), '(speech_features)\n', (4749, 4766), True, 'import numpy as np\n'), ((5536, 5576), 'tensorflow.keras.layers.GlobalAveragePooling1D', 'tf.keras.layers.GlobalAveragePooling1D', ([], {}), '()\n', (5574, 5576), True, 'import tensorflow as tf\n'), ((6229, 6278), 'tensorflow.keras.layers.Dense', 'tf.keras.layers.Dense', (["model_options['n_classes']"], {}), "(model_options['n_classes'])\n", (6250, 6278), True, 'import tensorflow as tf\n'), ((7266, 7293), 'tensorflow.nn.softmax', 'tf.nn.softmax', (['model_output'], {}), '(model_output)\n', (7279, 7293), True, 'import tensorflow as tf\n'), ((8517, 8551), 'tensorflow.keras.layers.Dense', 'tf.keras.layers.Dense', (['num_classes'], {}), '(num_classes)\n', (8538, 8551), True, 'import tensorflow as tf\n'), ((10163, 10235), 'tensorflow.py_function', 'tf.py_function', ([], {'func': 'preprocess_speech_func', 'inp': '[path]', 'Tout': 'tf.float32'}), '(func=preprocess_speech_func, inp=[path], Tout=tf.float32)\n', (10177, 10235), True, 'import tensorflow as tf\n'), ((11437, 11505), 'absl.logging.log', 'logging.log', (['logging.INFO', '"""Writing example features to TensorBoard"""'], {}), "(logging.INFO, 'Writing example features to TensorBoard')\n", (11448, 11505), False, 'from absl import logging\n'), ((13765, 13819), 'absl.logging.log', 'logging.log', (['logging.INFO', '"""Restoring optimizer state"""'], {}), "(logging.INFO, 'Restoring optimizer state')\n", (13776, 13819), False, 'from absl import logging\n'), ((13895, 13946), 'tensorflow.keras.optimizers.Adam', 'tf.keras.optimizers.Adam', ([], {'learning_rate': 'lr_schedule'}), '(learning_rate=lr_schedule)\n', (13919, 13946), True, 'import tensorflow as tf\n'), ((15318, 15667), 'moonshot.baselines.experiment.test_l_way_k_shot', 'experiment.test_l_way_k_shot', (['one_shot_dev_exp', 'FLAGS.K', 'FLAGS.L'], {'n': 'FLAGS.N', 'num_episodes': 'FLAGS.episodes', 'k_neighbours': 'FLAGS.k_neighbours', 'metric': 'FLAGS.metric', 'classification': 'classification', 'model': 'test_few_shot_model', 'embedding_model_func': 'embedding_model_func', 'fine_tune_steps': 'FLAGS.fine_tune_steps', 'fine_tune_lr': 'FLAGS.fine_tune_lr'}), '(one_shot_dev_exp, FLAGS.K, FLAGS.L, n=FLAGS.N,\n num_episodes=FLAGS.episodes, k_neighbours=FLAGS.k_neighbours, metric=\n FLAGS.metric, classification=classification, model=test_few_shot_model,\n embedding_model_func=embedding_model_func, fine_tune_steps=FLAGS.\n fine_tune_steps, fine_tune_lr=FLAGS.fine_tune_lr)\n', (15346, 15667), False, 'from moonshot.baselines import experiment\n'), ((15744, 15921), 'absl.logging.log', 'logging.log', (['logging.INFO', 'f"""Base model: {FLAGS.L}-way {FLAGS.K}-shot accuracy after {FLAGS.episodes} episodes: {val_task_accuracy:.3%} +- {conf_interval_95 * 100:.4f}"""'], {}), "(logging.INFO,\n f'Base model: {FLAGS.L}-way {FLAGS.K}-shot accuracy after {FLAGS.episodes} episodes: {val_task_accuracy:.3%} +- {conf_interval_95 * 100:.4f}'\n )\n", (15755, 15921), False, 'from absl import logging\n'), ((16380, 16427), 'absl.logging.log', 'logging.log', (['logging.INFO', 'f"""Epoch {epoch:03d}"""'], {}), "(logging.INFO, f'Epoch {epoch:03d}')\n", (16391, 16427), False, 'from absl import logging\n'), ((16566, 16644), 'tqdm.tqdm', 'tqdm', (['background_train_ds'], {'bar_format': '"""{desc} [{elapsed},{rate_fmt}{postfix}]"""'}), "(background_train_ds, bar_format='{desc} [{elapsed},{rate_fmt}{postfix}]')\n", (16570, 16644), False, 'from tqdm import tqdm\n'), ((19591, 19703), 'absl.logging.log', 'logging.log', (['logging.INFO', 'f"""Train: Loss: {train_loss:.6f}, Categorical accuracy: {train_accuracy:.3%}"""'], {}), "(logging.INFO,\n f'Train: Loss: {train_loss:.6f}, Categorical accuracy: {train_accuracy:.3%}'\n )\n", (19602, 19703), False, 'from absl import logging\n'), ((19745, 19886), 'absl.logging.log', 'logging.log', (['logging.INFO', 'f"""Validation: Loss: {dev_loss:.6f}, Categorical accuracy: {dev_accuracy:.3%} {\'*\' if best_model else \'\'}"""'], {}), '(logging.INFO,\n f"Validation: Loss: {dev_loss:.6f}, Categorical accuracy: {dev_accuracy:.3%} {\'*\' if best_model else \'\'}"\n )\n', (19756, 19886), False, 'from absl import logging\n'), ((21049, 21193), 'moonshot.baselines.model_utils.save_model', 'model_utils.save_model', (['speech_few_shot_model.model', 'output_dir', '(epoch + 1)', 'global_step', 'val_metric', 'val_score', 'best_val_score'], {'name': '"""model"""'}), "(speech_few_shot_model.model, output_dir, epoch + 1,\n global_step, val_metric, val_score, best_val_score, name='model')\n", (21071, 21193), False, 'from moonshot.baselines import model_utils\n'), ((22728, 22804), 'os.path.join', 'os.path.join', (['output_dir', '"""embed"""', 'FLAGS.embed_layer', '"""flickr_audio"""', 'subset'], {}), "(output_dir, 'embed', FLAGS.embed_layer, 'flickr_audio', subset)\n", (22740, 22804), False, 'import os\n'), ((22826, 22861), 'moonshot.utils.file_io.check_create_dir', 'file_io.check_create_dir', (['embed_dir'], {}), '(embed_dir)\n', (22850, 22861), False, 'from moonshot.utils import file_io\n'), ((22886, 22912), 'numpy.unique', 'np.unique', (['exp.audio_paths'], {}), '(exp.audio_paths)\n', (22895, 22912), True, 'import numpy as np\n'), ((22991, 23039), 'tensorflow.data.Dataset.from_tensor_slices', 'tf.data.Dataset.from_tensor_slices', (['unique_paths'], {}), '(unique_paths)\n', (23025, 23039), True, 'import tensorflow as tf\n'), ((23287, 23298), 'time.time', 'time.time', ([], {}), '()\n', (23296, 23298), False, 'import time\n'), ((23360, 23392), 'tqdm.tqdm', 'tqdm', (['path_ds'], {'total': 'num_samples'}), '(path_ds, total=num_samples)\n', (23364, 23392), False, 'from tqdm import tqdm\n'), ((23619, 23630), 'time.time', 'time.time', ([], {}), '()\n', (23628, 23630), False, 'import time\n'), ((23640, 23785), 'absl.logging.log', 'logging.log', (['logging.INFO', 'f"""Computed embeddings ({FLAGS.embed_layer}) for Flickr Audio {subset} in {end_time - start_time:.4f} seconds"""'], {}), "(logging.INFO,\n f'Computed embeddings ({FLAGS.embed_layer}) for Flickr Audio {subset} in {end_time - start_time:.4f} seconds'\n )\n", (23651, 23785), False, 'from absl import logging\n'), ((24294, 24357), 'absl.logging.log', 'logging.log', (['logging.INFO', 'f"""Embeddings stored at: {embed_dir}"""'], {}), "(logging.INFO, f'Embeddings stored at: {embed_dir}')\n", (24305, 24357), False, 'from absl import logging\n'), ((25420, 25485), 'moonshot.baselines.base.BaseModel', 'base.BaseModel', (['speech_network', 'None'], {'mc_dropout': 'FLAGS.mc_dropout'}), '(speech_network, None, mc_dropout=FLAGS.mc_dropout)\n', (25434, 25485), False, 'from moonshot.baselines import base\n'), ((26538, 26574), 'absl.logging.set_verbosity', 'logging.set_verbosity', (['logging.DEBUG'], {}), '(logging.DEBUG)\n', (26559, 26574), False, 'from absl import logging\n'), ((26583, 26634), 'absl.logging.log', 'logging.log', (['logging.DEBUG', '"""Running in debug mode"""'], {}), "(logging.DEBUG, 'Running in debug mode')\n", (26594, 26634), False, 'from absl import logging\n'), ((27156, 27192), 'moonshot.utils.file_io.check_create_dir', 'file_io.check_create_dir', (['output_dir'], {}), '(output_dir)\n', (27180, 27192), False, 'from moonshot.utils import file_io\n'), ((28455, 28496), 'tensorflow.summary.create_file_writer', 'tf.summary.create_file_writer', (['output_dir'], {}), '(output_dir)\n', (28484, 28496), True, 'import tensorflow as tf\n'), ((5675, 5729), 'tensorflow.keras.layers.Dropout', 'tf.keras.layers.Dropout', (["model_options['dropout_rate']"], {}), "(model_options['dropout_rate'])\n", (5698, 5729), True, 'import tensorflow as tf\n'), ((10350, 10397), 'tensorflow.data.Dataset.from_tensor_slices', 'tf.data.Dataset.from_tensor_slices', (['train_paths'], {}), '(train_paths)\n', (10384, 10397), True, 'import tensorflow as tf\n'), ((10407, 10463), 'tensorflow.data.Dataset.from_tensor_slices', 'tf.data.Dataset.from_tensor_slices', (['train_labels_one_hot'], {}), '(train_labels_one_hot)\n', (10441, 10463), True, 'import tensorflow as tf\n'), ((11202, 11256), 'tensorflow.data.Dataset.from_tensor_slices', 'tf.data.Dataset.from_tensor_slices', (['dev_labels_one_hot'], {}), '(dev_labels_one_hot)\n', (11236, 11256), True, 'import tensorflow as tf\n'), ((15172, 15250), 'moonshot.baselines.base.BaseModel', 'base.BaseModel', (['speech_few_shot_model.model', 'None'], {'mc_dropout': 'FLAGS.mc_dropout'}), '(speech_few_shot_model.model, None, mc_dropout=FLAGS.mc_dropout)\n', (15186, 15250), False, 'from moonshot.baselines import base\n'), ((16227, 16273), 'os.path.join', 'os.path.join', (['output_dir', '"""model_options.json"""'], {}), "(output_dir, 'model_options.json')\n", (16239, 16273), False, 'import os\n'), ((17047, 17073), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['loss_value'], {}), '(loss_value)\n', (17061, 17073), True, 'import tensorflow as tf\n'), ((18743, 19092), 'moonshot.baselines.experiment.test_l_way_k_shot', 'experiment.test_l_way_k_shot', (['one_shot_dev_exp', 'FLAGS.K', 'FLAGS.L'], {'n': 'FLAGS.N', 'num_episodes': 'FLAGS.episodes', 'k_neighbours': 'FLAGS.k_neighbours', 'metric': 'FLAGS.metric', 'classification': 'classification', 'model': 'test_few_shot_model', 'embedding_model_func': 'embedding_model_func', 'fine_tune_steps': 'FLAGS.fine_tune_steps', 'fine_tune_lr': 'FLAGS.fine_tune_lr'}), '(one_shot_dev_exp, FLAGS.K, FLAGS.L, n=FLAGS.N,\n num_episodes=FLAGS.episodes, k_neighbours=FLAGS.k_neighbours, metric=\n FLAGS.metric, classification=classification, model=test_few_shot_model,\n embedding_model_func=embedding_model_func, fine_tune_steps=FLAGS.\n fine_tune_steps, fine_tune_lr=FLAGS.fine_tune_lr)\n', (18771, 19092), False, 'from moonshot.baselines import experiment\n'), ((19981, 20186), 'absl.logging.log', 'logging.log', (['logging.INFO', 'f"""Validation: {FLAGS.L}-way {FLAGS.K}-shot accuracy after {FLAGS.episodes} episodes: {val_task_accuracy:.3%} +- {conf_interval_95 * 100:.4f} {\'*\' if best_model else \'\'}"""'], {}), '(logging.INFO,\n f"Validation: {FLAGS.L}-way {FLAGS.K}-shot accuracy after {FLAGS.episodes} episodes: {val_task_accuracy:.3%} +- {conf_interval_95 * 100:.4f} {\'*\' if best_model else \'\'}"\n )\n', (19992, 20186), False, 'from absl import logging\n'), ((21283, 21432), 'moonshot.baselines.model_utils.save_model', 'model_utils.save_model', (['speech_few_shot_model.model', 'output_dir', '(epoch + 1)', 'global_step', 'val_metric', 'val_score', 'best_val_score'], {'name': '"""best_model"""'}), "(speech_few_shot_model.model, output_dir, epoch + 1,\n global_step, val_metric, val_score, best_val_score, name='best_model')\n", (21305, 21432), False, 'from moonshot.baselines import model_utils\n'), ((21688, 21724), 'os.path.join', 'os.path.join', (['output_dir', 'model_file'], {}), '(output_dir, model_file)\n', (21700, 21724), False, 'import os\n'), ((21750, 21791), 'os.path.join', 'os.path.join', (['output_dir', 'model_step_file'], {}), '(output_dir, model_step_file)\n', (21762, 21791), False, 'import os\n'), ((23961, 24009), 'moonshot.baselines.dataset.embedding_to_example_protobuf', 'dataset.embedding_to_example_protobuf', (['embedding'], {}), '(embedding)\n', (23998, 24009), False, 'from moonshot.baselines import dataset\n'), ((24879, 24915), 'os.path.join', 'os.path.join', (['output_dir', 'model_file'], {}), '(output_dir, model_file)\n', (24891, 24915), False, 'import os\n'), ((24941, 24982), 'os.path.join', 'os.path.join', (['output_dir', 'model_step_file'], {}), '(output_dir, model_step_file)\n', (24953, 24982), False, 'import os\n'), ((27558, 27594), 'os.path.join', 'os.path.join', (['output_dir', 'model_file'], {}), '(output_dir, model_file)\n', (27570, 27594), False, 'import os\n'), ((4505, 4672), 'moonshot.baselines.dataset.load_and_preprocess_speech', 'dataset.load_and_preprocess_speech', (['speech_path'], {'features': "model_options['features']", 'max_length': "model_options['max_length']", 'scaling': "model_options['scaling']"}), "(speech_path, features=model_options[\n 'features'], max_length=model_options['max_length'], scaling=\n model_options['scaling'])\n", (4539, 4672), False, 'from moonshot.baselines import dataset\n'), ((5904, 5938), 'tensorflow.keras.layers.Dense', 'tf.keras.layers.Dense', (['dense_units'], {}), '(dense_units)\n', (5925, 5938), True, 'import tensorflow as tf\n'), ((5973, 5995), 'tensorflow.keras.layers.ReLU', 'tf.keras.layers.ReLU', ([], {}), '()\n', (5993, 5995), True, 'import tensorflow as tf\n'), ((12213, 12268), 'tensorflow.summary.text', 'tf.summary.text', (['"""Example train labels"""', 'labels'], {'step': '(0)'}), "('Example train labels', labels, step=0)\n", (12228, 12268), True, 'import tensorflow as tf\n'), ((12791, 12827), 'os.path.join', 'os.path.join', (['output_dir', 'model_file'], {}), '(output_dir, model_file)\n', (12803, 12827), False, 'import os\n'), ((12857, 12898), 'os.path.join', 'os.path.join', (['output_dir', 'model_step_file'], {}), '(output_dir, model_step_file)\n', (12869, 12898), False, 'import os\n'), ((18569, 18647), 'moonshot.baselines.base.BaseModel', 'base.BaseModel', (['speech_few_shot_model.model', 'None'], {'mc_dropout': 'FLAGS.mc_dropout'}), '(speech_few_shot_model.model, None, mc_dropout=FLAGS.mc_dropout)\n', (18583, 18647), False, 'from moonshot.baselines import base\n'), ((20341, 20407), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""Train step loss"""', 'train_loss'], {'step': 'global_step'}), "('Train step loss', train_loss, step=global_step)\n", (20358, 20407), True, 'import tensorflow as tf\n'), ((20445, 20531), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""Train categorical accuracy"""', 'train_accuracy'], {'step': 'global_step'}), "('Train categorical accuracy', train_accuracy, step=\n global_step)\n", (20462, 20531), True, 'import tensorflow as tf\n'), ((20564, 20628), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""Validation loss"""', 'dev_loss'], {'step': 'global_step'}), "('Validation loss', dev_loss, step=global_step)\n", (20581, 20628), True, 'import tensorflow as tf\n'), ((20666, 20755), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""Validation categorical accuracy"""', 'dev_accuracy'], {'step': 'global_step'}), "('Validation categorical accuracy', dev_accuracy, step=\n global_step)\n", (20683, 20755), True, 'import tensorflow as tf\n'), ((24167, 24209), 'tensorflow.io.TFRecordWriter', 'tf.io.TFRecordWriter', (['path'], {'options': '"""ZLIB"""'}), "(path, options='ZLIB')\n", (24187, 24209), True, 'import tensorflow as tf\n'), ((27692, 27738), 'os.path.join', 'os.path.join', (['output_dir', '"""model_options.json"""'], {}), "(output_dir, 'model_options.json')\n", (27704, 27738), False, 'import os\n'), ((6113, 6167), 'tensorflow.keras.layers.Dropout', 'tf.keras.layers.Dropout', (["model_options['dropout_rate']"], {}), "(model_options['dropout_rate'])\n", (6136, 6167), True, 'import tensorflow as tf\n'), ((11103, 11148), 'tensorflow.data.Dataset.from_tensor_slices', 'tf.data.Dataset.from_tensor_slices', (['dev_paths'], {}), '(dev_paths)\n', (11137, 11148), True, 'import tensorflow as tf\n'), ((11714, 11733), 'numpy.transpose', 'np.transpose', (['feats'], {}), '(feats)\n', (11726, 11733), True, 'import numpy as np\n'), ((11968, 12005), 'numpy.expand_dims', 'np.expand_dims', (['speech_feats'], {'axis': '(-1)'}), '(speech_feats, axis=-1)\n', (11982, 12005), True, 'import numpy as np\n'), ((17532, 17597), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""Train step loss"""', 'step_loss'], {'step': 'global_step'}), "('Train step loss', step_loss, step=global_step)\n", (17549, 17597), True, 'import tensorflow as tf\n'), ((20849, 20960), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['f"""Validation {FLAGS.L}-way {FLAGS.K}-shot accuracy"""', 'val_task_accuracy'], {'step': 'global_step'}), "(f'Validation {FLAGS.L}-way {FLAGS.K}-shot accuracy',\n val_task_accuracy, step=global_step)\n", (20866, 20960), True, 'import tensorflow as tf\n'), ((27097, 27120), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (27118, 27120), False, 'import datetime\n'), ((11825, 11838), 'numpy.max', 'np.max', (['feats'], {}), '(feats)\n', (11831, 11838), True, 'import numpy as np\n'), ((24114, 24133), 'os.path.split', 'os.path.split', (['path'], {}), '(path)\n', (24127, 24133), False, 'import os\n'), ((11808, 11821), 'numpy.min', 'np.min', (['feats'], {}), '(feats)\n', (11814, 11821), True, 'import numpy as np\n'), ((12155, 12185), 'numpy.asarray', 'np.asarray', (['train_exp.keywords'], {}), '(train_exp.keywords)\n', (12165, 12185), True, 'import numpy as np\n')]
import numpy as np import state def estimate_tauW(): # Update tauW shape=state.N * state.n/2+1e-3 rate=np.sum((state.W-state.YHa)*(state.W-state.YHa))/2+1e-3 state.tauW=np.random.gamma(shape,1/rate,1) return()
[ "numpy.sum", "numpy.random.gamma" ]
[((192, 227), 'numpy.random.gamma', 'np.random.gamma', (['shape', '(1 / rate)', '(1)'], {}), '(shape, 1 / rate, 1)\n', (207, 227), True, 'import numpy as np\n'), ((117, 170), 'numpy.sum', 'np.sum', (['((state.W - state.YHa) * (state.W - state.YHa))'], {}), '((state.W - state.YHa) * (state.W - state.YHa))\n', (123, 170), True, 'import numpy as np\n')]
# class to help manage loading stored camera poses import numpy as np from director import transformUtils class CameraPoses(object): def __init__(self, posegraphFile=None): self.posegraphFile = posegraphFile if self.posegraphFile is not None: self.loadCameraPoses(posegraphFile) def loadCameraPoses(self, posegraphFile): data = np.loadtxt(posegraphFile) self.poseTimes = np.array(data[:,0]*1e6, dtype=int) self.poses = [] for pose in data[:,1:]: pos = pose[:3] quat = pose[6], pose[3], pose[4], pose[5] # quat data from file is ordered as x, y, z, w self.poses.append((pos, quat)) def getCameraPoseAtUTime(self, utime): idx = np.searchsorted(self.poseTimes, utime, side='left') if idx == len(self.poseTimes): idx = len(self.poseTimes) - 1 (pos, quat) = self.poses[idx] return transformUtils.transformFromPose(pos, quat)
[ "numpy.searchsorted", "numpy.array", "numpy.loadtxt", "director.transformUtils.transformFromPose" ]
[((379, 404), 'numpy.loadtxt', 'np.loadtxt', (['posegraphFile'], {}), '(posegraphFile)\n', (389, 404), True, 'import numpy as np\n'), ((430, 473), 'numpy.array', 'np.array', (['(data[:, 0] * 1000000.0)'], {'dtype': 'int'}), '(data[:, 0] * 1000000.0, dtype=int)\n', (438, 473), True, 'import numpy as np\n'), ((750, 801), 'numpy.searchsorted', 'np.searchsorted', (['self.poseTimes', 'utime'], {'side': '"""left"""'}), "(self.poseTimes, utime, side='left')\n", (765, 801), True, 'import numpy as np\n'), ((937, 980), 'director.transformUtils.transformFromPose', 'transformUtils.transformFromPose', (['pos', 'quat'], {}), '(pos, quat)\n', (969, 980), False, 'from director import transformUtils\n')]
import time import pytest import numpy as np import pandas as pd import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import filestore import filestore.api import filestore.handlers import hxnfly.fly import hxnfly.log from hxnfly.callbacks import FlyLiveCrossSection from hxnfly.fly2d import Fly2D from hxnfly.bs import FlyPlan2D from .fly_mock import (MockDetector, MockSignal) from .sim_detector import TestDetector from .fixtures import * def test_scan_points(): from hxnfly.fly2d import _get_scan_points point_args = (0.0, 1.0, 10, 1.0, 2.0, 10, ) points = list(_get_scan_points(*point_args, max_points=22)) assert len(points) == 5 assert sum(py for xi, xj, px, yi, yj, py in points) == 10 xis = [xi for xi, xj, px, yi, yj, py in points] xjs = [xj for xi, xj, px, yi, yj, py in points] assert min(xis) == 0.0 assert max(xjs) == 1.0 yis = [yi for xi, xj, px, yi, yj, py in points] yjs = [yj for xi, xj, px, yi, yj, py in points] assert min(yis) == 1.0 assert max(yjs) == 2.0 def make_2d_data(startx, endx, nptsx, starty, endy, nptsy, gathered_points=200, gate_enable='low_to_high'): # this is not entirely accurate... time = np.linspace(0, 10.0, gathered_points) gather_y = gathered_points // nptsy px = np.array(np.linspace(startx, endx, gather_y).tolist() * nptsy) py = np.array(sum(([pt] * gather_y for pt in np.linspace(starty, endy, nptsy)), [])) pz = np.random.rand(gathered_points) / 10.0 enable = [] npts = nptsx * nptsy exposed_count = (gathered_points // npts) - 1 for i in range(npts): if gate_enable == 'low_to_high': enable.extend([0] + [1] * exposed_count) else: enable.extend([1] + [0] * exposed_count) if gate_enable == 'low_to_high': enable[-1] = 0 else: enable[-1] = 1 return [np.array(v) for v in (time, enable, px, py, pz)] @pytest.fixture(scope='function', params=['with_mock_detector', 'with_sim_detector', 'relative']) def fly2d(request, monkeypatch, ppmac, gpascii, axes, positioners, sim_det, ipython, global_state): import hxntools.scans hxntools.scans.setup(debug_mode=True) def run_and_wait(*args, **kwargs): print('run and wait!') change_callback = kwargs.pop('change_callback') time.sleep(0.1) change_callback('Q1', 0, 1) time.sleep(1.0) return 0 monkeypatch.setattr(gpascii, 'run_and_wait', run_and_wait) if request.param == 'with_sim_detector': sim_det.count_time.put(0.01) detectors = [sim_det] else: detectors = [MockDetector('', name='det')] gpascii.set_variable('gather.samples', 100) gpascii.set_variable('gather.maxlines', 100) scan = Fly2D(axes=axes, positioners=positioners, detectors=detectors) startx, endx, nptsx = -1.0, 1.0, 2 starty, endy, nptsy = -1.0, 1.0, 2 exposure_time = 1.0 relative = (request.param == 'relative') scan.configure(positioners['testx'], startx, endx, nptsx, positioners['testy'], starty, endy, nptsy, exposure_time=exposure_time, relative=relative) npts = nptsx * nptsy sclr1 = ipython.user_ns['sclr1'] sclr1.mca_by_index[1].spectrum.put(np.array([exposure_time * 50e3] * npts)) gather_client = scan.gather_client # fake data for parsing gather_client.gathered = make_2d_data(startx, endx, nptsx, starty, endy, nptsy, gathered_points=500, gate_enable=scan._gate_enable) def FakeClass(*args, **kwargs): print('initialized with', args, kwargs) scan.configure_defaults = dict(return_speed=5.0, dead_time=0.007, fly_type='soft', max_points=16384) return scan testx, testy = positioners['testx'], positioners['testy'] FlyPlan2D.scans = {frozenset({testx, testy}): FakeClass, } return scan def test_fly2d(fly2d): # kickoff sends in the subscan number normally data = fly2d.run_subscan(0) df = pd.DataFrame(list(pd.DataFrame(data)['data'])) print('acquired data:') print(df) has_test_det = any(isinstance(det, TestDetector) for det in fly2d.detectors) if has_test_det: assert 'sim_tiff' in df for img_uid in df['sim_tiff']: print(img_uid, filestore.api.retrieve(img_uid).shape) print(fly2d.collect()) print(fly2d.describe()) def test_failed_fly2d(fly2d, gpascii, monkeypatch): def run_and_wait(*args, **kwargs): time.sleep(1.0) return 1 monkeypatch.setattr(gpascii, 'run_and_wait', run_and_wait) data = fly2d.run_subscan(0) assert data is None def test_flyplan2d(monkeypatch, positioners, fly2d, run_engine): scan_fcn = hxnfly.bs.FlyPlan2D() gen = scan_fcn(positioners['testx'], -1.0, 1.0, 2, positioners['testy'], -1.0, 1.0, 2, 1.0, dead_time=0.001, ) run_engine(gen) def test_flyplan2d_liveimage(request, monkeypatch, positioners, run_engine, fly2d, xspress3): fly2d.detectors.append(xspress3) scan_fcn = hxnfly.bs.FlyPlan2D() from hxnfly.callbacks import (FlyDataCallbacks, FlyLiveImage) monkeypatch.setattr(hxnfly.fly, 'Xspress3Detector', xspress3.__class__) xspress3.array_counter.put(4) # TODO is this done in configure_roi? xspress3.setup_fake_rois([('Fe', [1, 2, 3, 4]), ('Mo', [4, 3, 2, 1]) ]) liveimage = FlyLiveImage(['Fe', 'Mo']) scan_fcn.subs = [FlyDataCallbacks(), liveimage] gen = scan_fcn(positioners['testx'], -1.0, 1.0, 2, positioners['testy'], -1.0, 1.0, 2, 1.0, dead_time=0.001, ) run_engine(gen) plt.savefig('liveimage-{}.png'.format(request.node.name)) liveimage.disable() plt.clf() # TODO crossection plot needs fixing # @pytest.mark= def test_flyplan2d_crossection(request, monkeypatch, positioners, run_engine, fly2d, xspress3): fly2d.detectors.append(xspress3) scan_fcn = hxnfly.bs.FlyPlan2D() monkeypatch.setattr(hxnfly.fly, 'Xspress3Detector', xspress3.__class__) xspress3.array_counter.put(4) # TODO is this done in configure_roi? xspress3.setup_fake_rois([('Fe', [1, 2, 3, 4]), ('Mo', [4, 3, 2, 1]) ]) with pytest.raises(ValueError): # cross-section only does 1 at a time FlyLiveCrossSection(['Fe', 'Mo']) crossection = FlyLiveCrossSection(['Fe']) scan_fcn.subs = [crossection] gen = scan_fcn(positioners['testx'], -1.0, 1.0, 2, positioners['testy'], -1.0, 1.0, 2, 1.0, dead_time=0.001, ) run_engine(gen) crossection.disable() from PyQt4.QtGui import QPixmap live_fn = 'crossection-live-{}.png'.format(request.node.name) QPixmap.grabWindow(crossection.live_window.winId()).save(live_fn, 'png') crossection.live_window.close() if crossection._final_window is not None: final_fn = 'crossection-final-{}.png'.format(request.node.name) QPixmap.grabWindow(crossection.final_window.winId()).save(final_fn, 'png') crossection.final_window.close()
[ "hxnfly.callbacks.FlyLiveCrossSection", "numpy.random.rand", "pandas.DataFrame", "matplotlib.use", "hxnfly.callbacks.FlyLiveImage", "matplotlib.pyplot.clf", "time.sleep", "filestore.api.retrieve", "numpy.array", "numpy.linspace", "pytest.raises", "hxnfly.fly2d.Fly2D", "pytest.fixture", "hx...
[((85, 106), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (99, 106), False, 'import matplotlib\n'), ((2077, 2177), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""function"""', 'params': "['with_mock_detector', 'with_sim_detector', 'relative']"}), "(scope='function', params=['with_mock_detector',\n 'with_sim_detector', 'relative'])\n", (2091, 2177), False, 'import pytest\n'), ((1306, 1343), 'numpy.linspace', 'np.linspace', (['(0)', '(10.0)', 'gathered_points'], {}), '(0, 10.0, gathered_points)\n', (1317, 1343), True, 'import numpy as np\n'), ((2968, 3030), 'hxnfly.fly2d.Fly2D', 'Fly2D', ([], {'axes': 'axes', 'positioners': 'positioners', 'detectors': 'detectors'}), '(axes=axes, positioners=positioners, detectors=detectors)\n', (2973, 3030), False, 'from hxnfly.fly2d import Fly2D\n'), ((5910, 5936), 'hxnfly.callbacks.FlyLiveImage', 'FlyLiveImage', (["['Fe', 'Mo']"], {}), "(['Fe', 'Mo'])\n", (5922, 5936), False, 'from hxnfly.callbacks import FlyDataCallbacks, FlyLiveImage\n'), ((6274, 6283), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (6281, 6283), True, 'import matplotlib.pyplot as plt\n'), ((6975, 7002), 'hxnfly.callbacks.FlyLiveCrossSection', 'FlyLiveCrossSection', (["['Fe']"], {}), "(['Fe'])\n", (6994, 7002), False, 'from hxnfly.callbacks import FlyLiveCrossSection\n'), ((640, 684), 'hxnfly.fly2d._get_scan_points', '_get_scan_points', (['*point_args'], {'max_points': '(22)'}), '(*point_args, max_points=22)\n', (656, 684), False, 'from hxnfly.fly2d import _get_scan_points\n'), ((1599, 1630), 'numpy.random.rand', 'np.random.rand', (['gathered_points'], {}), '(gathered_points)\n', (1613, 1630), True, 'import numpy as np\n'), ((2025, 2036), 'numpy.array', 'np.array', (['v'], {}), '(v)\n', (2033, 2036), True, 'import numpy as np\n'), ((2527, 2542), 'time.sleep', 'time.sleep', (['(0.1)'], {}), '(0.1)\n', (2537, 2542), False, 'import time\n'), ((2587, 2602), 'time.sleep', 'time.sleep', (['(1.0)'], {}), '(1.0)\n', (2597, 2602), False, 'import time\n'), ((3471, 3513), 'numpy.array', 'np.array', (['([exposure_time * 50000.0] * npts)'], {}), '([exposure_time * 50000.0] * npts)\n', (3479, 3513), True, 'import numpy as np\n'), ((4888, 4903), 'time.sleep', 'time.sleep', (['(1.0)'], {}), '(1.0)\n', (4898, 4903), False, 'import time\n'), ((5959, 5977), 'hxnfly.callbacks.FlyDataCallbacks', 'FlyDataCallbacks', ([], {}), '()\n', (5975, 5977), False, 'from hxnfly.callbacks import FlyDataCallbacks, FlyLiveImage\n'), ((6841, 6866), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (6854, 6866), False, 'import pytest\n'), ((6922, 6955), 'hxnfly.callbacks.FlyLiveCrossSection', 'FlyLiveCrossSection', (["['Fe', 'Mo']"], {}), "(['Fe', 'Mo'])\n", (6941, 6955), False, 'from hxnfly.callbacks import FlyLiveCrossSection\n'), ((4395, 4413), 'pandas.DataFrame', 'pd.DataFrame', (['data'], {}), '(data)\n', (4407, 4413), True, 'import pandas as pd\n'), ((1402, 1437), 'numpy.linspace', 'np.linspace', (['startx', 'endx', 'gather_y'], {}), '(startx, endx, gather_y)\n', (1413, 1437), True, 'import numpy as np\n'), ((1528, 1560), 'numpy.linspace', 'np.linspace', (['starty', 'endy', 'nptsy'], {}), '(starty, endy, nptsy)\n', (1539, 1560), True, 'import numpy as np\n'), ((4692, 4723), 'filestore.api.retrieve', 'filestore.api.retrieve', (['img_uid'], {}), '(img_uid)\n', (4714, 4723), False, 'import filestore\n')]
from utils.customloader import CustomDataset, DatasetSplit from torchvision import datasets, transforms from torch.utils.data import DataLoader from sklearn.model_selection import train_test_split import numpy as np import torch import random def get_dataloader(data='mnist', test_size=0.5, num_workers=0, batch_size=32, seed=42): if (data == 'mnist'): transform = transforms.Compose([ transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))]) dataset_train = datasets.MNIST('./data/mnist/', train=True, download=True, transform=transform) dataset_test = datasets.MNIST('./data/mnist/', train=False, download=True, transform=transform) total_data_x, total_data_y = dataset_train.data, dataset_train.targets total_data_x = np.expand_dims(total_data_x, -1) total_data_y = np.expand_dims(total_data_y, -1) global_x, local_x, global_y, local_y = train_test_split(total_data_x, total_data_y, test_size=test_size, random_state=seed, stratify=total_data_y) global_train_set = CustomDataset(global_x, global_y, transform=transform) local_train_set = CustomDataset(local_x, local_y, transform=transform) global_train_loader = DataLoader(global_train_set, batch_size=batch_size, shuffle=True, num_workers=num_workers) local_train_loader = DataLoader(global_train_set, batch_size=batch_size, shuffle=True, num_workers=8) test_loader = DataLoader(dataset_test, batch_size=batch_size, shuffle=False, num_workers=num_workers) return global_train_loader, local_train_loader, test_loader
[ "torch.utils.data.DataLoader", "sklearn.model_selection.train_test_split", "torchvision.datasets.MNIST", "numpy.expand_dims", "torchvision.transforms.Normalize", "utils.customloader.CustomDataset", "torchvision.transforms.ToTensor" ]
[((788, 820), 'numpy.expand_dims', 'np.expand_dims', (['total_data_x', '(-1)'], {}), '(total_data_x, -1)\n', (802, 820), True, 'import numpy as np\n'), ((840, 872), 'numpy.expand_dims', 'np.expand_dims', (['total_data_y', '(-1)'], {}), '(total_data_y, -1)\n', (854, 872), True, 'import numpy as np\n'), ((918, 1029), 'sklearn.model_selection.train_test_split', 'train_test_split', (['total_data_x', 'total_data_y'], {'test_size': 'test_size', 'random_state': 'seed', 'stratify': 'total_data_y'}), '(total_data_x, total_data_y, test_size=test_size,\n random_state=seed, stratify=total_data_y)\n', (934, 1029), False, 'from sklearn.model_selection import train_test_split\n'), ((1237, 1291), 'utils.customloader.CustomDataset', 'CustomDataset', (['global_x', 'global_y'], {'transform': 'transform'}), '(global_x, global_y, transform=transform)\n', (1250, 1291), False, 'from utils.customloader import CustomDataset, DatasetSplit\n'), ((1314, 1366), 'utils.customloader.CustomDataset', 'CustomDataset', (['local_x', 'local_y'], {'transform': 'transform'}), '(local_x, local_y, transform=transform)\n', (1327, 1366), False, 'from utils.customloader import CustomDataset, DatasetSplit\n'), ((1403, 1497), 'torch.utils.data.DataLoader', 'DataLoader', (['global_train_set'], {'batch_size': 'batch_size', 'shuffle': '(True)', 'num_workers': 'num_workers'}), '(global_train_set, batch_size=batch_size, shuffle=True,\n num_workers=num_workers)\n', (1413, 1497), False, 'from torch.utils.data import DataLoader\n'), ((1519, 1604), 'torch.utils.data.DataLoader', 'DataLoader', (['global_train_set'], {'batch_size': 'batch_size', 'shuffle': '(True)', 'num_workers': '(8)'}), '(global_train_set, batch_size=batch_size, shuffle=True, num_workers=8\n )\n', (1529, 1604), False, 'from torch.utils.data import DataLoader\n'), ((1618, 1710), 'torch.utils.data.DataLoader', 'DataLoader', (['dataset_test'], {'batch_size': 'batch_size', 'shuffle': '(False)', 'num_workers': 'num_workers'}), '(dataset_test, batch_size=batch_size, shuffle=False, num_workers=\n num_workers)\n', (1628, 1710), False, 'from torch.utils.data import DataLoader\n'), ((497, 576), 'torchvision.datasets.MNIST', 'datasets.MNIST', (['"""./data/mnist/"""'], {'train': '(True)', 'download': '(True)', 'transform': 'transform'}), "('./data/mnist/', train=True, download=True, transform=transform)\n", (511, 576), False, 'from torchvision import datasets, transforms\n'), ((600, 685), 'torchvision.datasets.MNIST', 'datasets.MNIST', (['"""./data/mnist/"""'], {'train': '(False)', 'download': '(True)', 'transform': 'transform'}), "('./data/mnist/', train=False, download=True, transform=transform\n )\n", (614, 685), False, 'from torchvision import datasets, transforms\n'), ((404, 425), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (423, 425), False, 'from torchvision import datasets, transforms\n'), ((428, 470), 'torchvision.transforms.Normalize', 'transforms.Normalize', (['(0.1307,)', '(0.3081,)'], {}), '((0.1307,), (0.3081,))\n', (448, 470), False, 'from torchvision import datasets, transforms\n')]
"""Common functions for polar coding.""" import numba import numpy as np from ..constants import INFINITY from .node_types import NodeTypes @numba.njit def zero( llr: np.array, mask_steps: int = 0, last_chunk_type: int = 0, ) -> np.array: """Compute beta values for ZERO node. https://arxiv.org/pdf/1510.06495.pdf Section III.C. """ return np.ones(llr.size, dtype=np.double) * INFINITY @numba.njit def one( llr: np.array, mask_steps: int = 0, last_chunk_type: int = 0, ) -> np.array: """Compute beta values for ONE node. https://arxiv.org/pdf/1510.06495.pdf Section III.C. """ return np.zeros(llr.size, dtype=np.double) @numba.njit def repetition( llr: np.array, mask_steps: int = 0, last_chunk_type: int = 0, ) -> np.array: """Compute beta value for Repetition node.""" alpha_sum = np.sum(llr) return -1 * llr + alpha_sum @numba.njit def single_parity_check( llr: np.array, mask_steps: int = 0, last_chunk_type: int = 0, ) -> np.array: """Compute beta value for Single parity node.""" all_sign = np.sign(np.prod(llr)) abs_alpha = np.fabs(llr) first_min_idx, second_min_idx = np.argsort(abs_alpha)[:2] result = np.sign(llr) * all_sign for i in range(result.size): if i == first_min_idx: result[i] *= abs_alpha[second_min_idx] else: result[i] *= abs_alpha[first_min_idx] return result @numba.njit def g_repetition( llr: np.array, mask_steps: int, last_chunk_type: int, ) -> np.array: """Compute bits for Generalized Repetition node. Based on: https://arxiv.org/pdf/1804.09508.pdf, Section III, A. """ N = llr.size step = N // mask_steps # step is equal to a chunk size last_alpha = np.zeros(step) for i in range(step): last_alpha[i] = np.sum(np.array([ llr[i + j * step] for j in range(mask_steps) ])) last_beta = ( one(last_alpha) if last_chunk_type == 1 else single_parity_check(last_alpha) ) result = np.zeros(N) for i in range(0, N, step): result[i: i + step] = last_beta return result @numba.njit def rg_parity( llr: np.array, mask_steps: int, last_chunk_type: int = 0, ) -> np.array: """Compute bits for Relaxed Generalized Parity Check node. Based on: https://arxiv.org/pdf/1804.09508.pdf, Section III, B. """ N = llr.size step = N // mask_steps # step is equal to a chunk size result = np.zeros(N) for i in range(step): alpha = np.zeros(mask_steps) for j in range(mask_steps): alpha[j] = llr[i + j * step] beta = single_parity_check(alpha) result[i:N:step] = beta return result # Mapping between decoding node types and corresponding decoding methods _methods_map = { NodeTypes.ZERO: zero, NodeTypes.ONE: one, NodeTypes.SINGLE_PARITY_CHECK: single_parity_check, NodeTypes.REPETITION: repetition, NodeTypes.RG_PARITY: rg_parity, NodeTypes.G_REPETITION: g_repetition, } def compute_beta_soft( node_type: str, llr: np.array, mask_steps: int = 0, last_chunk_type: int = 0, *args, **kwargs, ) -> np.array: """Unites functions for making soft decisions during decoding.""" method = _methods_map[node_type] return method(llr, mask_steps, last_chunk_type, *args, **kwargs)
[ "numpy.fabs", "numpy.prod", "numpy.ones", "numpy.argsort", "numpy.sum", "numpy.zeros", "numpy.sign" ]
[((673, 708), 'numpy.zeros', 'np.zeros', (['llr.size'], {'dtype': 'np.double'}), '(llr.size, dtype=np.double)\n', (681, 708), True, 'import numpy as np\n'), ((906, 917), 'numpy.sum', 'np.sum', (['llr'], {}), '(llr)\n', (912, 917), True, 'import numpy as np\n'), ((1196, 1208), 'numpy.fabs', 'np.fabs', (['llr'], {}), '(llr)\n', (1203, 1208), True, 'import numpy as np\n'), ((1858, 1872), 'numpy.zeros', 'np.zeros', (['step'], {}), '(step)\n', (1866, 1872), True, 'import numpy as np\n'), ((2142, 2153), 'numpy.zeros', 'np.zeros', (['N'], {}), '(N)\n', (2150, 2153), True, 'import numpy as np\n'), ((2602, 2613), 'numpy.zeros', 'np.zeros', (['N'], {}), '(N)\n', (2610, 2613), True, 'import numpy as np\n'), ((385, 419), 'numpy.ones', 'np.ones', (['llr.size'], {'dtype': 'np.double'}), '(llr.size, dtype=np.double)\n', (392, 419), True, 'import numpy as np\n'), ((1166, 1178), 'numpy.prod', 'np.prod', (['llr'], {}), '(llr)\n', (1173, 1178), True, 'import numpy as np\n'), ((1245, 1266), 'numpy.argsort', 'np.argsort', (['abs_alpha'], {}), '(abs_alpha)\n', (1255, 1266), True, 'import numpy as np\n'), ((1285, 1297), 'numpy.sign', 'np.sign', (['llr'], {}), '(llr)\n', (1292, 1297), True, 'import numpy as np\n'), ((2657, 2677), 'numpy.zeros', 'np.zeros', (['mask_steps'], {}), '(mask_steps)\n', (2665, 2677), True, 'import numpy as np\n')]
# # Copyright 2018 Analytics Zoo 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. # import numpy as np import math from bigdl.nn.layer import Sum from zoo.pipeline.api.keras.engine import ZooKerasLayer from zoo.pipeline.api.keras.layers import * from zoo.pipeline.api.keras.models import Sequential from zoo.pipeline.api.keras.models import Model import zoo.pipeline.api.autograd as auto if sys.version >= '3': long = int unicode = str class TransformerLayer(ZooKerasLayer): """ A self attention layer # Arguments nBlock: block number resid_drop: drop probability off projection attn_drop: drop probability of attention n_head: head number mask_attention: whether unidirectional or bidirectional embedding_layer: embedding layer """ def __init__(self, n_block, resid_drop, attn_drop, n_head, mask_attention, embedding_layer, input_shape, bigdl_type="float"): self.resid_drop = resid_drop self.attn_drop = attn_drop self.n_head = n_head self.mask_attention = mask_attention self.seq_len = input_shape[0] self.bigdl_type = bigdl_type if mask_attention: mask_value = np.tril(np.ones((self.seq_len, self.seq_len), dtype=bigdl_type)) self.mask_value = auto.Constant(data=mask_value.reshape((1, 1, self.seq_len, self.seq_len))) input = Input(shape=list(input_shape)) embedding = embedding_layer(input) hidden_size = embedding.get_output_shape()[-1] next_input = embedding for _ in range(n_block): output = self.block(next_input, hidden_size) next_input = output model = Model(input, next_input) self.value = model.value def block(self, x, size): g = auto.Parameter(shape=(1, size), init_weight=np.ones((1, size), dtype=self.bigdl_type)) b = auto.Parameter(shape=(1, size), init_weight=np.zeros((1, size), dtype=self.bigdl_type)) g2 = auto.Parameter(shape=(1, size), init_weight=np.ones((1, size), dtype=self.bigdl_type)) b2 = auto.Parameter(shape=(1, size), init_weight=np.zeros((1, size), dtype=self.bigdl_type)) a = self.multi_head_self_attention(x, size) n = self.layer_norm(x + a, w=g, b=b) m = self.mlp(n, size) h = self.layer_norm(n + m, w=g2, b=b2) return h def multi_head_self_attention(self, x, size): c = Convolution1D(size * 3, 1, "normal", (0.0, 0.02))(x) query = c.slice(2, 0, size) key = c.slice(2, size, size) value = c.slice(2, size*2, size) q = self.split_heads(query) k = self.split_heads(key, k=True) v = self.split_heads(value) a = self.attn(q, k, v, True) m = self.merge_heads(a) n = Convolution1D(size, 1, "normal", (0.0, 0.02))(m) d = Dropout(self.resid_drop)(n) return d def split_heads(self, x, k=False): sizes = x.get_output_shape()[1:] shape = list(sizes + (sizes[-1]/self.n_head,)) shape[-2] = self.n_head r = Reshape(shape)(x) if k: f = Permute((2, 3, 1))(r) else: f = Permute((2, 1, 3))(r) return f def merge_heads(self, x): p = auto.contiguous(Permute((2, 1, 3))(x)) sizes = p.get_output_shape()[1:] merge_sizes = list((sizes[0], sizes[-1]*sizes[-2])) m = Reshape(merge_sizes)(p) return m def attn(self, q, k, v, scale=False): w = auto.mm(q, k) if scale: w = w / math.sqrt(v.get_output_shape()[-1]) if self.mask_attention: w = w * self.mask_value + (self.mask_value * (-1.0) + 1.0) * (-1e9) w = Activation("softmax")(w) w = Dropout(self.attn_drop)(w) w = auto.mm(w, v) return w def layer_norm(self, x, w, b, e=1e-5): sizes = x.get_output_shape()[1:] u = auto.mean(x, len(sizes), True) s = auto.mean(auto.square(x - u), len(sizes), True) y = (x - u) / auto.sqrt(s + e) y = y * w + b return y def mlp(self, x, size): h = Convolution1D(size*4, 1, init="normal", limits=(0.0, 0.02))(x) a = self.gelu(h) h2 = Convolution1D(size, 1, init="normal", limits=(0.0, 0.02))(a) y = Dropout(self.resid_drop)(h2) return y def gelu(self, x): y = (auto.square(x) * x * 0.044715 + x) * (math.sqrt(2 / math.pi)) y = Activation("tanh")(y) + 1.0 y = x * 0.5 * y return y @classmethod def init_with_default_embedding(cls, vocab=40990, seq_len=77, n_block=12, resid_drop=0.1, attn_drop=0.1, n_head=12, hidden_size=768, embedding_drop=0.1, mask_attention=True): """ vocab: vocabulary size of training data, default is 40990 seq_len: max sequence length of training data, default is 77 n_block: block number, default is 12 resid_drop: drop probability of projection, default is 0.1 attn_drop: drop probability of attention, default is 0.1 n_head: head number, default is 12 hidden_size: is also embedding size embedding_drop: drop probability of embedding layer, default is 0.1 mask_attention: whether unidirectional or bidirectional, default is true(unidirectional) """ from bigdl.nn.layer import Squeeze embedding = Sequential() embedding.add(Reshape([seq_len * 2], input_shape=(seq_len, 2)))\ .add(Embedding(vocab, hidden_size, input_length=seq_len * 2))\ .add(Dropout(embedding_drop))\ .add(Reshape((seq_len, 2, hidden_size)))\ .add(KerasLayerWrapper(Sum(dimension=3, squeeze=True))) # walk around for bug #1208, need remove this line after the bug fixed embedding.add(KerasLayerWrapper(Squeeze(dim=3))) return TransformerLayer(n_block, resid_drop, attn_drop, n_head, mask_attention, embedding, input_shape=(seq_len, 2))
[ "zoo.pipeline.api.autograd.square", "zoo.pipeline.api.autograd.mm", "numpy.ones", "zoo.pipeline.api.keras.models.Sequential", "math.sqrt", "zoo.pipeline.api.keras.models.Model", "numpy.zeros", "bigdl.nn.layer.Squeeze", "zoo.pipeline.api.autograd.sqrt", "bigdl.nn.layer.Sum" ]
[((2272, 2296), 'zoo.pipeline.api.keras.models.Model', 'Model', (['input', 'next_input'], {}), '(input, next_input)\n', (2277, 2296), False, 'from zoo.pipeline.api.keras.models import Model\n'), ((4094, 4107), 'zoo.pipeline.api.autograd.mm', 'auto.mm', (['q', 'k'], {}), '(q, k)\n', (4101, 4107), True, 'import zoo.pipeline.api.autograd as auto\n'), ((4384, 4397), 'zoo.pipeline.api.autograd.mm', 'auto.mm', (['w', 'v'], {}), '(w, v)\n', (4391, 4397), True, 'import zoo.pipeline.api.autograd as auto\n'), ((6050, 6062), 'zoo.pipeline.api.keras.models.Sequential', 'Sequential', ([], {}), '()\n', (6060, 6062), False, 'from zoo.pipeline.api.keras.models import Sequential\n'), ((4565, 4583), 'zoo.pipeline.api.autograd.square', 'auto.square', (['(x - u)'], {}), '(x - u)\n', (4576, 4583), True, 'import zoo.pipeline.api.autograd as auto\n'), ((4625, 4641), 'zoo.pipeline.api.autograd.sqrt', 'auto.sqrt', (['(s + e)'], {}), '(s + e)\n', (4634, 4641), True, 'import zoo.pipeline.api.autograd as auto\n'), ((5017, 5039), 'math.sqrt', 'math.sqrt', (['(2 / math.pi)'], {}), '(2 / math.pi)\n', (5026, 5039), False, 'import math\n'), ((1723, 1778), 'numpy.ones', 'np.ones', (['(self.seq_len, self.seq_len)'], {'dtype': 'bigdl_type'}), '((self.seq_len, self.seq_len), dtype=bigdl_type)\n', (1730, 1778), True, 'import numpy as np\n'), ((2417, 2458), 'numpy.ones', 'np.ones', (['(1, size)'], {'dtype': 'self.bigdl_type'}), '((1, size), dtype=self.bigdl_type)\n', (2424, 2458), True, 'import numpy as np\n'), ((2516, 2558), 'numpy.zeros', 'np.zeros', (['(1, size)'], {'dtype': 'self.bigdl_type'}), '((1, size), dtype=self.bigdl_type)\n', (2524, 2558), True, 'import numpy as np\n'), ((2617, 2658), 'numpy.ones', 'np.ones', (['(1, size)'], {'dtype': 'self.bigdl_type'}), '((1, size), dtype=self.bigdl_type)\n', (2624, 2658), True, 'import numpy as np\n'), ((2717, 2759), 'numpy.zeros', 'np.zeros', (['(1, size)'], {'dtype': 'self.bigdl_type'}), '((1, size), dtype=self.bigdl_type)\n', (2725, 2759), True, 'import numpy as np\n'), ((6344, 6374), 'bigdl.nn.layer.Sum', 'Sum', ([], {'dimension': '(3)', 'squeeze': '(True)'}), '(dimension=3, squeeze=True)\n', (6347, 6374), False, 'from bigdl.nn.layer import Sum\n'), ((6496, 6510), 'bigdl.nn.layer.Squeeze', 'Squeeze', ([], {'dim': '(3)'}), '(dim=3)\n', (6503, 6510), False, 'from bigdl.nn.layer import Squeeze\n'), ((4979, 4993), 'zoo.pipeline.api.autograd.square', 'auto.square', (['x'], {}), '(x)\n', (4990, 4993), True, 'import zoo.pipeline.api.autograd as auto\n')]
import tensorflow as tf import os from PIL import Image import numpy as np import logging import time from dl.step1_cnn import Step1CNN from dl.util import visualize_boxes_and_labels_on_image_array_V1 logger = logging.getLogger("detect") class FreezerDetectorFactory: _detector = {} @staticmethod def get_static_detector(exportid): if exportid not in FreezerDetectorFactory._detector: # FIXME 缓存对象有问题 FreezerDetectorFactory._detector[exportid] = ShelfDetector(exportid) return FreezerDetectorFactory._detector[exportid] class ShelfDetector: def __init__(self, exportid): file_path, _ = os.path.split(os.path.realpath(__file__)) self.step1_cnn = Step1CNN(os.path.join(file_path, 'model', str(exportid))) self.counter = 0 self.config = tf.ConfigProto() self.config.gpu_options.allow_growth = True def load(self): if self.counter > 0: logger.info('waiting model to load (3s) ...') time.sleep(3) return self.counter = self.counter + 1 if not self.step1_cnn.is_load(): self.step1_cnn.load(self.config) def detect(self, image_path, step1_min_score_thresh=.5, totol_level = 6): if not self.step1_cnn.is_load(): self.load() if not self.step1_cnn.is_load(): logger.warning('loading model failed') return None import time time0 = time.time() # image_path = image_instance.source.path image = Image.open(image_path) if image.mode != 'RGB': image = image.convert('RGB') # the array based representation of the image will be used later in order to prepare the # result image with boxes and labels on it. (im_width, im_height) = image.size image_np = np.array(image) # Actual detection. (boxes, scores) = self.step1_cnn.detect(image_np) # data solving boxes = np.squeeze(boxes) # classes = np.squeeze(classes).astype(np.int32) scores_step1 = np.squeeze(scores) ret = [] # logger.info('detect number:{}'.format(boxes.shape[0])) for i in range(boxes.shape[0]): if scores_step1[i] > step1_min_score_thresh: ymin, xmin, ymax, xmax = boxes[i] ymin = int(ymin * im_height) xmin = int(xmin * im_width) ymax = int(ymax * im_height) xmax = int(xmax * im_width) ret.append({'score': scores_step1[i], 'xmin': xmin, 'ymin': ymin, 'xmax': xmax, 'ymax': ymax, }) # visualization output_image_path = None if len(ret) > 0: image_dir = os.path.dirname(image_path) output_image_path = os.path.join(image_dir, 'visual_' + os.path.split(image_path)[-1]) visualize_boxes_and_labels_on_image_array_V1( image_np, boxes, scores_step1, use_normalized_coordinates=True, step1_min_score_thresh=step1_min_score_thresh, line_thickness=2, show_error_boxes=False, max_boxes_to_draw=None, ) output_image = Image.fromarray(image_np) output_image.thumbnail((int(im_width), int(im_height)), Image.ANTIALIAS) output_image.save(output_image_path) time1 = time.time() return ret, time1-time0,output_image_path
[ "logging.getLogger", "PIL.Image.fromarray", "PIL.Image.open", "time.sleep", "numpy.squeeze", "os.path.realpath", "numpy.array", "os.path.dirname", "os.path.split", "tensorflow.ConfigProto", "dl.util.visualize_boxes_and_labels_on_image_array_V1", "time.time" ]
[((211, 238), 'logging.getLogger', 'logging.getLogger', (['"""detect"""'], {}), "('detect')\n", (228, 238), False, 'import logging\n'), ((828, 844), 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {}), '()\n', (842, 844), True, 'import tensorflow as tf\n'), ((1487, 1498), 'time.time', 'time.time', ([], {}), '()\n', (1496, 1498), False, 'import time\n'), ((1566, 1588), 'PIL.Image.open', 'Image.open', (['image_path'], {}), '(image_path)\n', (1576, 1588), False, 'from PIL import Image\n'), ((1873, 1888), 'numpy.array', 'np.array', (['image'], {}), '(image)\n', (1881, 1888), True, 'import numpy as np\n'), ((2015, 2032), 'numpy.squeeze', 'np.squeeze', (['boxes'], {}), '(boxes)\n', (2025, 2032), True, 'import numpy as np\n'), ((2113, 2131), 'numpy.squeeze', 'np.squeeze', (['scores'], {}), '(scores)\n', (2123, 2131), True, 'import numpy as np\n'), ((3526, 3537), 'time.time', 'time.time', ([], {}), '()\n', (3535, 3537), False, 'import time\n'), ((669, 695), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (685, 695), False, 'import os\n'), ((1017, 1030), 'time.sleep', 'time.sleep', (['(3)'], {}), '(3)\n', (1027, 1030), False, 'import time\n'), ((2818, 2845), 'os.path.dirname', 'os.path.dirname', (['image_path'], {}), '(image_path)\n', (2833, 2845), False, 'import os\n'), ((2957, 3191), 'dl.util.visualize_boxes_and_labels_on_image_array_V1', 'visualize_boxes_and_labels_on_image_array_V1', (['image_np', 'boxes', 'scores_step1'], {'use_normalized_coordinates': '(True)', 'step1_min_score_thresh': 'step1_min_score_thresh', 'line_thickness': '(2)', 'show_error_boxes': '(False)', 'max_boxes_to_draw': 'None'}), '(image_np, boxes, scores_step1,\n use_normalized_coordinates=True, step1_min_score_thresh=\n step1_min_score_thresh, line_thickness=2, show_error_boxes=False,\n max_boxes_to_draw=None)\n', (3001, 3191), False, 'from dl.util import visualize_boxes_and_labels_on_image_array_V1\n'), ((3349, 3374), 'PIL.Image.fromarray', 'Image.fromarray', (['image_np'], {}), '(image_np)\n', (3364, 3374), False, 'from PIL import Image\n'), ((2914, 2939), 'os.path.split', 'os.path.split', (['image_path'], {}), '(image_path)\n', (2927, 2939), False, 'import os\n')]
import numpy as np import matplotlib.pyplot as plt x = np.arange(0,100) y = x*2 # Functional Method fig = plt.figure() ax = fig.add_axes([0, 0, 1, 1]) ax.plot(x, y) ax.set_title('title') ax.set_xlabel('X') ax.set_ylabel('Y') plt.show()
[ "matplotlib.pyplot.figure", "numpy.arange", "matplotlib.pyplot.show" ]
[((63, 80), 'numpy.arange', 'np.arange', (['(0)', '(100)'], {}), '(0, 100)\n', (72, 80), True, 'import numpy as np\n'), ((119, 131), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (129, 131), True, 'import matplotlib.pyplot as plt\n'), ((244, 254), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (252, 254), True, 'import matplotlib.pyplot as plt\n')]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ''' gnpy.core.utils =============== This module contains utility functions that are used with gnpy. ''' import json import numpy as np from numpy import pi, cos, sqrt, log10 from scipy import constants def load_json(filename): with open(filename, 'r') as f: data = json.load(f) return data def save_json(obj, filename): with open(filename, 'w') as f: json.dump(obj, f) def c(): """ Returns the speed of light in meters per second """ return constants.c def itufs(spacing, startf=191.35, stopf=196.10): """Creates an array of frequencies whose default range is 191.35-196.10 THz :param spacing: Frequency spacing in THz :param starf: Start frequency in THz :param stopf: Stop frequency in THz :type spacing: float :type startf: float :type stopf: float :return an array of frequnecies determined by the spacing parameter :rtype: numpy.ndarray """ return np.arange(startf, stopf + spacing / 2, spacing) def h(): """ Returns plank's constant in J*s """ return constants.h def lin2db(value): return 10 * log10(value) def db2lin(value): return 10**(value / 10) wavelength2freq = constants.lambda2nu freq2wavelength = constants.nu2lambda def freq2wavelength(value): """ Converts frequency units to wavelength units. """ return c() / value def deltawl2deltaf(delta_wl, wavelength): """ deltawl2deltaf(delta_wl, wavelength): delta_wl is BW in wavelength units wavelength is the center wl units for delta_wl and wavelength must be same :param delta_wl: delta wavelength BW in same units as wavelength :param wavelength: wavelength BW is relevant for :type delta_wl: float or numpy.ndarray :type wavelength: float :return: The BW in frequency units :rtype: float or ndarray """ f = wavelength2freq(wavelength) return delta_wl * f / wavelength def deltaf2deltawl(delta_f, frequency): """ deltawl2deltaf(delta_f, frequency): converts delta frequency to delta wavelength units for delta_wl and wavelength must be same :param delta_f: delta frequency in same units as frequency :param frequency: frequency BW is relevant for :type delta_f: float or numpy.ndarray :type frequency: float :return: The BW in wavelength units :rtype: float or ndarray """ wl = freq2wavelength(frequency) return delta_f * wl / frequency def rrc(ffs, baud_rate, alpha): """ rrc(ffs, baud_rate, alpha): computes the root-raised cosine filter function. :param ffs: A numpy array of frequencies :param baud_rate: The Baud Rate of the System :param alpha: The roll-off factor of the filter :type ffs: numpy.ndarray :type baud_rate: float :type alpha: float :return: hf a numpy array of the filter shape :rtype: numpy.ndarray """ Ts = 1 / baud_rate l_lim = (1 - alpha) / (2 * Ts) r_lim = (1 + alpha) / (2 * Ts) hf = np.zeros(np.shape(ffs)) slope_inds = np.where( np.logical_and(np.abs(ffs) > l_lim, np.abs(ffs) < r_lim)) hf[slope_inds] = 0.5 * (1 + cos((pi * Ts / alpha) * (np.abs(ffs[slope_inds]) - l_lim))) p_inds = np.where(np.logical_and(np.abs(ffs) > 0, np.abs(ffs) < l_lim)) hf[p_inds] = 1 return sqrt(hf)
[ "numpy.abs", "numpy.log10", "numpy.sqrt", "numpy.arange", "json.load", "numpy.shape", "json.dump" ]
[((1006, 1053), 'numpy.arange', 'np.arange', (['startf', '(stopf + spacing / 2)', 'spacing'], {}), '(startf, stopf + spacing / 2, spacing)\n', (1015, 1053), True, 'import numpy as np\n'), ((3403, 3411), 'numpy.sqrt', 'sqrt', (['hf'], {}), '(hf)\n', (3407, 3411), False, 'from numpy import pi, cos, sqrt, log10\n'), ((331, 343), 'json.load', 'json.load', (['f'], {}), '(f)\n', (340, 343), False, 'import json\n'), ((435, 452), 'json.dump', 'json.dump', (['obj', 'f'], {}), '(obj, f)\n', (444, 452), False, 'import json\n'), ((1177, 1189), 'numpy.log10', 'log10', (['value'], {}), '(value)\n', (1182, 1189), False, 'from numpy import pi, cos, sqrt, log10\n'), ((3061, 3074), 'numpy.shape', 'np.shape', (['ffs'], {}), '(ffs)\n', (3069, 3074), True, 'import numpy as np\n'), ((3126, 3137), 'numpy.abs', 'np.abs', (['ffs'], {}), '(ffs)\n', (3132, 3137), True, 'import numpy as np\n'), ((3147, 3158), 'numpy.abs', 'np.abs', (['ffs'], {}), '(ffs)\n', (3153, 3158), True, 'import numpy as np\n'), ((3334, 3345), 'numpy.abs', 'np.abs', (['ffs'], {}), '(ffs)\n', (3340, 3345), True, 'import numpy as np\n'), ((3351, 3362), 'numpy.abs', 'np.abs', (['ffs'], {}), '(ffs)\n', (3357, 3362), True, 'import numpy as np\n'), ((3262, 3285), 'numpy.abs', 'np.abs', (['ffs[slope_inds]'], {}), '(ffs[slope_inds])\n', (3268, 3285), True, 'import numpy as np\n')]
from abc import abstractmethod import logging from hampel import hampel import mlflow import numpy as np import pandas as pd from sklearn.linear_model import LinearRegression from sklearn.model_selection import train_test_split from sklearn.metrics import mean_absolute_error from sklearn.svm import SVR from xgboost import XGBRegressor from sigeml.schemas import TrainConfig from sigeml.config.config import get_postgres_uri from sigeml.models.dataset import Dataset from sigeml.services.sige import get_data_from_sige from sigeml.services.predictions import store_experiment_predictions class LoadCurveModel: def __init__(self, config: TrainConfig, dataset: Dataset) -> None: mlflow.set_tracking_uri(get_postgres_uri()) mlflow.set_experiment(config.experiment_name) self.config = config logging.basicConfig(level=logging.INFO) self.logger = logging.getLogger(__name__) self.data = dataset.data self.X_train = self.X_test = self.y_train = self.y_test = np.array([]) self.model_params = self.config.model_params delattr(self.model_params, "model") self.data_params = dataset.config self.test_sample_size = 200 def get_X(self): X = ( self.data.collection_date.dt.hour + self.data.collection_date.dt.minute / 60 ).values.reshape((len(self.data), 1)) return X def get_y(self): return self.data["consumption"].values def get_sample_from_test_data(self): test_data = np.column_stack([self.X_test, self.y_test]) np.random.seed(42) return test_data[np.random.choice(test_data.shape[0], self.test_sample_size, replace=False)] def get_test_points(self): test_data_sample = self.get_sample_from_test_data() return list(map(lambda d: {"x": float(d[0]), "y": float(d[1])}, test_data_sample)) @staticmethod def get_load_curve(y_pred): preds = zip(np.arange(0, 24, 0.25), y_pred) return list(map(lambda d: {"x": float(d[0]), "y": float(d[1])}, preds)) def split_data(self): X = self.get_X() y = self.get_y() self.X_train, self.X_test, self.y_train, self.y_test = train_test_split( X, y, random_state=42, test_size=self.config.test_size ) def train(self): self.split_data() self.run() @abstractmethod def run(self): pass def evaluate(self, actual, pred) -> float: mae = mean_absolute_error(actual, pred) return mae class XGBoostModel(LoadCurveModel): def run(self): with mlflow.start_run(): xgb = XGBRegressor(**self.model_params.dict()).fit(self.X_train, self.y_train) xgb.fit(self.X_train, self.y_train) y_pred = xgb.predict(self.X_test) mae = self.evaluate(self.y_test, y_pred) self.logger.info( f"XGBRegressor {[str(p[0]) + '=' + str(p[1]) for p in self.model_params]}" ) self.logger.info(f"MAE: {mae:.2f}") params = { **self.model_params.dict(), **self.data_params.dict(), **{"model_name": "XGBRegressor"}, } mlflow.log_params(params) mlflow.log_metric("mae", mae) if not self.config.is_experiment: mlflow.xgboost.log_model(xgb, "model", registered_model_name="XGBRegressor") run = mlflow.active_run() load_curve = self.get_load_curve(xgb.predict(np.arange(0, 23.25, 0.25).reshape(-1, 1))) store_experiment_predictions(run.info.run_id, self.get_test_points(), load_curve) class LinearRegressorModel(LoadCurveModel): def run(self): with mlflow.start_run(): reg = LinearRegression(**self.model_params.dict()).fit(self.X_train, self.y_train) reg.fit(self.X_train, self.y_train) y_pred = reg.predict(self.X_test) load_curve = self.get_load_curve(reg.predict(np.arange(0, 23.25, 0.25).reshape(-1, 1))) mae = self.evaluate(self.y_test, y_pred) self.logger.info( f"LinearRegressor {[str(p[0]) + '=' + str(p[1]) for p in self.model_params]}" ) self.logger.info(f"MAE: {mae:.2f}") params = { **self.model_params.dict(), **self.data_params.dict(), **{"model_name": "LinearRegressor"}, } mlflow.log_params(params) mlflow.log_metric("mae", mae) if not self.config.is_experiment: mlflow.sklearn.log_model(reg, "model", registered_model_name="LinearRegressor") run = mlflow.active_run() load_curve = self.get_load_curve(reg.predict(np.arange(0, 23.25, 0.25).reshape(-1, 1))) store_experiment_predictions(run.info.run_id, self.get_test_points(), load_curve) class SVRModel(LoadCurveModel): def run(self): with mlflow.start_run(): svr = SVR(**self.model_params.dict()).fit(self.X_train, self.y_train) svr.fit(self.X_train, self.y_train) y_pred = svr.predict(self.X_test) mae = self.evaluate(self.y_test, y_pred) self.logger.info(f"SVR {[str(p[0]) + '=' + str(p[1]) for p in self.model_params]}") self.logger.info(f"MAE: {mae:.2f}") params = { **self.model_params.dict(), **self.data_params.dict(), **{"model_name": "SVR"}, } mlflow.log_params(params) mlflow.log_metric("mae", mae) if not self.config.is_experiment: mlflow.sklearn.log_model(svr, "model", registered_model_name="SVR") run = mlflow.active_run() load_curve = self.get_load_curve(svr.predict(np.arange(0, 23.25, 0.25).reshape(-1, 1))) store_experiment_predictions(run.info.run_id, self.get_test_points(), load_curve)
[ "logging.basicConfig", "logging.getLogger", "mlflow.start_run", "sklearn.model_selection.train_test_split", "numpy.random.choice", "mlflow.log_metric", "mlflow.active_run", "mlflow.xgboost.log_model", "numpy.column_stack", "mlflow.set_experiment", "numpy.array", "numpy.random.seed", "sigeml....
[((746, 791), 'mlflow.set_experiment', 'mlflow.set_experiment', (['config.experiment_name'], {}), '(config.experiment_name)\n', (767, 791), False, 'import mlflow\n'), ((830, 869), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO'}), '(level=logging.INFO)\n', (849, 869), False, 'import logging\n'), ((892, 919), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (909, 919), False, 'import logging\n'), ((1020, 1032), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (1028, 1032), True, 'import numpy as np\n'), ((1529, 1572), 'numpy.column_stack', 'np.column_stack', (['[self.X_test, self.y_test]'], {}), '([self.X_test, self.y_test])\n', (1544, 1572), True, 'import numpy as np\n'), ((1581, 1599), 'numpy.random.seed', 'np.random.seed', (['(42)'], {}), '(42)\n', (1595, 1599), True, 'import numpy as np\n'), ((2207, 2279), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X', 'y'], {'random_state': '(42)', 'test_size': 'self.config.test_size'}), '(X, y, random_state=42, test_size=self.config.test_size)\n', (2223, 2279), False, 'from sklearn.model_selection import train_test_split\n'), ((2484, 2517), 'sklearn.metrics.mean_absolute_error', 'mean_absolute_error', (['actual', 'pred'], {}), '(actual, pred)\n', (2503, 2517), False, 'from sklearn.metrics import mean_absolute_error\n'), ((718, 736), 'sigeml.config.config.get_postgres_uri', 'get_postgres_uri', ([], {}), '()\n', (734, 736), False, 'from sigeml.config.config import get_postgres_uri\n'), ((1625, 1699), 'numpy.random.choice', 'np.random.choice', (['test_data.shape[0]', 'self.test_sample_size'], {'replace': '(False)'}), '(test_data.shape[0], self.test_sample_size, replace=False)\n', (1641, 1699), True, 'import numpy as np\n'), ((1955, 1977), 'numpy.arange', 'np.arange', (['(0)', '(24)', '(0.25)'], {}), '(0, 24, 0.25)\n', (1964, 1977), True, 'import numpy as np\n'), ((2607, 2625), 'mlflow.start_run', 'mlflow.start_run', ([], {}), '()\n', (2623, 2625), False, 'import mlflow\n'), ((3239, 3264), 'mlflow.log_params', 'mlflow.log_params', (['params'], {}), '(params)\n', (3256, 3264), False, 'import mlflow\n'), ((3277, 3306), 'mlflow.log_metric', 'mlflow.log_metric', (['"""mae"""', 'mae'], {}), "('mae', mae)\n", (3294, 3306), False, 'import mlflow\n'), ((3466, 3485), 'mlflow.active_run', 'mlflow.active_run', ([], {}), '()\n', (3483, 3485), False, 'import mlflow\n'), ((3758, 3776), 'mlflow.start_run', 'mlflow.start_run', ([], {}), '()\n', (3774, 3776), False, 'import mlflow\n'), ((4501, 4526), 'mlflow.log_params', 'mlflow.log_params', (['params'], {}), '(params)\n', (4518, 4526), False, 'import mlflow\n'), ((4540, 4569), 'mlflow.log_metric', 'mlflow.log_metric', (['"""mae"""', 'mae'], {}), "('mae', mae)\n", (4557, 4569), False, 'import mlflow\n'), ((4732, 4751), 'mlflow.active_run', 'mlflow.active_run', ([], {}), '()\n', (4749, 4751), False, 'import mlflow\n'), ((5012, 5030), 'mlflow.start_run', 'mlflow.start_run', ([], {}), '()\n', (5028, 5030), False, 'import mlflow\n'), ((5587, 5612), 'mlflow.log_params', 'mlflow.log_params', (['params'], {}), '(params)\n', (5604, 5612), False, 'import mlflow\n'), ((5626, 5655), 'mlflow.log_metric', 'mlflow.log_metric', (['"""mae"""', 'mae'], {}), "('mae', mae)\n", (5643, 5655), False, 'import mlflow\n'), ((5806, 5825), 'mlflow.active_run', 'mlflow.active_run', ([], {}), '()\n', (5823, 5825), False, 'import mlflow\n'), ((3370, 3446), 'mlflow.xgboost.log_model', 'mlflow.xgboost.log_model', (['xgb', '"""model"""'], {'registered_model_name': '"""XGBRegressor"""'}), "(xgb, 'model', registered_model_name='XGBRegressor')\n", (3394, 3446), False, 'import mlflow\n'), ((4633, 4712), 'mlflow.sklearn.log_model', 'mlflow.sklearn.log_model', (['reg', '"""model"""'], {'registered_model_name': '"""LinearRegressor"""'}), "(reg, 'model', registered_model_name='LinearRegressor')\n", (4657, 4712), False, 'import mlflow\n'), ((5719, 5786), 'mlflow.sklearn.log_model', 'mlflow.sklearn.log_model', (['svr', '"""model"""'], {'registered_model_name': '"""SVR"""'}), "(svr, 'model', registered_model_name='SVR')\n", (5743, 5786), False, 'import mlflow\n'), ((3543, 3568), 'numpy.arange', 'np.arange', (['(0)', '(23.25)', '(0.25)'], {}), '(0, 23.25, 0.25)\n', (3552, 3568), True, 'import numpy as np\n'), ((4027, 4052), 'numpy.arange', 'np.arange', (['(0)', '(23.25)', '(0.25)'], {}), '(0, 23.25, 0.25)\n', (4036, 4052), True, 'import numpy as np\n'), ((4809, 4834), 'numpy.arange', 'np.arange', (['(0)', '(23.25)', '(0.25)'], {}), '(0, 23.25, 0.25)\n', (4818, 4834), True, 'import numpy as np\n'), ((5883, 5908), 'numpy.arange', 'np.arange', (['(0)', '(23.25)', '(0.25)'], {}), '(0, 23.25, 0.25)\n', (5892, 5908), True, 'import numpy as np\n')]
import os import dash_html_components as html import dash_core_components as dcc from dash.dependencies import Input, Output import dash_bio import pandas as pd import numpy as np import math import plotly.graph_objects as go from layout_helper import run_standalone_app text_style = {"color": "#506784", "font-family": "Open Sans"} _COMPONENT_ID = "pileup-browser" def description(): return "An interactive in-browser track viewer." def azure_url(file): return os.path.join( "https://sampleappsdata.blob.core.windows.net/dash-pileup-demo/rna/", file ) def header_colors(): return { "bg_color": "#0F5BA7", "font_color": "white", } def rna_differential(app): basal_lactate = { "url": azure_url("SRR1552454.fastq.gz.sampled.bam"), "indexUrl": azure_url("SRR1552454.fastq.gz.sampled.bam.bai"), } luminal_lactate = { "url": azure_url("SRR1552448.fastq.gz.sampled.bam"), "indexUrl": azure_url("SRR1552448.fastq.gz.sampled.bam.bai"), } HOSTED_TRACKS = { "range": {"contig": "chr1", "start": 54986297, "stop": 54991347}, "celltype": [ {"viz": "scale", "label": "Scale"}, {"viz": "location", "label": "Location"}, { "viz": "genes", "label": "genes", "source": "bigBed", "sourceOptions": {"url": azure_url("mm10.ncbiRefSeq.sorted.bb")}, }, { "viz": "coverage", "label": "Basal", "source": "bam", "sourceOptions": basal_lactate, }, { "viz": "pileup", "vizOptions": {"viewAsPairs": True}, "label": "Basal", "source": "bam", "sourceOptions": basal_lactate, }, { "viz": "coverage", "label": "Luminal", "source": "bam", "sourceOptions": luminal_lactate, }, { "viz": "pileup", "label": "Luminal", "source": "bam", "sourceOptions": luminal_lactate, }, ], } return HOSTED_TRACKS REFERENCE = { "label": "mm10", "url": "https://hgdownload.cse.ucsc.edu/goldenPath/mm10/bigZips/mm10.2bit", } DATAPATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "assets/data") # Differentially expressed genes (identified in R, see assets/data/rna/README.md) DE_dataframe = pd.read_csv(azure_url("DE_genes.csv")) # filter for the cell type condition DE_dataframe = DE_dataframe[ DE_dataframe["Comparison"] == "luminal__v__basal" ].reset_index() # add SNP column DE_dataframe["SNP"] = "NA" # get min and max effect sizes df_min = math.floor(min(DE_dataframe["log2FoldChange"])) df_max = math.ceil(max(DE_dataframe["log2FoldChange"])) def layout(app): HOSTED_CASE_DICT = rna_differential(app) return html.Div( id="pileup-body", className="app-body", children=[ html.Div( id="pileup-control-tabs", className="control-tabs", children=[ dcc.Tabs( id="pileup-tabs", value="data", children=[ dcc.Tab( label="Volcano plot", value="data", children=html.Div( className="control-tab", children=[ "Effect Size", dcc.RangeSlider( id="pileup-volcanoplot-input", min=df_min, max=df_max, step=None, marks={ i: {"label": str(i)} for i in range(df_min, df_max + 1, 2) }, value=[-1, 1], ), html.Br(), dcc.Graph( id="pileup-dashbio-volcanoplot", figure=dash_bio.VolcanoPlot( dataframe=DE_dataframe, margin=go.layout.Margin(l=0, r=0, b=0), legend={ "orientation": "h", "yanchor": "bottom", "y": 1.02, "bgcolor": "#f2f5fa", }, effect_size="log2FoldChange", effect_size_line=[-1, 1], title="Differentially Expressed Genes", genomewideline_value=-np.log10(0.05), p="padj", snp="SNP", gene="Gene", ), ), ], ), ), dcc.Tab( label="About this tutorial", value="description", children=html.Div( className="control-tab", children=[ html.H4( className="description", children="""Visualizing RNA-seq data with pileup.js and volcano plots""", ), dcc.Markdown( """ In this example, we use the pileup.js and volcano plot components from dash-bio to visualize two RNA-sequencing (RNA-seq) samples from two conditions. RNA-seq allows us to learn how the expression of genes changes between different samples of interest. Here, we are looking at RNA-seq from two samples that are taken from two different mouse cell types. We refer to these different cell types as basal and luminal cell types. On the right, we use pileup.js to visualize aligned reads from RNA-seq samples. On the left, we have a volcano plot, that visualizes the magnitude of change in gene expression between the two samples. On the x-axis, the `Effect Size` indicates the log2 fold change in expression between the two conditions. On the y-axis, `-log10(p)` indicates the -log10(p-value) for each gene. This p-value, along with the effect size, can help determine whether each gene is significantly differentially expressed between the conditions of interest. To explore a gene, you can click on a gene in the volcano plot. After clicking on a gene, the genomic region overlapping that gene will show up in the pileup.js browser on the right. Now, you can investigate RNA-seq alignments at each gene of interest. You may notice that genes with a negative effect size in the volcano plot have more RNA-seq reads in the top sample (the basal cell type), while genes with a positive effect size have more reads in the bottom sample (the luminal cell type). """ ), ], ), ), dcc.Tab( label="About pileup.js", value="what-is", children=html.Div( className="control-tab", children=[ html.H4( className="what-is", children="What is pileup.js?", ), dcc.Markdown( """ The Dash pileup.js component is a high-performance genomics data visualization component developed originally by the Hammer Lab (https://github.com/hammerlab/pileup.js). pileup.js supports visualization of genomic file formats, such as vcf, bam, and bigbed files. pileup.js additionally allows flexible interaction with non-standard data formats. Users can visualize GA4GH JSON formatted alignments, features and variants. Users can also connect with and visualize data stored in GA4GH formatted data stores. """ ), ], ), ), ], ) ], ), dcc.Loading( parent_className="dashbio-loading", id="pileup-output", children=html.Div( [ dash_bio.Pileup( id=_COMPONENT_ID, range=HOSTED_CASE_DICT["range"], reference=REFERENCE, tracks=HOSTED_CASE_DICT["celltype"], ) ] ), ), ], ) def callbacks(_app): HOSTED_CASE_DICT = rna_differential(_app) @_app.callback( Output("pileup-dashbio-volcanoplot", "figure"), [Input("pileup-volcanoplot-input", "value")], ) def update_volcano(effects): return dash_bio.VolcanoPlot( dataframe=DE_dataframe, margin=go.layout.Margin(l=0, r=0, b=0), legend={"orientation": "h", "yanchor": "bottom", "y": 1.02, "x": 0.0,}, effect_size="log2FoldChange", effect_size_line=effects, title="Differentially Expressed Genes", genomewideline_value=-np.log10(0.05), p="padj", snp="SNP", gene="Gene", ) @_app.callback( Output(_COMPONENT_ID, "range"), Input("pileup-dashbio-volcanoplot", "clickData") ) def update_range(point): if point is None: range = HOSTED_CASE_DICT["range"] else: # get genomic location of selected genes and goto pointText = point["points"][0]["text"] gene = pointText.split("GENE: ")[-1] row = DE_dataframe[DE_dataframe["Gene"] == gene].iloc[0] range = {"contig": row["chr"], "start": row["start"], "stop": row["end"]} return range app = run_standalone_app(layout, callbacks, header_colors, __file__) server = app.server if __name__ == "__main__": app.run_server(debug=True, port=8050)
[ "numpy.log10", "plotly.graph_objects.layout.Margin", "dash.dependencies.Output", "dash_html_components.Br", "os.path.join", "layout_helper.run_standalone_app", "dash.dependencies.Input", "dash_core_components.Markdown", "os.path.abspath", "dash_bio.Pileup", "dash_html_components.H4" ]
[((12471, 12533), 'layout_helper.run_standalone_app', 'run_standalone_app', (['layout', 'callbacks', 'header_colors', '__file__'], {}), '(layout, callbacks, header_colors, __file__)\n', (12489, 12533), False, 'from layout_helper import run_standalone_app\n'), ((477, 570), 'os.path.join', 'os.path.join', (['"""https://sampleappsdata.blob.core.windows.net/dash-pileup-demo/rna/"""', 'file'], {}), "(\n 'https://sampleappsdata.blob.core.windows.net/dash-pileup-demo/rna/', file)\n", (489, 570), False, 'import os\n'), ((2445, 2470), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (2460, 2470), False, 'import os\n'), ((11276, 11322), 'dash.dependencies.Output', 'Output', (['"""pileup-dashbio-volcanoplot"""', '"""figure"""'], {}), "('pileup-dashbio-volcanoplot', 'figure')\n", (11282, 11322), False, 'from dash.dependencies import Input, Output\n'), ((11918, 11948), 'dash.dependencies.Output', 'Output', (['_COMPONENT_ID', '"""range"""'], {}), "(_COMPONENT_ID, 'range')\n", (11924, 11948), False, 'from dash.dependencies import Input, Output\n'), ((11950, 11998), 'dash.dependencies.Input', 'Input', (['"""pileup-dashbio-volcanoplot"""', '"""clickData"""'], {}), "('pileup-dashbio-volcanoplot', 'clickData')\n", (11955, 11998), False, 'from dash.dependencies import Input, Output\n'), ((11333, 11375), 'dash.dependencies.Input', 'Input', (['"""pileup-volcanoplot-input"""', '"""value"""'], {}), "('pileup-volcanoplot-input', 'value')\n", (11338, 11375), False, 'from dash.dependencies import Input, Output\n'), ((11510, 11541), 'plotly.graph_objects.layout.Margin', 'go.layout.Margin', ([], {'l': '(0)', 'r': '(0)', 'b': '(0)'}), '(l=0, r=0, b=0)\n', (11526, 11541), True, 'import plotly.graph_objects as go\n'), ((11793, 11807), 'numpy.log10', 'np.log10', (['(0.05)'], {}), '(0.05)\n', (11801, 11807), True, 'import numpy as np\n'), ((10841, 10969), 'dash_bio.Pileup', 'dash_bio.Pileup', ([], {'id': '_COMPONENT_ID', 'range': "HOSTED_CASE_DICT['range']", 'reference': 'REFERENCE', 'tracks': "HOSTED_CASE_DICT['celltype']"}), "(id=_COMPONENT_ID, range=HOSTED_CASE_DICT['range'],\n reference=REFERENCE, tracks=HOSTED_CASE_DICT['celltype'])\n", (10856, 10969), False, 'import dash_bio\n'), ((4437, 4446), 'dash_html_components.Br', 'html.Br', ([], {}), '()\n', (4444, 4446), True, 'import dash_html_components as html\n'), ((6248, 6408), 'dash_html_components.H4', 'html.H4', ([], {'className': '"""description"""', 'children': '"""Visualizing RNA-seq data with pileup.js\n and volcano plots"""'}), '(className=\'description\', children=\n """Visualizing RNA-seq data with pileup.js\n and volcano plots"""\n )\n', (6255, 6408), True, 'import dash_html_components as html\n'), ((6571, 8764), 'dash_core_components.Markdown', 'dcc.Markdown', (['"""\n In this example, we use the pileup.js and volcano plot components from dash-bio\n to visualize two RNA-sequencing\n (RNA-seq) samples from two conditions. RNA-seq allows us to learn how the expression\n of genes changes between different samples of interest. Here, we are looking at\n RNA-seq from two samples that are taken from two different mouse cell types.\n We refer to these different cell types as basal and luminal cell types.\n\n On the right, we use pileup.js to visualize aligned reads from RNA-seq samples.\n On the left, we have a volcano plot, that visualizes the magnitude of change\n in gene expression between the two samples. On the x-axis, the `Effect Size`\n indicates the log2 fold change in expression\n between the two conditions. On the y-axis, `-log10(p)` indicates the -log10(p-value)\n for each gene. This p-value, along with the effect size,\n can help determine whether each gene is significantly\n differentially expressed between the conditions of interest.\n\n To explore a gene, you can click on a gene in the volcano plot. After clicking on\n a gene, the genomic region overlapping that gene will show up in the pileup.js\n browser on the right. Now, you can investigate RNA-seq alignments at each\n gene of interest. You may notice that genes with a negative effect size in the volcano\n plot have more RNA-seq reads in the top sample (the basal cell type), while genes\n with a positive effect size have more reads in the bottom sample\n (the luminal cell type).\n """'], {}), '(\n """\n In this example, we use the pileup.js and volcano plot components from dash-bio\n to visualize two RNA-sequencing\n (RNA-seq) samples from two conditions. RNA-seq allows us to learn how the expression\n of genes changes between different samples of interest. Here, we are looking at\n RNA-seq from two samples that are taken from two different mouse cell types.\n We refer to these different cell types as basal and luminal cell types.\n\n On the right, we use pileup.js to visualize aligned reads from RNA-seq samples.\n On the left, we have a volcano plot, that visualizes the magnitude of change\n in gene expression between the two samples. On the x-axis, the `Effect Size`\n indicates the log2 fold change in expression\n between the two conditions. On the y-axis, `-log10(p)` indicates the -log10(p-value)\n for each gene. This p-value, along with the effect size,\n can help determine whether each gene is significantly\n differentially expressed between the conditions of interest.\n\n To explore a gene, you can click on a gene in the volcano plot. After clicking on\n a gene, the genomic region overlapping that gene will show up in the pileup.js\n browser on the right. Now, you can investigate RNA-seq alignments at each\n gene of interest. You may notice that genes with a negative effect size in the volcano\n plot have more RNA-seq reads in the top sample (the basal cell type), while genes\n with a positive effect size have more reads in the bottom sample\n (the luminal cell type).\n """\n )\n', (6583, 8764), True, 'import dash_core_components as dcc\n'), ((9289, 9348), 'dash_html_components.H4', 'html.H4', ([], {'className': '"""what-is"""', 'children': '"""What is pileup.js?"""'}), "(className='what-is', children='What is pileup.js?')\n", (9296, 9348), True, 'import dash_html_components as html\n'), ((9521, 10381), 'dash_core_components.Markdown', 'dcc.Markdown', (['"""\n The Dash pileup.js component is a high-performance genomics\n data visualization component developed originally by the Hammer Lab\n (https://github.com/hammerlab/pileup.js). pileup.js\n supports visualization of genomic file formats, such as vcf,\n bam, and bigbed files. pileup.js additionally allows flexible\n interaction with non-standard data formats. Users can visualize\n GA4GH JSON formatted alignments, features and variants. Users can\n also connect with and visualize data stored in GA4GH formatted data\n stores.\n """'], {}), '(\n """\n The Dash pileup.js component is a high-performance genomics\n data visualization component developed originally by the Hammer Lab\n (https://github.com/hammerlab/pileup.js). pileup.js\n supports visualization of genomic file formats, such as vcf,\n bam, and bigbed files. pileup.js additionally allows flexible\n interaction with non-standard data formats. Users can visualize\n GA4GH JSON formatted alignments, features and variants. Users can\n also connect with and visualize data stored in GA4GH formatted data\n stores.\n """\n )\n', (9533, 10381), True, 'import dash_core_components as dcc\n'), ((4776, 4807), 'plotly.graph_objects.layout.Margin', 'go.layout.Margin', ([], {'l': '(0)', 'r': '(0)', 'b': '(0)'}), '(l=0, r=0, b=0)\n', (4792, 4807), True, 'import plotly.graph_objects as go\n'), ((5509, 5523), 'numpy.log10', 'np.log10', (['(0.05)'], {}), '(0.05)\n', (5517, 5523), True, 'import numpy as np\n')]
import matplotlib.pyplot as plt import numpy as np from lms_code.analysis.run_bem import get_slip_magnitude import lms_code.lib.rep2 as rep2 import lms_code.plots.plot_all as lms_plot def main(): lms_plot.setup() fig = plt.figure() which_model = 'all_details' bem_soln = rep2.load('bem_' + which_model) shortening = rep2.load('shortening_estimate_' + which_model) est = shortening['lsqr_shortening'] est_low = est - shortening['lsqr_shortening_error'] est_high = est + shortening['lsqr_shortening_error'] total_length = 0.0 slip = 0.0 slip_low = 0.0 slip_high = 0.0 joint = [4.20012e5 + 1.6, -2.006e4 - 5] for e in bem_soln['fault_mesh']: if e.vertex1.loc[0] < joint[0] - 10: continue total_length += e.length slip_mag = np.linalg.norm(get_slip_magnitude(e)) slip += e.length * est * slip_mag slip_low += e.length * est_low * slip_mag slip_high += e.length * est_high * slip_mag s = (slip / total_length) / 1000 s_low = (slip_low / total_length) / 1000 s_high = (slip_high / total_length) / 1000 slip_err = s_high - s # s = 6.1 / 1000 # s_low = 4.6 / 1000 # s_high = 7.6 / 1000 T = np.linspace(0, 3000, 100) d = T * s T_high = d / s_low T_low = d / s_high wenchuan_d = 4.0 wenchuan_T_low = wenchuan_d / s_low wenchuan_T = wenchuan_d / s wenchuan_T_high = wenchuan_d / s_high print("Wenchuan recurrence: " + str(wenchuan_T) + " (low: " + str(wenchuan_T_low) + ", high: " + str(wenchuan_T_high) + ")") a_wells = 6.93 b_wells = 0.82 mag7_ad = np.exp((7.0 - a_wells) / b_wells) mag7_T = mag7_ad / s paleo_T = 2300 paleo_ad = paleo_T * s paleo_mag = (np.log(paleo_ad) * b_wells) + a_wells plt.plot(d, T, 'k-') plt.fill_between(d, T_low, T_high, facecolor = '#AAAAAA') plt.plot([0, paleo_ad + 100], [paleo_T, paleo_T], 'k--') plt.plot([wenchuan_d, mag7_ad, paleo_ad], [wenchuan_T, mag7_T, paleo_T], linestyle = 'None', marker = 'o', markeredgewidth = 4.0, markeredgecolor = (0, 0, 0, 1.0), markerfacecolor = (1, 1, 1, 1.0), markersize = 15) # Plot Wenchuan text = 'Wenchuan-like $\\textrm{M}_{\\textrm{w}}$ 7.9 (' + '%.0f'%wenchuan_d + ' m, ' +\ '%.0f'%wenchuan_T + ' years)' plt.annotate(text, (wenchuan_d, wenchuan_T), xytext = (wenchuan_d + 0.5, wenchuan_T - 50)) # Plot the Mw 7 pt text = 'Typical $\\textrm{M}_{\\textrm{w}}$ 7.0 (' + '%.0f'%mag7_ad + ' m, ' +\ '%.0f'%mag7_T + ' years)' plt.annotate(text, (mag7_ad, mag7_T), xytext = (mag7_ad + 0.9, mag7_T - 30)) # Plot the paleoseismic pt text = 'Low paleoseismic estimate' plt.text(1.7, 2350, text) text = '($Ran$ $et$ $al.$ 2010)' plt.text(1.7, 2200, text) text = '$\\textrm{M}_{\\textrm{w}}$ ' + '%0.f'%paleo_mag + ', ' + '%0.f'%paleo_ad + ' m' plt.annotate(text, (paleo_ad, paleo_T), xytext = (paleo_ad - 3.2, paleo_T + 30)) plt.text(2.0, 40, '($Wells$ $and$ $Coppersmith$ 1994)') plt.text(0.5, 1800, 'average slip rate = ' + '%.1f'%(s * 1000) + ' $\pm$ %.1f'%(slip_err * 1000) + ' mm/yr') plt.ylabel('$T$ (years)') plt.xlabel('$d$ (meters)') plt.ylim([0, 2500]) plt.xlim([0, 2500 * s]) width = 7.0 fig.set_size_inches([width, (6.0 / 8.0) * width]) plt.savefig('hazard_' + which_model) if __name__ == '__main__': main()
[ "matplotlib.pyplot.text", "matplotlib.pyplot.savefig", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.plot", "numpy.log", "lms_code.plots.plot_all.setup", "matplotlib.pyplot.fill_between", "numpy.exp", "lms_code.lib.rep2.load", "matplotlib.pyplot.figure", "numpy.lin...
[((201, 217), 'lms_code.plots.plot_all.setup', 'lms_plot.setup', ([], {}), '()\n', (215, 217), True, 'import lms_code.plots.plot_all as lms_plot\n'), ((228, 240), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (238, 240), True, 'import matplotlib.pyplot as plt\n'), ((289, 320), 'lms_code.lib.rep2.load', 'rep2.load', (["('bem_' + which_model)"], {}), "('bem_' + which_model)\n", (298, 320), True, 'import lms_code.lib.rep2 as rep2\n'), ((338, 385), 'lms_code.lib.rep2.load', 'rep2.load', (["('shortening_estimate_' + which_model)"], {}), "('shortening_estimate_' + which_model)\n", (347, 385), True, 'import lms_code.lib.rep2 as rep2\n'), ((1235, 1260), 'numpy.linspace', 'np.linspace', (['(0)', '(3000)', '(100)'], {}), '(0, 3000, 100)\n', (1246, 1260), True, 'import numpy as np\n'), ((1639, 1672), 'numpy.exp', 'np.exp', (['((7.0 - a_wells) / b_wells)'], {}), '((7.0 - a_wells) / b_wells)\n', (1645, 1672), True, 'import numpy as np\n'), ((1805, 1825), 'matplotlib.pyplot.plot', 'plt.plot', (['d', 'T', '"""k-"""'], {}), "(d, T, 'k-')\n", (1813, 1825), True, 'import matplotlib.pyplot as plt\n'), ((1830, 1885), 'matplotlib.pyplot.fill_between', 'plt.fill_between', (['d', 'T_low', 'T_high'], {'facecolor': '"""#AAAAAA"""'}), "(d, T_low, T_high, facecolor='#AAAAAA')\n", (1846, 1885), True, 'import matplotlib.pyplot as plt\n'), ((1892, 1948), 'matplotlib.pyplot.plot', 'plt.plot', (['[0, paleo_ad + 100]', '[paleo_T, paleo_T]', '"""k--"""'], {}), "([0, paleo_ad + 100], [paleo_T, paleo_T], 'k--')\n", (1900, 1948), True, 'import matplotlib.pyplot as plt\n'), ((1953, 2164), 'matplotlib.pyplot.plot', 'plt.plot', (['[wenchuan_d, mag7_ad, paleo_ad]', '[wenchuan_T, mag7_T, paleo_T]'], {'linestyle': '"""None"""', 'marker': '"""o"""', 'markeredgewidth': '(4.0)', 'markeredgecolor': '(0, 0, 0, 1.0)', 'markerfacecolor': '(1, 1, 1, 1.0)', 'markersize': '(15)'}), "([wenchuan_d, mag7_ad, paleo_ad], [wenchuan_T, mag7_T, paleo_T],\n linestyle='None', marker='o', markeredgewidth=4.0, markeredgecolor=(0, \n 0, 0, 1.0), markerfacecolor=(1, 1, 1, 1.0), markersize=15)\n", (1961, 2164), True, 'import matplotlib.pyplot as plt\n'), ((2406, 2499), 'matplotlib.pyplot.annotate', 'plt.annotate', (['text', '(wenchuan_d, wenchuan_T)'], {'xytext': '(wenchuan_d + 0.5, wenchuan_T - 50)'}), '(text, (wenchuan_d, wenchuan_T), xytext=(wenchuan_d + 0.5, \n wenchuan_T - 50))\n', (2418, 2499), True, 'import matplotlib.pyplot as plt\n'), ((2663, 2737), 'matplotlib.pyplot.annotate', 'plt.annotate', (['text', '(mag7_ad, mag7_T)'], {'xytext': '(mag7_ad + 0.9, mag7_T - 30)'}), '(text, (mag7_ad, mag7_T), xytext=(mag7_ad + 0.9, mag7_T - 30))\n', (2675, 2737), True, 'import matplotlib.pyplot as plt\n'), ((2831, 2856), 'matplotlib.pyplot.text', 'plt.text', (['(1.7)', '(2350)', 'text'], {}), '(1.7, 2350, text)\n', (2839, 2856), True, 'import matplotlib.pyplot as plt\n'), ((2899, 2924), 'matplotlib.pyplot.text', 'plt.text', (['(1.7)', '(2200)', 'text'], {}), '(1.7, 2200, text)\n', (2907, 2924), True, 'import matplotlib.pyplot as plt\n'), ((3022, 3100), 'matplotlib.pyplot.annotate', 'plt.annotate', (['text', '(paleo_ad, paleo_T)'], {'xytext': '(paleo_ad - 3.2, paleo_T + 30)'}), '(text, (paleo_ad, paleo_T), xytext=(paleo_ad - 3.2, paleo_T + 30))\n', (3034, 3100), True, 'import matplotlib.pyplot as plt\n'), ((3124, 3179), 'matplotlib.pyplot.text', 'plt.text', (['(2.0)', '(40)', '"""($Wells$ $and$ $Coppersmith$ 1994)"""'], {}), "(2.0, 40, '($Wells$ $and$ $Coppersmith$ 1994)')\n", (3132, 3179), True, 'import matplotlib.pyplot as plt\n'), ((3184, 3302), 'matplotlib.pyplot.text', 'plt.text', (['(0.5)', '(1800)', "('average slip rate = ' + '%.1f' % (s * 1000) + ' $\\\\pm$ %.1f' % (slip_err *\n 1000) + ' mm/yr')"], {}), "(0.5, 1800, 'average slip rate = ' + '%.1f' % (s * 1000) + \n ' $\\\\pm$ %.1f' % (slip_err * 1000) + ' mm/yr')\n", (3192, 3302), True, 'import matplotlib.pyplot as plt\n'), ((3297, 3322), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""$T$ (years)"""'], {}), "('$T$ (years)')\n", (3307, 3322), True, 'import matplotlib.pyplot as plt\n'), ((3327, 3353), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""$d$ (meters)"""'], {}), "('$d$ (meters)')\n", (3337, 3353), True, 'import matplotlib.pyplot as plt\n'), ((3358, 3377), 'matplotlib.pyplot.ylim', 'plt.ylim', (['[0, 2500]'], {}), '([0, 2500])\n', (3366, 3377), True, 'import matplotlib.pyplot as plt\n'), ((3382, 3405), 'matplotlib.pyplot.xlim', 'plt.xlim', (['[0, 2500 * s]'], {}), '([0, 2500 * s])\n', (3390, 3405), True, 'import matplotlib.pyplot as plt\n'), ((3480, 3516), 'matplotlib.pyplot.savefig', 'plt.savefig', (["('hazard_' + which_model)"], {}), "('hazard_' + which_model)\n", (3491, 3516), True, 'import matplotlib.pyplot as plt\n'), ((832, 853), 'lms_code.analysis.run_bem.get_slip_magnitude', 'get_slip_magnitude', (['e'], {}), '(e)\n', (850, 853), False, 'from lms_code.analysis.run_bem import get_slip_magnitude\n'), ((1762, 1778), 'numpy.log', 'np.log', (['paleo_ad'], {}), '(paleo_ad)\n', (1768, 1778), True, 'import numpy as np\n')]
import argparse import os import pickle import random import time from tqdm import tqdm from multiprocessing import Pool import torch import numpy as np import matplotlib.pyplot as plt from util.bioinformatics_algorithms.edit_distance import cross_distance_matrix from util.data_handling.string_generator import IndependentGenerator, k_mutations def generate_batch(args): # generates a single batch of sequences and computes their distance matrix batch_size, len_sequence, string_generator, max_changes = args sequences = [string_generator.generate(len_sequence)] for i in range(batch_size - 1): S_ref = sequences[random.randint(0, i)] S = k_mutations(S_ref, 1 + np.random.geometric(max_changes / len_sequence)) sequences.append(S) sequences_str = ["".join(chr(s + 97) for s in S) for S in sequences] distances = cross_distance_matrix(sequences_str, sequences_str) return sequences, distances class EditDistanceDatasetGenerator: def __init__(self, N_batches, batch_size, len_sequence, max_changes, string_generator, n_thread=5, seed=0, plot=False): self.sequences = {} self.distances = {} random.seed(seed) for dataset in N_batches.keys(): print("Generating", dataset, end=':') # parallel batch generation with Pool(n_thread) as pool: start = time.time() batches = list( tqdm( pool.imap(generate_batch, [(batch_size[dataset], len_sequence[dataset], string_generator, max_changes[dataset]) for _ in range(N_batches[dataset])]), total=N_batches[dataset], desc="Batches " + dataset, )) print("Time to compute the batches: {}".format(time.time() - start)) # concatenate all batches batches = list(zip(*batches)) sequence_batches = batches[0] distance_batches = batches[1] # plot histogram of distances if plot: plt.hist(x=np.reshape(np.asarray(distance_batches), (-1)), bins='auto', color='#0504aa', alpha=0.7, rwidth=0.85) plt.show() self.sequences[dataset] = torch.from_numpy(np.asarray(sequence_batches)).long() self.distances[dataset] = torch.from_numpy(np.asarray(distance_batches)).float() def save_as_pickle(self, filename): directory = os.path.dirname(filename) if directory != '' and not os.path.exists(directory): os.makedirs(directory) with open(filename, 'wb') as f: pickle.dump((self.sequences, self.distances), f) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--out', type=str, default="../data/edit_synthetic_small.pkl", help='Output data path') parser.add_argument('--train_size', type=int, default=1400, help='Number of training batches') parser.add_argument('--val_size', type=int, default=200, help='Number of validation batches') parser.add_argument('--test_size', type=int, default=400, help='Number of test batches') parser.add_argument('--batch_size', type=int, default=50, help='Sequences per batch') parser.add_argument('--len_sequence', type=int, default=1024, help='Length of the sequences') parser.add_argument('--max_changes', type=float, default=13, help='Parameter of changes distribution') parser.add_argument('--seed', type=int, default=0, help='Random seed') args = parser.parse_args() generator = IndependentGenerator(seed=args.seed) data = EditDistanceDatasetGenerator\ (N_batches={"train": args.train_size, "val": args.val_size, "test": args.test_size}, batch_size={"train": args.batch_size, "val": args.batch_size, "test": args.batch_size}, len_sequence={"train": args.len_sequence, "val": args.len_sequence, "test": args.len_sequence}, max_changes={"train": args.max_changes, "val": args.max_changes, "test": args.max_changes}, seed=args.seed, string_generator=generator) data.save_as_pickle(args.out)
[ "os.path.exists", "numpy.random.geometric", "pickle.dump", "argparse.ArgumentParser", "os.makedirs", "util.bioinformatics_algorithms.edit_distance.cross_distance_matrix", "numpy.asarray", "random.seed", "os.path.dirname", "multiprocessing.Pool", "util.data_handling.string_generator.IndependentGe...
[((865, 916), 'util.bioinformatics_algorithms.edit_distance.cross_distance_matrix', 'cross_distance_matrix', (['sequences_str', 'sequences_str'], {}), '(sequences_str, sequences_str)\n', (886, 916), False, 'from util.bioinformatics_algorithms.edit_distance import cross_distance_matrix\n'), ((2796, 2821), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (2819, 2821), False, 'import argparse\n'), ((3642, 3678), 'util.data_handling.string_generator.IndependentGenerator', 'IndependentGenerator', ([], {'seed': 'args.seed'}), '(seed=args.seed)\n', (3662, 3678), False, 'from util.data_handling.string_generator import IndependentGenerator, k_mutations\n'), ((1176, 1193), 'random.seed', 'random.seed', (['seed'], {}), '(seed)\n', (1187, 1193), False, 'import random\n'), ((2529, 2554), 'os.path.dirname', 'os.path.dirname', (['filename'], {}), '(filename)\n', (2544, 2554), False, 'import os\n'), ((641, 661), 'random.randint', 'random.randint', (['(0)', 'i'], {}), '(0, i)\n', (655, 661), False, 'import random\n'), ((2629, 2651), 'os.makedirs', 'os.makedirs', (['directory'], {}), '(directory)\n', (2640, 2651), False, 'import os\n'), ((2705, 2753), 'pickle.dump', 'pickle.dump', (['(self.sequences, self.distances)', 'f'], {}), '((self.sequences, self.distances), f)\n', (2716, 2753), False, 'import pickle\n'), ((698, 745), 'numpy.random.geometric', 'np.random.geometric', (['(max_changes / len_sequence)'], {}), '(max_changes / len_sequence)\n', (717, 745), True, 'import numpy as np\n'), ((1344, 1358), 'multiprocessing.Pool', 'Pool', (['n_thread'], {}), '(n_thread)\n', (1348, 1358), False, 'from multiprocessing import Pool\n'), ((1392, 1403), 'time.time', 'time.time', ([], {}), '()\n', (1401, 1403), False, 'import time\n'), ((2271, 2281), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2279, 2281), True, 'import matplotlib.pyplot as plt\n'), ((2590, 2615), 'os.path.exists', 'os.path.exists', (['directory'], {}), '(directory)\n', (2604, 2615), False, 'import os\n'), ((2338, 2366), 'numpy.asarray', 'np.asarray', (['sequence_batches'], {}), '(sequence_batches)\n', (2348, 2366), True, 'import numpy as np\n'), ((2430, 2458), 'numpy.asarray', 'np.asarray', (['distance_batches'], {}), '(distance_batches)\n', (2440, 2458), True, 'import numpy as np\n'), ((1875, 1886), 'time.time', 'time.time', ([], {}), '()\n', (1884, 1886), False, 'import time\n'), ((2164, 2192), 'numpy.asarray', 'np.asarray', (['distance_batches'], {}), '(distance_batches)\n', (2174, 2192), True, 'import numpy as np\n')]
import time import os os.environ["CUDA_VISIBLE_DEVICES"] = "-1" import tensorflow as tf from tensorflow.python.saved_model import tag_constants from PIL import Image from absl import app, flags, logging import cv2 import numpy as np from absl.flags import FLAGS from tensorflow.compat.v1 import ConfigProto from tensorflow.compat.v1 import InteractiveSession from tensorflow.keras.models import load_model from core.utils import * from centroid_tracking.tracker import Tracker from core.analysis import analysis from core.analysis import create_dashboard from core.posemodule import poseDetector import tkinter as tk flags.DEFINE_string('framework', 'tf', '(tf, tflite, trt') flags.DEFINE_string('weights_ball', './checkpoints/3l4b3_ball_416', 'path to weights ball file') flags.DEFINE_string('weights_palm', './checkpoints/custom-tiny-palm-416', 'path to weights palm file') flags.DEFINE_integer('size', 416, 'resize images to') flags.DEFINE_boolean('tiny', True, 'yolo or yolo-tiny') flags.DEFINE_string('model', 'yolov4-tiny-3l', 'yolov3 or yolov4') flags.DEFINE_string('video', 'src/video0.mov', 'path to input video') flags.DEFINE_float('iou', 0.25, 'iou threshold') flags.DEFINE_float('score', 0.30, 'score threshold') flags.DEFINE_string('output_format', 'XVID', 'codec used in VideoWriter when saving video to file') flags.DEFINE_string('output', 'output.avi', 'path to output video') flags.DEFINE_string('demo_output', 'demo.avi', 'path to demo output video') flags.DEFINE_string('ptn_model', 'checkpoints/pattern_model.h5', 'path to pattern recognition model') flags.DEFINE_boolean('gpu', True, 'activate gpu - True else False') def main(_argv): # initialize all the FLAGS setting input_size = FLAGS.size video_path = FLAGS.video gpu = FLAGS.gpu weights_ball = FLAGS.weights_ball weights_palm = FLAGS.weights_palm score = FLAGS.score iou = FLAGS.iou pattern_model = FLAGS.ptn_model output = FLAGS.output demo_output = FLAGS.demo_output output_format = FLAGS.output_format if gpu: # set up gpu setting physical_devices = tf.config.experimental.list_physical_devices('GPU') if len(physical_devices) > 0: tf.config.experimental.set_memory_growth(physical_devices[0], True) config = ConfigProto() config.gpu_options.allow_growth = True session = InteractiveSession(config=config) # load in all the models saved_model_loaded_ball = tf.saved_model.load(weights_ball, tags=[tag_constants.SERVING]) infer_ball = saved_model_loaded_ball.signatures['serving_default'] pattern_model = load_model(pattern_model) pose_detector = poseDetector() # human pose estimator # read in the video print("Video from: ", video_path) try: vid = cv2.VideoCapture(int(video_path)) # 0 - real time camera access except: vid = cv2.VideoCapture(video_path) # else - video input # get os resolution for display purpose rescale_width, rescale_height, image_width, image_height = resolution_display(vid) # initialize video writer if output: fps = 20 codec = cv2.VideoWriter_fourcc(*output_format) out = cv2.VideoWriter(output, codec, fps, (image_width,image_height)) demo_out = cv2.VideoWriter(demo_output, codec, fps, (image_width,image_height)) tracker = Tracker() # initialize tracker ptns = [] # start capturing and detection while True: return_value, frame = vid.read() if not return_value: print("Video processing complete") os._exit(0) frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) frame = cv2.resize(frame, (image_width,image_height)) demo = np.zeros((image_height, image_width, 3), np.uint8) prev_time = time.time() # fps counting # human pose estimation sucess, demo = pose_detector.findPose(frame, demo) # run the detection only if human pose found if sucess: lmList = pose_detector.findPosition(demo, draw=False) right_palm, left_palm = pose_detector.findPalm() # ball detection image_data = cv2.resize(frame, (input_size, input_size)) image_data = image_data / 255. image_data = image_data[np.newaxis, ...].astype(np.float32) # capture the detection box batch_data = tf.constant(image_data) pred_bbox_ball = infer_ball(batch_data) for key, value in pred_bbox_ball.items(): boxes_ball = value[:, :, 0:4] pred_conf_ball = value[:, :, 4:] # non max suppression boxes, scores, classes, valid_detections = tf.image.combined_non_max_suppression( boxes=tf.reshape(boxes_ball, (tf.shape(boxes_ball)[0], -1, 1, 4)), scores=tf.reshape( pred_conf_ball, (tf.shape(pred_conf_ball)[0], -1, tf.shape(pred_conf_ball)[-1])), max_output_size_per_class=50, max_total_size=50, iou_threshold=iou, score_threshold=score ) # finalized pred bbox pred_bbox = [boxes.numpy(), scores.numpy(), classes.numpy(), valid_detections.numpy()] # perform unbound tracking pair_ball = tracker.track(frame, pred_bbox) bound_ball = mapping(pair_ball, [right_palm,left_palm],True) tracker.object_checking(bound_ball) bound_ball = mapping(tracker.pair_ball, [right_palm,left_palm]) bound_ball_copy = copy.deepcopy(bound_ball) unbound_results = classification(frame, bound_ball, tracker.prev_pair_ball, tracker.pair_ball, pattern_model) # analysis result and display on dashboard frame = create_dashboard(frame) frame = analysis(pair_ball, tracker.pair_ball, frame) frame = pose_detector.distance_estimation(frame) frame, dmeo = pose_detector.find_Elbow_angle(frame, demo) # perform bound tracking demo, pred_balls = tracker.bound_tracking(demo, unbound_results, bound_ball_copy) bound_results = classification(frame, pred_balls, tracker.prev_pair_ball, tracker.pair_ball, pattern_model) results = unbound_results + bound_results bound_ball.extend(pred_balls) # display result - simulation and draw bbox on frame demo, ptns = display_demo(demo, results, ptns, bound_ball, tracker.pair_ball, [right_palm,left_palm]) frame = draw_bbox(frame, bound_ball, tracker.pair_ball, [right_palm,left_palm]) # display frame frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR) re_frame = cv2.resize(frame, (rescale_width,rescale_height)) re_demo = cv2.resize(demo, (rescale_width,rescale_height)) # set the position for output and demo result window if sucess: cv2.imshow("output", re_frame) cv2.imshow("demo", re_demo) else: frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) cv2.imshow("output", frame) cv2.imshow("demo", demo) cv2.moveWindow("output", 0, 0) cv2.moveWindow("demo", int(rescale_width), 0) if cv2.waitKey(1) & 0xFF == ord('q'): break # printout fps curr_time = time.time() exec_time = 1.0 / (curr_time - prev_time) print("FPS: %.2f" % exec_time) print() print() # save both output and demo results if output: out.write(frame) if demo_output: demo_out.write(demo) if __name__ == '__main__': try: app.run(main) except SystemExit: pass
[ "tensorflow.shape", "cv2.imshow", "core.analysis.create_dashboard", "tensorflow.keras.models.load_model", "absl.flags.DEFINE_float", "tensorflow.saved_model.load", "cv2.moveWindow", "centroid_tracking.tracker.Tracker", "absl.flags.DEFINE_boolean", "cv2.VideoWriter", "absl.app.run", "cv2.VideoW...
[((619, 677), 'absl.flags.DEFINE_string', 'flags.DEFINE_string', (['"""framework"""', '"""tf"""', '"""(tf, tflite, trt"""'], {}), "('framework', 'tf', '(tf, tflite, trt')\n", (638, 677), False, 'from absl import app, flags, logging\n'), ((678, 778), 'absl.flags.DEFINE_string', 'flags.DEFINE_string', (['"""weights_ball"""', '"""./checkpoints/3l4b3_ball_416"""', '"""path to weights ball file"""'], {}), "('weights_ball', './checkpoints/3l4b3_ball_416',\n 'path to weights ball file')\n", (697, 778), False, 'from absl import app, flags, logging\n'), ((795, 901), 'absl.flags.DEFINE_string', 'flags.DEFINE_string', (['"""weights_palm"""', '"""./checkpoints/custom-tiny-palm-416"""', '"""path to weights palm file"""'], {}), "('weights_palm', './checkpoints/custom-tiny-palm-416',\n 'path to weights palm file')\n", (814, 901), False, 'from absl import app, flags, logging\n'), ((918, 971), 'absl.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""size"""', '(416)', '"""resize images to"""'], {}), "('size', 416, 'resize images to')\n", (938, 971), False, 'from absl import app, flags, logging\n'), ((972, 1027), 'absl.flags.DEFINE_boolean', 'flags.DEFINE_boolean', (['"""tiny"""', '(True)', '"""yolo or yolo-tiny"""'], {}), "('tiny', True, 'yolo or yolo-tiny')\n", (992, 1027), False, 'from absl import app, flags, logging\n'), ((1028, 1094), 'absl.flags.DEFINE_string', 'flags.DEFINE_string', (['"""model"""', '"""yolov4-tiny-3l"""', '"""yolov3 or yolov4"""'], {}), "('model', 'yolov4-tiny-3l', 'yolov3 or yolov4')\n", (1047, 1094), False, 'from absl import app, flags, logging\n'), ((1095, 1164), 'absl.flags.DEFINE_string', 'flags.DEFINE_string', (['"""video"""', '"""src/video0.mov"""', '"""path to input video"""'], {}), "('video', 'src/video0.mov', 'path to input video')\n", (1114, 1164), False, 'from absl import app, flags, logging\n'), ((1165, 1213), 'absl.flags.DEFINE_float', 'flags.DEFINE_float', (['"""iou"""', '(0.25)', '"""iou threshold"""'], {}), "('iou', 0.25, 'iou threshold')\n", (1183, 1213), False, 'from absl import app, flags, logging\n'), ((1214, 1265), 'absl.flags.DEFINE_float', 'flags.DEFINE_float', (['"""score"""', '(0.3)', '"""score threshold"""'], {}), "('score', 0.3, 'score threshold')\n", (1232, 1265), False, 'from absl import app, flags, logging\n'), ((1267, 1370), 'absl.flags.DEFINE_string', 'flags.DEFINE_string', (['"""output_format"""', '"""XVID"""', '"""codec used in VideoWriter when saving video to file"""'], {}), "('output_format', 'XVID',\n 'codec used in VideoWriter when saving video to file')\n", (1286, 1370), False, 'from absl import app, flags, logging\n'), ((1367, 1434), 'absl.flags.DEFINE_string', 'flags.DEFINE_string', (['"""output"""', '"""output.avi"""', '"""path to output video"""'], {}), "('output', 'output.avi', 'path to output video')\n", (1386, 1434), False, 'from absl import app, flags, logging\n'), ((1435, 1510), 'absl.flags.DEFINE_string', 'flags.DEFINE_string', (['"""demo_output"""', '"""demo.avi"""', '"""path to demo output video"""'], {}), "('demo_output', 'demo.avi', 'path to demo output video')\n", (1454, 1510), False, 'from absl import app, flags, logging\n'), ((1511, 1616), 'absl.flags.DEFINE_string', 'flags.DEFINE_string', (['"""ptn_model"""', '"""checkpoints/pattern_model.h5"""', '"""path to pattern recognition model"""'], {}), "('ptn_model', 'checkpoints/pattern_model.h5',\n 'path to pattern recognition model')\n", (1530, 1616), False, 'from absl import app, flags, logging\n'), ((1613, 1680), 'absl.flags.DEFINE_boolean', 'flags.DEFINE_boolean', (['"""gpu"""', '(True)', '"""activate gpu - True else False"""'], {}), "('gpu', True, 'activate gpu - True else False')\n", (1633, 1680), False, 'from absl import app, flags, logging\n'), ((2502, 2565), 'tensorflow.saved_model.load', 'tf.saved_model.load', (['weights_ball'], {'tags': '[tag_constants.SERVING]'}), '(weights_ball, tags=[tag_constants.SERVING])\n', (2521, 2565), True, 'import tensorflow as tf\n'), ((2657, 2682), 'tensorflow.keras.models.load_model', 'load_model', (['pattern_model'], {}), '(pattern_model)\n', (2667, 2682), False, 'from tensorflow.keras.models import load_model\n'), ((2703, 2717), 'core.posemodule.poseDetector', 'poseDetector', ([], {}), '()\n', (2715, 2717), False, 'from core.posemodule import poseDetector\n'), ((3398, 3407), 'centroid_tracking.tracker.Tracker', 'Tracker', ([], {}), '()\n', (3405, 3407), False, 'from centroid_tracking.tracker import Tracker\n'), ((2142, 2193), 'tensorflow.config.experimental.list_physical_devices', 'tf.config.experimental.list_physical_devices', (['"""GPU"""'], {}), "('GPU')\n", (2186, 2193), True, 'import tensorflow as tf\n'), ((2329, 2342), 'tensorflow.compat.v1.ConfigProto', 'ConfigProto', ([], {}), '()\n', (2340, 2342), False, 'from tensorflow.compat.v1 import ConfigProto\n'), ((2408, 2441), 'tensorflow.compat.v1.InteractiveSession', 'InteractiveSession', ([], {'config': 'config'}), '(config=config)\n', (2426, 2441), False, 'from tensorflow.compat.v1 import InteractiveSession\n'), ((3178, 3216), 'cv2.VideoWriter_fourcc', 'cv2.VideoWriter_fourcc', (['*output_format'], {}), '(*output_format)\n', (3200, 3216), False, 'import cv2\n'), ((3231, 3295), 'cv2.VideoWriter', 'cv2.VideoWriter', (['output', 'codec', 'fps', '(image_width, image_height)'], {}), '(output, codec, fps, (image_width, image_height))\n', (3246, 3295), False, 'import cv2\n'), ((3314, 3383), 'cv2.VideoWriter', 'cv2.VideoWriter', (['demo_output', 'codec', 'fps', '(image_width, image_height)'], {}), '(demo_output, codec, fps, (image_width, image_height))\n', (3329, 3383), False, 'import cv2\n'), ((3654, 3692), 'cv2.cvtColor', 'cv2.cvtColor', (['frame', 'cv2.COLOR_BGR2RGB'], {}), '(frame, cv2.COLOR_BGR2RGB)\n', (3666, 3692), False, 'import cv2\n'), ((3709, 3755), 'cv2.resize', 'cv2.resize', (['frame', '(image_width, image_height)'], {}), '(frame, (image_width, image_height))\n', (3719, 3755), False, 'import cv2\n'), ((3770, 3820), 'numpy.zeros', 'np.zeros', (['(image_height, image_width, 3)', 'np.uint8'], {}), '((image_height, image_width, 3), np.uint8)\n', (3778, 3820), True, 'import numpy as np\n'), ((3841, 3852), 'time.time', 'time.time', ([], {}), '()\n', (3850, 3852), False, 'import time\n'), ((7257, 7287), 'cv2.moveWindow', 'cv2.moveWindow', (['"""output"""', '(0)', '(0)'], {}), "('output', 0, 0)\n", (7271, 7287), False, 'import cv2\n'), ((7438, 7449), 'time.time', 'time.time', ([], {}), '()\n', (7447, 7449), False, 'import time\n'), ((7767, 7780), 'absl.app.run', 'app.run', (['main'], {}), '(main)\n', (7774, 7780), False, 'from absl import app, flags, logging\n'), ((2244, 2311), 'tensorflow.config.experimental.set_memory_growth', 'tf.config.experimental.set_memory_growth', (['physical_devices[0]', '(True)'], {}), '(physical_devices[0], True)\n', (2284, 2311), True, 'import tensorflow as tf\n'), ((2917, 2945), 'cv2.VideoCapture', 'cv2.VideoCapture', (['video_path'], {}), '(video_path)\n', (2933, 2945), False, 'import cv2\n'), ((3625, 3636), 'os._exit', 'os._exit', (['(0)'], {}), '(0)\n', (3633, 3636), False, 'import os\n'), ((4214, 4257), 'cv2.resize', 'cv2.resize', (['frame', '(input_size, input_size)'], {}), '(frame, (input_size, input_size))\n', (4224, 4257), False, 'import cv2\n'), ((4439, 4462), 'tensorflow.constant', 'tf.constant', (['image_data'], {}), '(image_data)\n', (4450, 4462), True, 'import tensorflow as tf\n'), ((5862, 5885), 'core.analysis.create_dashboard', 'create_dashboard', (['frame'], {}), '(frame)\n', (5878, 5885), False, 'from core.analysis import create_dashboard\n'), ((5906, 5951), 'core.analysis.analysis', 'analysis', (['pair_ball', 'tracker.pair_ball', 'frame'], {}), '(pair_ball, tracker.pair_ball, frame)\n', (5914, 5951), False, 'from core.analysis import analysis\n'), ((6752, 6790), 'cv2.cvtColor', 'cv2.cvtColor', (['frame', 'cv2.COLOR_RGB2BGR'], {}), '(frame, cv2.COLOR_RGB2BGR)\n', (6764, 6790), False, 'import cv2\n'), ((6814, 6864), 'cv2.resize', 'cv2.resize', (['frame', '(rescale_width, rescale_height)'], {}), '(frame, (rescale_width, rescale_height))\n', (6824, 6864), False, 'import cv2\n'), ((6886, 6935), 'cv2.resize', 'cv2.resize', (['demo', '(rescale_width, rescale_height)'], {}), '(demo, (rescale_width, rescale_height))\n', (6896, 6935), False, 'import cv2\n'), ((7028, 7058), 'cv2.imshow', 'cv2.imshow', (['"""output"""', 're_frame'], {}), "('output', re_frame)\n", (7038, 7058), False, 'import cv2\n'), ((7071, 7098), 'cv2.imshow', 'cv2.imshow', (['"""demo"""', 're_demo'], {}), "('demo', re_demo)\n", (7081, 7098), False, 'import cv2\n'), ((7133, 7171), 'cv2.cvtColor', 'cv2.cvtColor', (['frame', 'cv2.COLOR_BGR2RGB'], {}), '(frame, cv2.COLOR_BGR2RGB)\n', (7145, 7171), False, 'import cv2\n'), ((7184, 7211), 'cv2.imshow', 'cv2.imshow', (['"""output"""', 'frame'], {}), "('output', frame)\n", (7194, 7211), False, 'import cv2\n'), ((7224, 7248), 'cv2.imshow', 'cv2.imshow', (['"""demo"""', 'demo'], {}), "('demo', demo)\n", (7234, 7248), False, 'import cv2\n'), ((7353, 7367), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (7364, 7367), False, 'import cv2\n'), ((4839, 4859), 'tensorflow.shape', 'tf.shape', (['boxes_ball'], {}), '(boxes_ball)\n', (4847, 4859), True, 'import tensorflow as tf\n'), ((4948, 4972), 'tensorflow.shape', 'tf.shape', (['pred_conf_ball'], {}), '(pred_conf_ball)\n', (4956, 4972), True, 'import tensorflow as tf\n'), ((4981, 5005), 'tensorflow.shape', 'tf.shape', (['pred_conf_ball'], {}), '(pred_conf_ball)\n', (4989, 5005), True, 'import tensorflow as tf\n')]
import serial import sys import time import numpy as np import struct import threading import matplotlib.pyplot as plt def readTSI(dev, bdrate, samplesNb, periodMs : int): ser = serial.Serial(dev, bdrate, timeout=10) command = "SSR" + str(periodMs).zfill(4) ser.write(command.encode()) ser.write(b'\r') line = str(ser.readline())[2:][:-5] if line != 'OK': print("ERROR : TSI DIDN'T ACK COMMAND SET PERIOD TO", periodMs) return command = "DCFxx" + str(samplesNb).zfill(4) ser.write(command.encode()) ser.write(b'\r') line = str(ser.readline())[2:][:-5] if line != 'OK': print("ERROR : TSI DIDN'T ACK COMMAND START MEASUREMENT") return counter = 0 samples = [] startTime = int(round(time.time() * 1000)) while True: line = str(ser.readline()) if len(line) > 0: Fslm_Tsi = float(line[2:][:-5]) counter += 1 millis = int(round(time.time() * 1000) - startTime) samples.append([millis, Fslm_Tsi]) if counter == samplesNb: stop_event.set() break np_samples = np.array(samples) np.savetxt('tsi.txt', np_samples) print("TSI finished", counter, "samples") def read_recovid(dev, bdrate): ser = serial.Serial(dev, bdrate, timeout=10) samples = [] count = 0 startTime = int(round(time.time() * 1000)) while True: if stop_event.isSet(): break c = ser.read() while c == b'>': if stop_event.isSet(): break millis = int(round(time.time() * 1000) - startTime) # t, = struct.unpack('H', ser.read(2)) dp, = struct.unpack('f', ser.read(4)) paw, = struct.unpack('f', ser.read(4)) vol, = struct.unpack('f', ser.read(4)) samples.append([millis, dp, paw]) count += 1 c = ser.read() np_samples = np.array(samples) np.savetxt('recovid.txt', np_samples) print("Recovid finished", count, "samples") samples_cnt = 1000 T = 10 stop_event = threading.Event() def main(argv): thread_tsi = threading.Thread(target=readTSI, args=('/dev/ttyUSB0', 38400, samples_cnt, T)) thread_covid = threading.Thread(target=read_recovid, args=('/dev/ttyUSB2', 115200)) thread_tsi.start() thread_covid.start() thread_tsi.join() thread_covid.join() tsi = np.loadtxt('tsi.txt') recovid = np.loadtxt('recovid.txt') fig, ax = plt.subplots(1, 1) ftsi = ax.plot(tsi[:,0], tsi[:,1]) #freco = ax.plot(recovid[:, 0], recovid[:, 1], 's' ) # pr afficher les points freco = ax.plot(recovid[:, 0], recovid[:, 1]) plt.legend(['F TSI', 'F Recovid']) ax.set(xlabel='time (ms)', ylabel='?', title='Sensors') ax.grid() plt.show() # print(tsi.shape, recovid.shape) print("main finished") if __name__ == "__main__": main(sys.argv)
[ "threading.Event", "numpy.array", "serial.Serial", "numpy.savetxt", "threading.Thread", "numpy.loadtxt", "time.time", "matplotlib.pyplot.subplots", "matplotlib.pyplot.legend", "matplotlib.pyplot.show" ]
[((2122, 2139), 'threading.Event', 'threading.Event', ([], {}), '()\n', (2137, 2139), False, 'import threading\n'), ((184, 222), 'serial.Serial', 'serial.Serial', (['dev', 'bdrate'], {'timeout': '(10)'}), '(dev, bdrate, timeout=10)\n', (197, 222), False, 'import serial\n'), ((1159, 1176), 'numpy.array', 'np.array', (['samples'], {}), '(samples)\n', (1167, 1176), True, 'import numpy as np\n'), ((1181, 1214), 'numpy.savetxt', 'np.savetxt', (['"""tsi.txt"""', 'np_samples'], {}), "('tsi.txt', np_samples)\n", (1191, 1214), True, 'import numpy as np\n'), ((1304, 1342), 'serial.Serial', 'serial.Serial', (['dev', 'bdrate'], {'timeout': '(10)'}), '(dev, bdrate, timeout=10)\n', (1317, 1342), False, 'import serial\n'), ((1972, 1989), 'numpy.array', 'np.array', (['samples'], {}), '(samples)\n', (1980, 1989), True, 'import numpy as np\n'), ((1994, 2031), 'numpy.savetxt', 'np.savetxt', (['"""recovid.txt"""', 'np_samples'], {}), "('recovid.txt', np_samples)\n", (2004, 2031), True, 'import numpy as np\n'), ((2174, 2252), 'threading.Thread', 'threading.Thread', ([], {'target': 'readTSI', 'args': "('/dev/ttyUSB0', 38400, samples_cnt, T)"}), "(target=readTSI, args=('/dev/ttyUSB0', 38400, samples_cnt, T))\n", (2190, 2252), False, 'import threading\n'), ((2272, 2340), 'threading.Thread', 'threading.Thread', ([], {'target': 'read_recovid', 'args': "('/dev/ttyUSB2', 115200)"}), "(target=read_recovid, args=('/dev/ttyUSB2', 115200))\n", (2288, 2340), False, 'import threading\n'), ((2446, 2467), 'numpy.loadtxt', 'np.loadtxt', (['"""tsi.txt"""'], {}), "('tsi.txt')\n", (2456, 2467), True, 'import numpy as np\n'), ((2482, 2507), 'numpy.loadtxt', 'np.loadtxt', (['"""recovid.txt"""'], {}), "('recovid.txt')\n", (2492, 2507), True, 'import numpy as np\n'), ((2523, 2541), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {}), '(1, 1)\n', (2535, 2541), True, 'import matplotlib.pyplot as plt\n'), ((2718, 2752), 'matplotlib.pyplot.legend', 'plt.legend', (["['F TSI', 'F Recovid']"], {}), "(['F TSI', 'F Recovid'])\n", (2728, 2752), True, 'import matplotlib.pyplot as plt\n'), ((2831, 2841), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2839, 2841), True, 'import matplotlib.pyplot as plt\n'), ((772, 783), 'time.time', 'time.time', ([], {}), '()\n', (781, 783), False, 'import time\n'), ((1400, 1411), 'time.time', 'time.time', ([], {}), '()\n', (1409, 1411), False, 'import time\n'), ((970, 981), 'time.time', 'time.time', ([], {}), '()\n', (979, 981), False, 'import time\n'), ((1622, 1633), 'time.time', 'time.time', ([], {}), '()\n', (1631, 1633), False, 'import time\n')]
from reliapy._messages import * from scipy.stats import norm import numpy as np from reliapy.math import spectral_decomposition, cholesky_decomposition class Random: """ ``Random`` simple random sampling. **Input:** * **distribution_obj** (`object`) Object of ``JointDistribution``. **Attributes:** * **distribution_obj** (`object`) Object of ``JointDistribution``. * **marginal** (`list`) A list of objects of marginal distribution. * **correlation** (`ndarray`) Correlation matrix. * **nrv** (`int`) Number of random variables. * **random_state** (`float`, `int`) Random seed. * **decomposition** (`str`) Decomposition of the correlation method: `spectral` or `cholesky`. * **mean** (`ndarray`) Array of means. * **std** (`ndarray`) Array of standard deviations. """ def __init__(self, distribution_obj=None): if not isinstance(distribution_obj.marginal, list): type_error('distributions', 'list') self.distribution_obj = distribution_obj self.marginal = distribution_obj.marginal self.Cz = distribution_obj.Cz self.nrv = len(distribution_obj.marginal) self.random_state = distribution_obj.random_state self.decomposition = distribution_obj.decomposition mean = [] std = [] for i in range(self.nrv): m = distribution_obj.marginal[i].stats[0] s = np.sqrt(distribution_obj.marginal[i].stats[1]) mean.append(m) std.append(s) self.mean = np.array(mean) self.std = np.array(std) def rvs(self, n_sim=1): """ Get random samples from the joint PDF using the simple sampling. **Input:** * **n_sim** (`float`) Number of samples. **Output:** * **x** (`ndarray`) Random samples. """ if self.decomposition == 'spectral': _, Jzy = spectral_decomposition(self.Cz) elif self.decomposition == 'cholesky': _, Jzy = cholesky_decomposition(self.Cz) else: not_implemented_error() y = norm.rvs(loc=0, scale=1, size=(self.nrv, n_sim), random_state=self.random_state) z = Jzy @ y x = [] for i in range(n_sim): u = norm.cdf(z[:, i], loc=0, scale=1) xj = [] for j in range(self.nrv): x_ = self.marginal[j].icdf(u[j]) xj.append(x_) x.append(xj) x = np.array(x) return x
[ "numpy.sqrt", "scipy.stats.norm.rvs", "numpy.array", "reliapy.math.cholesky_decomposition", "scipy.stats.norm.cdf", "reliapy.math.spectral_decomposition" ]
[((1634, 1648), 'numpy.array', 'np.array', (['mean'], {}), '(mean)\n', (1642, 1648), True, 'import numpy as np\n'), ((1668, 1681), 'numpy.array', 'np.array', (['std'], {}), '(std)\n', (1676, 1681), True, 'import numpy as np\n'), ((2229, 2314), 'scipy.stats.norm.rvs', 'norm.rvs', ([], {'loc': '(0)', 'scale': '(1)', 'size': '(self.nrv, n_sim)', 'random_state': 'self.random_state'}), '(loc=0, scale=1, size=(self.nrv, n_sim), random_state=self.random_state\n )\n', (2237, 2314), False, 'from scipy.stats import norm\n'), ((2604, 2615), 'numpy.array', 'np.array', (['x'], {}), '(x)\n', (2612, 2615), True, 'import numpy as np\n'), ((1513, 1559), 'numpy.sqrt', 'np.sqrt', (['distribution_obj.marginal[i].stats[1]'], {}), '(distribution_obj.marginal[i].stats[1])\n', (1520, 1559), True, 'import numpy as np\n'), ((2034, 2065), 'reliapy.math.spectral_decomposition', 'spectral_decomposition', (['self.Cz'], {}), '(self.Cz)\n', (2056, 2065), False, 'from reliapy.math import spectral_decomposition, cholesky_decomposition\n'), ((2393, 2426), 'scipy.stats.norm.cdf', 'norm.cdf', (['z[:, i]'], {'loc': '(0)', 'scale': '(1)'}), '(z[:, i], loc=0, scale=1)\n', (2401, 2426), False, 'from scipy.stats import norm\n'), ((2134, 2165), 'reliapy.math.cholesky_decomposition', 'cholesky_decomposition', (['self.Cz'], {}), '(self.Cz)\n', (2156, 2165), False, 'from reliapy.math import spectral_decomposition, cholesky_decomposition\n')]
import sys import numpy as np from scipy.stats import describe import os import time import matplotlib import pandas as pd from sklearn.base import ClassifierMixin, BaseEstimator import warnings import scipy import sklearn from sklearn.model_selection import train_test_split from sklearn.decomposition import PCA import itertools import multiprocessing as mp matplotlib.use('Agg') import matplotlib.pyplot as plt from numpy.linalg import svd from sklearn.neural_network import MLPClassifier from sklearn.neighbors import KNeighborsClassifier from sklearn.svm import SVC from sklearn.gaussian_process import GaussianProcessClassifier from sklearn.gaussian_process.kernels import RBF from sklearn.tree import DecisionTreeClassifier from sklearn.tree import plot_tree from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier from sklearn.naive_bayes import GaussianNB from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis from sklearn.model_selection import cross_val_score from sklearn.model_selection import RandomizedSearchCV from sklearn.linear_model import LassoLars h = .02 # step size in the mesh delimiter = ";" matplotlib.rcParams['pdf.fonttype'] = 42 matplotlib.rcParams['ps.fonttype'] = 42 # plt.interactive(True) # http://ksrowell.com/blog-visualizing-data/2012/02/02/ # optimal-colors-for-graphs/ MY_BLUE = (57, 106, 177) MY_ORANGE = (218, 124, 48) MY_GREEN = (62, 150, 81) MY_RED = (204, 37, 41) MY_BLACK = (83, 81, 84) MY_GOLD = (148, 139, 61) MY_VIOLET = (107, 76, 154) MY_BROWN = (146, 36, 40) MY_OWN = (25, 150, 10) def get_color(COLOR_TUPLE_255): return [x / 255 for x in COLOR_TUPLE_255] def plot(nr_samples, error_rates, title='error rate vs. # of train samples'): plt.plot(nr_samples, error_rates, color=get_color(MY_RED)) plt.title(title) plt.xlabel('# of train samples') plt.ylabel('Error rate') file_name = title.replace(': ', '_').replace(' ', '_') file_name = file_name.replace(', ', '_').replace('.', '-') # plt.savefig("./iris_" + file_name + "2.pdf") plt.savefig("./muscle.pdf") plt.clf() plt.close() class LeastSquareClassifier(BaseEstimator, ClassifierMixin): def add_ones_short(self, X): ones = np.ones(X.shape[0]) X = np.concatenate((ones[:, np.newaxis], X), axis=1) return X def fit(self, X, y=None): # make the classifier affine X = self.add_ones_short(X) self.w = find_w(X, y) def predict(self, X, y=None): X = self.add_ones_short(X) return [x for x in np.sign(np.matmul(X, self.w))] def score(self, X, y): X = self.add_ones_short(X) n, _ = X.shape y_hat = np.sign(np.matmul(X, self.w)) score = np.sum(y_hat == y) return score / n def predict_proba(self, X): X = self.add_ones_short(X) ys = np.matmul(X, self.w) probs = [] for y in ys: if y < 0: if y < -1: probs.append([1, 0.0]) else: y = 0.5 * np.abs(y) + 0.5 probs.append([y, 1 - y]) else: if y > 1: probs.append([0.0, 1]) else: y = 0.5 * np.abs(y) + 0.5 probs.append([1 - y, y]) probs = np.array(probs) return probs classifiers = { "Least Squares": LeastSquareClassifier(), "Nearest Neighbors": KNeighborsClassifier(3), "SVM": SVC(kernel="linear", C=0.025, probability=True), "RBF SVM": SVC(gamma=2, C=1, probability=True), "Gaussian Process": GaussianProcessClassifier(1.0 * RBF(1.0)), "Decision Tree": DecisionTreeClassifier(max_depth=None), "Random Forest": RandomForestClassifier(max_depth=5, n_estimators=10, max_features=1), "Neural Net": MLPClassifier(alpha=0.01, max_iter=1000), "AdaBoost": AdaBoostClassifier(), "Naive Bayes": GaussianNB(), "QDA": QuadraticDiscriminantAnalysis() } def find_w_X_more_rows_than_cols(X, y): H, W = X.shape assert H >= W X_t = X.transpose() X_t_X = np.matmul(X_t, X) X_t_X_inv = np.linalg.inv(X_t_X) X_t_X_inv_X_t = np.matmul(X_t_X_inv, X_t) w_hat = np.matmul(X_t_X_inv_X_t, y) return w_hat def find_w_X_more_cols_than_rows(X, y): H, W = X.shape assert H < W X_t = X.transpose() X_X_t = np.matmul(X, X_t) X_X_t_inv = np.linalg.inv(X_X_t) X_t_X_X_t_inv = np.matmul(X_t, X_X_t_inv) w_hat = np.matmul(X_t_X_X_t_inv, y) return w_hat def find_w_svd(X, y): H, W = X.shape assert W >= H u, s, vh = svd(a=X, full_matrices=False) s = 1 / s u_v = np.matmul(u * s[..., None, :], vh) w = np.matmul(u_v.T, y) return w def find_w(X, y): H, W = X.shape if H >= W: return find_w_X_more_rows_than_cols(X, y) else: # return find_w_X_more_cols_than_rows(X, y) return find_w_svd(X, y) def take_n_samples_each_clas(X, Y, nr_class, nr_samples_each_class): n, _ = X.shape n_class = n // nr_class x = [] y = [] start_index = 0 end_index = n_class # We need to extract samples for each class separately # ensure that there are the same number of samples for # each class in the train and the validation sets. for i in range(nr_class): x.append(X[start_index:end_index, ...]) y.append(Y[start_index:end_index]) start_index += n_class end_index += n_class # Randomize the samples within this class. # We could also do it after the extraction # of the validation set. randomized_indices = np.random.choice( n_class, nr_samples_each_class, replace=False) x[i] = x[i][randomized_indices] y[i] = y[i][randomized_indices] x = np.concatenate(x, axis=0) y = np.concatenate(y, axis=0) return x, y def cross_validate(X, Y, classifier, cv_count=6, nr_class=2, repeat=3, col_names=None, train_limit=None): """ Cross-validate the model. :param X: the input matrix of features We expect that the samples for each class are of the same number and arranged in the continuous way in the input dataset. :param Y: the input vector of correct predictions :param cv_count: cross validation count how many subsets of the data we want, where one of the subsets is the validation set and the remaining subsets create constitute the train set. We have cv_count iterations, where each of the cv_count subsets is validation set in one of the iterations. :param nr_class: number of classes in the dataset :param repeat: how many times to repeat the process :param is_affine: add the column with all 1's (ones) :return: the average accuracy across all repetitions and cross-validations within the repetitions. """ n, _ = X.shape n_class = n // nr_class # number of samples per class assert n_class % cv_count == 0 # length of the validated set from a single class cv_len = n_class // cv_count all_accuracies = [] all_aucs = [] for _ in range(repeat): x = [] y = [] start_index = 0 end_index = n_class # We need to extract samples for each class separately # ensure that there are the same number of samples for # each class in the train and the validation sets. for i in range(nr_class): x.append(X[start_index:end_index, ...]) y.append(Y[start_index:end_index]) start_index += n_class end_index += n_class # Randomize the samples within this class. # We could also do it after the extraction # of the validation set. randomized_indices = np.random.choice( n_class, n_class, replace=False) x[i] = x[i][randomized_indices, ...] y[i] = y[i][randomized_indices] # Cross-validate the model cv_count times. for i in range(cv_count): bottom_index = i * cv_len top_index = (i + 1) * cv_len bottom_x = [] top_x = [] bottom_y = [] top_y = [] for j in range(nr_class): bottom_x.append(x[j][:bottom_index, :]) top_x.append(x[j][top_index:, :]) bottom_y.append(y[j][:bottom_index]) top_y.append(y[j][top_index:]) bottom_x = np.concatenate(bottom_x, axis=0) top_x = np.concatenate(top_x, axis=0) bottom_y = np.concatenate(bottom_y, axis=0) top_y = np.concatenate(top_y, axis=0) if i == 0: x_train = top_x y_train = top_y elif i == cv_count - 1: x_train = bottom_x y_train = bottom_y else: x_train = np.concatenate((bottom_x, top_x), axis=0) y_train = np.concatenate((bottom_y, top_y), axis=0) if train_limit: x_train = x_train[:train_limit, :] y_train = y_train[:train_limit] x_train, means, stds = normalize_with_nans(x_train) x_test = [] y_test = [] for j in range(nr_class): x_test.append(x[j][bottom_index:top_index, :]) y_test.append(y[j][bottom_index:top_index]) x_test = np.concatenate(x_test, axis=0) y_test = np.concatenate(y_test, axis=0) x_test, _, _ = normalize_with_nans(x_test, means=means, stds=stds, col_names=col_names) clf = classifier clf.fit(x_train, y_train) score = clf.score(x_test, y_test) # y_score = clf.predict(x_test) y_probs = clf.predict_proba(x_test) auc = sklearn.metrics.roc_auc_score(y_true=y_test, y_score=y_probs[:, 1]) all_aucs.append(auc) all_accuracies.append(score) return np.average(all_accuracies), np.average(all_aucs) def err_percent(error_rate): return str(100 * error_rate) + " %" def accuracy_percent(accuracy): return str(100 * accuracy) + " %" def missing_values_col(data, nans, col_names, missing_rate=0.5): remove_cols = [] missing_values_col = [] for col_nr in range(data.shape[1]): col = data[:, col_nr].copy() col_clean = col[col != nans] nr_missing_values = len(col) - len(col_clean) col_name = col_names[col_nr] if nr_missing_values >= (missing_rate * len(col)): print(f'More than {missing_rate} of the patients have missing ' f'value for column number {col_nr} labeled {col_name}') remove_cols.append(col_nr) missing_values_col.append(nr_missing_values) avg_missing_values_per_column = np.average(missing_values_col) print('average number of missing values per column: ', avg_missing_values_per_column) return remove_cols def missing_values_row(data, nans, missing_rate=0.5): missing_values_row = [] remove_patients = [] for row_nr in range(data.shape[0]): row = data[row_nr, :].copy() row_clean = row[row != nans] nr_missing_values = len(row) - len(row_clean) missing_values_row.append(nr_missing_values) if nr_missing_values >= (missing_rate * len(row)): print( f'{nr_missing_values} (more than {missing_rate * 100}%) of the ' f'measurements are missing for patient number: {row_nr}') remove_patients.append(row_nr) avg_missing_values_per_row = np.average(missing_values_row) print('average number of missing values per row: ', avg_missing_values_per_row) return remove_patients def normalize_with_nans(data, nans=999, means=None, stds=None, col_names=None): """ Normalize the data after setting nans to mean values. :param data: the input data :param nans: values for non-applied data items :param means: the mean values for each feature column :param stds: the standard deviations for each feature column :return: normalized data """ if means is None and stds is not None: raise Exception('Provide also means.') if means is not None and stds is None: raise Exception('Provide also stds.') is_test = True if means is None and stds is None: is_test = False means = [] stds = [] for col_nr in range(data.shape[1]): col = data[:, col_nr].copy() col_clean = col[col != nans] if np.count_nonzero(col_clean) == 0: message = f'All data elements in column nr: {col_nr} are zero.' if col_names is not None: message += f' The column name is: {col_names[col_nr]}' # print('normalization message: ', message) # raise Exception(message) if is_test: mean = means[col_nr] std = stds[col_nr] else: mean = np.mean(col_clean) std = np.std(col_clean) means.append(mean) stds.append(std) # normalize the column col[col == nans] = mean col -= mean if std != 0: col /= std data[:, col_nr] = col return data, means, stds priority_classifiers = { "Least Squares": LeastSquareClassifier(), "Decision Tree": DecisionTreeClassifier(max_depth=5) } def column_priority(X, y, X_cv, y_cv, labels, classifiers=priority_classifiers): w = find_w_svd(X, y) w_abs = np.abs(w) index_w = [[i, w] for i, w in enumerate(w_abs)] # sort in descending order sort_index_w = sorted(index_w, key=lambda index_w: [-index_w[1]]) w_sorted_indexes = [index for (index, _) in sort_index_w] for index, w in sort_index_w: print(index, ';', labels[index], ';', w) # print('sort_index_w: ', sort_index_w) print('# of columns', end="") classifier_names = classifiers.keys() for classifier_name in classifier_names: print(delimiter, classifier_name, "accuracy train,", classifier_name, ",accuracy cross-validation", end="") print() for i in range(1, len(w_sorted_indexes) + 1): print(i, end="") # Extract most important columns from the dataset X. column_subset = w_sorted_indexes[:i] X_short = X[:, column_subset] X_cv_short = X_cv[:, column_subset] for clf in classifiers.values(): clf.fit(X_short, y) train_score = clf.score(X_short, y) print(delimiter, train_score, end="") try: cv_score = np.average( cross_val_score(clf, X_cv_short, y_cv, cv=6)) print(delimiter, cv_score, end="") except np.linalg.LinAlgError as err: print(delimiter, "N/A", end="") print() return w_sorted_indexes def show_decision_tree(estimator, col_names, means, stds): # source: https://scikit-learn.org/stable/auto_examples/tree/plot_unveil_tree_structure.html # The decision estimator has an attribute called tree_ which stores the entire # tree structure and allows access to low level attributes. The binary tree # tree_ is represented as a number of parallel arrays. The i-th element of each # array holds information about the node `i`. Node 0 is the tree's root. NOTE: # Some of the arrays only apply to either leaves or split nodes, resp. In this # case the values of nodes of the other type are arbitrary! # # Among those arrays, we have: # - left_child, id of the left child of the node # - right_child, id of the right child of the node # - feature, feature used for splitting the node # - threshold, threshold value at the node # # Using those arrays, we can parse the tree structure: n_nodes = estimator.tree_.node_count children_left = estimator.tree_.children_left children_right = estimator.tree_.children_right feature = estimator.tree_.feature threshold = estimator.tree_.threshold # The tree structure can be traversed to compute various properties such # as the depth of each node and whether or not it is a leaf. node_depth = np.zeros(shape=n_nodes, dtype=np.int64) is_leaves = np.zeros(shape=n_nodes, dtype=bool) stack = [(0, -1)] # seed is the root node id and its parent depth while len(stack) > 0: node_id, parent_depth = stack.pop() node_depth[node_id] = parent_depth + 1 # If we have a test node if (children_left[node_id] != children_right[node_id]): stack.append((children_left[node_id], parent_depth + 1)) stack.append((children_right[node_id], parent_depth + 1)) else: is_leaves[node_id] = True print("The binary tree structure has %s nodes and has " "the following tree structure:" % n_nodes) for i in range(n_nodes): if is_leaves[i]: print("%snode=%s leaf node." % (node_depth[i] * "\t", i)) else: feature_nr = feature[i] print( # "%snode=%s test node: go to node %s if X[:, %s] <= %s else to " # "node %s." "%snode=%s test node: go to node %s if '%s' <= %s else to " "node %s." % (node_depth[i] * "\t", i, children_left[i], # feature[i], col_names[feature_nr], # threshold[i], threshold[i] * stds[feature_nr] + means[feature_nr], children_right[i], )) # Utility function to report best scores: # source: https://scikit-learn.org/stable/auto_examples/model_selection/ # plot_randomized_search.html#sphx-glr-auto-examples-model-selection-plot # randomized-search-py def report(results, n_top=3): for i in range(1, n_top + 1): candidates = np.flatnonzero(results['rank_test_score'] == i) for candidate in candidates: print("Model with rank: {0}".format(i)) print("Mean validation score: {0:.3f} (std: {1:.3f})".format( results['mean_test_score'][candidate], results['std_test_score'][candidate])) print("Parameters: {0}".format(results['params'][candidate])) print("") def run_param_search(X, y, clf=SVC(probability=True)): # specify parameters and distributions to sample from param_dist = {'C': scipy.stats.expon(scale=100), 'gamma': scipy.stats.expon(scale=.1), 'kernel': ['rbf', 'linear'], 'class_weight': ['balanced', None]} # run randomized search n_iter_search = 20 random_search = RandomizedSearchCV(clf, param_distributions=param_dist, n_iter=n_iter_search, cv=5, iid=False) start = time.time() random_search.fit(X, y) print("RandomizedSearchCV took %.2f seconds for %d candidates" " parameter settings." % ((time.time() - start), n_iter_search)) report(random_search.cv_results_) def show_param_performance(X_cv, y_cv, nr_class, col_names): print( 'Accuracy on self-crafted cross-validation with normalization: ') for C in np.linspace(start=0.0001, stop=200, num=100): for name, clf in [('SVM', SVC(kernel="linear", C=C, probability=True))]: accuracy, auc = cross_validate(X_cv, y_cv, classifier=clf, nr_class=nr_class, col_names=col_names) print(name, "C=", C, delimiter, accuracy_percent(accuracy), auc) print() def svd_spectrum(X): u, s, vh = svd(a=X, full_matrices=False) print("Rank of X: ", len(s)) s = [x ** 2 for x in s] sum_s = np.sum(s) s = [x / sum_s for x in s] print("Importance of singular values: ", s) print("length of singular values: ", len(s)) ax1 = plt.subplot(111) ax1.plot( range(len(s)), s, label="$\frac{\sigma_i^2}{\sum_j^N \sigma_j^2}$", marker="o", linestyle="", color=get_color(MY_BLUE)) ax1.set_title("Spectrum of X") ax1.set_xlabel("index i of $\sigma_i$") # ax1.set_ylabel("$\sigma_i^2$/\n$\sum_j^N \sigma_j^2$", rotation=0) ax1.set_ylabel("$\sigma_i^2$", rotation=0) # ax1.legend(["true rating", "predicted rating"], loc="upper left") # ax1.axis([0, num_train, -15, 10]) # plt.show() dir_path = os.path.dirname(os.path.realpath(__file__)) output_path = os.path.join(dir_path, "svd_spectrum.png") plt.tight_layout() plt.savefig(output_path) plt.close() def pca(X, index): """ Compute PCA for X. :param X: the whole input data :param index: how many singular values retain (the dimension of the subspace) :return: the projected rows of X on a lower dimensional space """ XT = X.T # samples in columns u, s, vh = svd(a=XT, full_matrices=False) # We want to project the samples on a lower dimensional space. u = u[:, :index] # Columns of z are the new lower dimensional coordinates for the intial samples. z = np.matmul(X, u) return z def pca_scikit_whole_train(X, index): pca = PCA(n_components=index) # adjust yourself pca.fit(X) z = pca.transform(X) return z def pca_scikit_train_test(X, y, clf): print("PCA train test from scikit learn:") print("index, score") X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.4, random_state=0) for index in range(1, X_test.shape[0]): pca = PCA(n_components=index) # adjust yourself pca.fit(X_train) X_t_train = pca.transform(X_train) X_t_test = pca.transform(X_test) clf.fit(X_t_train, y_train) print(index, ',', clf.score(X_t_test, y_test)) def pca_scikit_train(X, y, clf): print("PCA train from scikit learn:") print("index, score") for index in range(1, X.shape[0]): pca = PCA(n_components=index) # adjust yourself pca.fit(X) xpca = pca.transform(X) clf.fit(xpca, y) print(index, ',', clf.score(xpca, y)) def accuracy_on_pca_data(X, y, classifiers, nr_class, col_names, pca_function=pca): H, W = X.shape print('PCA:') print('index' + delimiter + 'accuracy' + delimiter + 'auc') for index in range(1, H): xpca = pca_function(X, index=index) for name, clf in classifiers.items(): accuracy, auc = cross_validate( X=xpca, Y=y, classifier=clf, nr_class=nr_class, col_names=col_names) result = [index, accuracy, auc] str_result = delimiter.join([str(x) for x in result]) print(str_result) def findsubsets(s, max=None): if max is None: n = len(s) + 1 else: n = max + 1 subsets = [] for i in range(1, n): subset = list(itertools.combinations(s, i)) for x in subset: subsets.append(x) return subsets def col_scores_single_thread(X, y, clf, nr_class, col_names, max_col_nr): H, W = X.shape col_scores = {} for col in range(W): col_scores[col] = 0 subsets = findsubsets(np.arange(W), max_col_nr) print('subsets count: ', len(subsets)) for set in subsets: Xset = X[:, set] accuracy, auc = cross_validate(Xset, y, classifier=clf, nr_class=nr_class, col_names=col_names) for col in set: col_scores[col] += accuracy for w in sorted(col_scores, key=col_scores.get, reverse=True): result = [w, col_names[w], col_scores[w]] result_str = delimiter.join([str(x) for x in result]) print(result_str) return col_scores col_scores = {} def get_accuracy(X, set, y, clf, nr_class, col_names): Xset = X[:, set] accuracy, _ = cross_validate(Xset, y, classifier=clf, nr_class=nr_class, col_names=col_names) return set, accuracy def collect_accuracies(result): set, accuracy = result for col in set: col_scores[col] += accuracy def col_scores_parallel(X, y, clf, nr_class, col_names, max_col_nr): H, W = X.shape global col_scores for col in range(W): col_scores[col] = 0 subsets = findsubsets(np.arange(W), max_col_nr) print('subsets count: ', len(subsets)) # parallel python # source: # https://www.machinelearningplus.com/python/parallel-processing-python/ # Step 1: Init multiprocessing.Pool() pool = mp.Pool(mp.cpu_count()) # Step 2: pool.apply to a function for set in subsets: pool.apply_async( get_accuracy, args=(X, set, y, clf, nr_class, col_names), callback=collect_accuracies ) # Step 3: close the pool pool.close() # Step 4: postpones the execution of next line of code until all # processes in the queue are done. pool.join() for w in sorted(col_scores, key=col_scores.get, reverse=True): result = [w, col_names[w], col_scores[w]] result_str = delimiter.join([str(x) for x in result]) print(result_str) sys.stdout.flush() return col_scores_single_thread def accuracy_column_order(clf, X_cv, y_cv, nr_class, col_names, data_path): col_order = [] if 'garrett' in data_path: col_order = [126, 120, 130, 128, 111, 132, 116, 99, 100, 114, 129, 103, 125, 94, 117, 131, 127, 115, 104, 121, 98, 92, 97, 112, 113, 95, 119, 96, 118, 102, 101, 105, 122, 109, 184, 135, 134, 179, 123, 107, 89, 180, 124, 178, 185, 106, 150, 10, 155, 170, 55, 2, 176, 140, 160, 6, 52, 11, 74, 91, 56, 75, 93, 110, 90, 154, 51, 174, 32, 145, 5, 133, 19, 73, 183, 29, 27, 21, 78, 18, 14, 80, 144, 164, 69, 48, 151, 171, 149, 169, 72, 1, 163, 88, 68, 31, 86, 143, 46, 84, 23, 44, 85, 67, 79, 33, 24, 54, 63, 22, 82, 153, 173, 159, 139, 7, 83, 181, 61, 30, 66, 62, 49, 16, 71, 161, 141, 58, 166, 177, 42, 146, 45, 77, 142, 57, 162, 70, 65, 35, 20, 36, 41, 39, 40, 60, 168, 148, 0, 26, 76, 157, 34, 87, 158, 156, 4, 136, 138, 13, 147, 167, 137, 25, 172, 9, 43, 59, 152, 108, 50, 8, 28, 64, 182, 17, 38, 12, 37, 81, 53, 47, 3, 175, 165, 15] if 'remy' in data_path: col_order = [46, 89, 112, 62, 110, 90, 77, 31, 71, 76, 14, 63, 105, 70, 80, 66, 100, 67, 30, 95, 113, 11, 78, 45, 73, 75, 72, 47, 55, 35, 15, 41, 109, 10, 98, 108, 27, 79, 84, 65, 104, 51, 74, 39, 25, 24, 26, 99, 83, 21, 54, 111, 40, 33, 32, 64, 59, 28, 53, 87, 69, 61, 88, 106, 82, 20, 37, 29, 50, 44, 34, 94, 18, 22, 8, 101, 58, 7, 43, 38, 81, 13, 6, 36, 103, 60, 85, 49, 2, 56, 102, 16, 19, 3, 5, 1, 57, 12, 23, 42, 17, 48, 86, 93, 97, 96, 91, 52, 92, 107, 4, 0, 9, 68] print('SVM accuracy col order') print('nr of priority columns', delimiter, 'accuracy') for i in range(1, len(col_order) + 1): cols_order = col_order[:i] X_order = X_cv[:, cols_order] accuracy, auc = cross_validate( X_order, y_cv, classifier=clf, nr_class=nr_class, col_names=col_names) print(i, delimiter, accuracy) def f_importances(coef, names, topk=5): """ Source: https://stackoverflow.com/questions/41592661/determining-the-most-contributing-features-for-svm-classifier-in-sklearn :param coef: SVM coefficients :param names: the names of features :param topk: how many top features to show Save the graph. """ imp = coef.tolist()[0] imp, names = zip(*sorted(zip(imp, names))) imp = imp[:topk] + imp[-topk:] names = names[:topk] + names[-topk:] plt.barh(range(len(names)), imp, align='center') plt.yticks(range(len(names)), names) # plt.show() dir_path = os.path.dirname(os.path.realpath(__file__)) output_path = os.path.join(dir_path, "svm_importance_features.pdf") plt.tight_layout() plt.savefig(output_path) plt.close() def plot_coefficients(classifier, feature_names, top_features=20): """ Source: https://medium.com/@aneesha/visualising-top-features-in-linear-svm-with-scikit-learn-and-matplotlib-3454ab18a14d :param classifier: a linear SVM classifier :param feature_names: the names of features :param top_features: how many top features to show Save graph. """ coef = classifier.coef_.ravel() top_positive_coefficients = np.argsort(coef)[-top_features:] top_negative_coefficients = np.argsort(coef)[:top_features] top_coefficients = np.hstack( [top_negative_coefficients, top_positive_coefficients]) # create plot plt.figure(figsize=(15, 5)) colors = ['red' if c < 0 else 'blue' for c in coef[top_coefficients]] coefficients = coef[top_coefficients] plt.bar(np.arange(2 * top_features), coefficients, color=colors) feature_names = np.array(feature_names) feature_names = feature_names[top_coefficients] plt.xticks(np.arange(0, 1 + 2 * top_features), feature_names, rotation=60, ha='right') # plt.show() dir_path = os.path.dirname(os.path.realpath(__file__)) output_path = os.path.join(dir_path, "svm_importance_features2.pdf") plt.tight_layout() plt.savefig(output_path) plt.close() print('feature name, coefficient value') for name, coef in zip(feature_names, coefficients): print(name, ';', coef) def compute(): warnings.filterwarnings("ignore") dir_path = os.path.dirname(os.path.realpath(__file__)) # data_path = os.path.join(dir_path, "remy_data_all.csv") # data_path = os.path.join(dir_path, "remy_data_cleaned_with_header.csv") # data_path = os.path.join(dir_path, "remy_data_final.csv") # data_path = os.path.join(dir_path, "remy_data_final_sign_class.csv") # data_path = os.path.join(dir_path, "clean-2019-11-24-3.csv") # data_path = os.path.join(dir_path, "remy_2019_10_29.csv") # data_path = os.path.join(dir_path, "arnold_2019_12_07.csv") data_path = os.path.join(dir_path, "garrett_2019_11_24.csv") print('data_path: ', data_path) data_all = pd.read_csv(data_path, header=0) labels = np.asarray(data_all.iloc[:, 0], dtype=np.int) nr_class = len(np.unique(labels)) X = np.asarray(data_all.iloc[:, 1:], dtype=np.float) y = labels row_nr, col_nr = X.shape assert len(y) == row_nr col_names = np.array(list(data_all.columns.values)) col_names = col_names[1:] # skip the ASD column name assert len(col_names) == col_nr # print('X: ', X) # print('y: ', y) # print('size of X: ', X.shape) # print('size of y: ', y.shape) print('row number: ', row_nr) print('column number: ', col_nr) # remove the dependent columns # Q, R = qr(a=X, mode='reduced') # print('descriptive statistics for X: ', describe(X)) # print('X affine: ', X) # remove column with all zeros # print('columns with all zeros: ', np.where(~X_norm.any(axis=0))[0]) nans = 999 """ Special case: Column: “Asymmetry Total CSA > 12% at C3” – it has only zero values or ‘999’s only (it is the 3rd column from the end). """ # X = np.delete(X, -3, axis=1) # col_names = np.delete(col_names, -3) remove_cols = missing_values_col(data=X, nans=nans, col_names=col_names) remove_rows = missing_values_row(data=X, nans=nans) print('Delete columns: ', remove_cols) X = np.delete(X, remove_cols, axis=1) col_names = np.delete(col_names, remove_cols) print('Delete rows: ', remove_rows) X = np.delete(X, remove_rows, axis=0) y = np.delete(y, remove_rows) X_norm, means, stds = normalize_with_nans(data=X.copy(), nans=nans) # print('means: ', means) # print('stds: ', stds) # show the SVD spectrum. # svd_spectrum(X) w_hat = find_w(X_norm, y) y_hat = np.sign(np.matmul(X_norm, w_hat)) # print("check y_hat: ", y_hat) diff = np.sum(y_hat == y) accuracy = diff / len(y) print('On the whole data: ') print('Full Least Squares accuracy: ', accuracy_percent(accuracy)) # for cross validation we take the same number of samples for each class num_pos = np.count_nonzero(y == 1) num_neg = np.count_nonzero(y == -1) count = min(num_pos, num_neg) X_cv = np.concatenate((X[:count, :], X[-count:, :])) y_cv = np.concatenate((y[:count], y[-count:])) features_names = col_names.tolist() print('index;feature_name') for index, feature_name in enumerate(features_names): print(index, ';', feature_name) clf = DecisionTreeClassifier() clf = clf.fit(X, y) # plt.figure(figsize=(11,9)) plt.figure() plot_tree(clf, filled=True, feature_names=features_names, class_names=['neg', 'pos']) dir_path = os.path.dirname(os.path.realpath(__file__)) output_path = os.path.join(dir_path, "plot_tree13_full_data.pdf") # plt.tight_layout() plt.savefig(output_path, bbox_inches='tight') plt.close() for alpha in np.linspace(0, 0.1, 100): clf = LassoLars(alpha=alpha) clf = clf.fit(X, y) # Indices of active variables at the end of the path. active = clf.active_ active = sorted(active) feature_names = np.array(features_names) print('alpha regularization: ', alpha, ' number of variables: ', len(active)) print('variable names: ', feature_names[active]) print('variable coefficients (how important they are): ', clf.coef_[active]) # STOP exit(0) SVM = classifiers["SVM"] clf = SVM clf.fit(X_norm, y) print("clf.coef_: ", clf.coef_) score = clf.score(X_norm, y) print('SVM accuracy: ', accuracy_percent(score)) features_names = col_names.tolist() f_importances(clf.coef_, features_names) plot_coefficients(clf, feature_names=features_names, top_features=20) # accuracy_column_order(clf=SVM, nr_class=nr_class, col_names=col_names, # X_cv=X_cv, y_cv=y_cv, data_path=data_path) max_col_nr = 3 for name, clf in classifiers.items(): print('classifier name: ', clf) start = time.time() col_scores_parallel( X=X_cv, y=y_cv, col_names=col_names, clf=SVM, nr_class=nr_class, max_col_nr=max_col_nr) print('col scores parallel timing: ', time.time() - start) sys.stdout.flush() # start = time.time() # col_scores_single_thread( # X=X_cv, y=y_cv, col_names=col_names, clf=SVM, nr_class=nr_class, # max_col_nr=max_col_nr) # print('col scores single timing: ', time.time() - start) # pca_scikit_train_test(X=X_cv, y=y_cv, clf=SVM) pca_scikit_train(X=X_cv, y=y_cv, clf=SVM) # pca_function=pca pca_function = pca_scikit_whole_train accuracy_on_pca_data(X=X_cv, y=y_cv, classifiers={"SVM": SVM}, nr_class=nr_class, col_names=col_names, pca_function=pca_function) # run_param_search(X=X_cv, y=y_cv, clf=SVC(probability=True)) # show_param_performance(X_cv=X_cv, y_cv=y_cv, nr_class=nr_class, # col_names=col_names) print("Column priority: ") w_sorted_indexes = column_priority(X_norm, y, X_cv, y_cv, labels=col_names) print('labels len: ', len(col_names)) print('w_hat len: ', len(w_hat)) ones = np.ones(X_norm.shape[0]) X_ones = np.concatenate((ones[:, np.newaxis], X_norm), axis=1) w_hat = find_w_svd(X_ones, y) y_hat = np.sign(np.matmul(X_ones, w_hat)) # print("check y_hat: ", y_hat) diff = np.sum(y_hat == y) accuracy = diff / len(y) print('Least Squares accuracy: ', accuracy_percent(accuracy)) clf = LeastSquareClassifier() clf.fit(X_norm, y) score = clf.score(X_norm, y) print('Least Squares accuracy: ', accuracy_percent(score)) clf = classifiers['Neural Net'] clf.fit(X_norm, y) score = clf.score(X_norm, y) print('Neural net accuracy: ', accuracy_percent(score)) clf = classifiers['Decision Tree'] clf.fit(X_norm, y) score = clf.score(X_norm, y) print('Decision Tree accuracy: ', accuracy_percent(score)) show_decision_tree(estimator=clf, col_names=col_names, means=means, stds=stds) print('Accuracy on normalized X_norm: ') for name, clf in classifiers.items(): clf.fit(X_norm, y) score = clf.score(X_norm, y) print(name, accuracy_percent(score)) col_subset = 32 print( f'Accuracy and AUC on self-crafted cross-validation with normalization ' f'and subset of {col_subset} columns: ') X_subset = X_cv[:, w_sorted_indexes[:col_subset]] for name, clf in classifiers.items(): accuracy, auc = cross_validate(X_subset, y_cv, classifier=clf, nr_class=nr_class, col_names=col_names) print(name, delimiter, accuracy_percent(accuracy), delimiter, auc) print() print('Accuracy from cross-validation (non-normalized data): ') for name, clf in classifiers.items(): accuracy = np.average(cross_val_score(clf, X_cv, y_cv, cv=6)) print(name, delimiter, accuracy_percent(accuracy)) print() X_norm2 = np.concatenate((X_norm[:30, :], X_norm[31:61, :])) print('Accuracy from cross-validation (normalized the whole): ') for name, clf in classifiers.items(): accuracy = np.average(cross_val_score(clf, X_norm2, y_cv, cv=6)) print(name, delimiter, accuracy_percent(accuracy)) print() print( 'Accuracy and AUC on self-crafted cross-validation with normalization: ') print("model name, accuracy (%), AUC") for name, clf in classifiers.items(): accuracy, auc = cross_validate(X_cv, y_cv, classifier=clf, nr_class=nr_class, col_names=col_names) print(name, delimiter, accuracy_percent(accuracy), delimiter, auc) print() if __name__ == "__main__": compute()
[ "pandas.read_csv", "matplotlib.pyplot.ylabel", "numpy.hstack", "sklearn.ensemble.AdaBoostClassifier", "sklearn.neighbors.KNeighborsClassifier", "multiprocessing.cpu_count", "sklearn.metrics.roc_auc_score", "numpy.count_nonzero", "numpy.array", "numpy.argsort", "scipy.stats.expon", "numpy.arang...
[((361, 382), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (375, 382), False, 'import matplotlib\n'), ((1806, 1822), 'matplotlib.pyplot.title', 'plt.title', (['title'], {}), '(title)\n', (1815, 1822), True, 'import matplotlib.pyplot as plt\n'), ((1827, 1859), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""# of train samples"""'], {}), "('# of train samples')\n", (1837, 1859), True, 'import matplotlib.pyplot as plt\n'), ((1864, 1888), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Error rate"""'], {}), "('Error rate')\n", (1874, 1888), True, 'import matplotlib.pyplot as plt\n'), ((2066, 2093), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""./muscle.pdf"""'], {}), "('./muscle.pdf')\n", (2077, 2093), True, 'import matplotlib.pyplot as plt\n'), ((2098, 2107), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (2105, 2107), True, 'import matplotlib.pyplot as plt\n'), ((2112, 2123), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (2121, 2123), True, 'import matplotlib.pyplot as plt\n'), ((3476, 3499), 'sklearn.neighbors.KNeighborsClassifier', 'KNeighborsClassifier', (['(3)'], {}), '(3)\n', (3496, 3499), False, 'from sklearn.neighbors import KNeighborsClassifier\n'), ((3512, 3559), 'sklearn.svm.SVC', 'SVC', ([], {'kernel': '"""linear"""', 'C': '(0.025)', 'probability': '(True)'}), "(kernel='linear', C=0.025, probability=True)\n", (3515, 3559), False, 'from sklearn.svm import SVC\n'), ((3576, 3611), 'sklearn.svm.SVC', 'SVC', ([], {'gamma': '(2)', 'C': '(1)', 'probability': '(True)'}), '(gamma=2, C=1, probability=True)\n', (3579, 3611), False, 'from sklearn.svm import SVC\n'), ((3701, 3739), 'sklearn.tree.DecisionTreeClassifier', 'DecisionTreeClassifier', ([], {'max_depth': 'None'}), '(max_depth=None)\n', (3723, 3739), False, 'from sklearn.tree import DecisionTreeClassifier\n'), ((3762, 3830), 'sklearn.ensemble.RandomForestClassifier', 'RandomForestClassifier', ([], {'max_depth': '(5)', 'n_estimators': '(10)', 'max_features': '(1)'}), '(max_depth=5, n_estimators=10, max_features=1)\n', (3784, 3830), False, 'from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier\n'), ((3894, 3934), 'sklearn.neural_network.MLPClassifier', 'MLPClassifier', ([], {'alpha': '(0.01)', 'max_iter': '(1000)'}), '(alpha=0.01, max_iter=1000)\n', (3907, 3934), False, 'from sklearn.neural_network import MLPClassifier\n'), ((3952, 3972), 'sklearn.ensemble.AdaBoostClassifier', 'AdaBoostClassifier', ([], {}), '()\n', (3970, 3972), False, 'from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier\n'), ((3993, 4005), 'sklearn.naive_bayes.GaussianNB', 'GaussianNB', ([], {}), '()\n', (4003, 4005), False, 'from sklearn.naive_bayes import GaussianNB\n'), ((4018, 4049), 'sklearn.discriminant_analysis.QuadraticDiscriminantAnalysis', 'QuadraticDiscriminantAnalysis', ([], {}), '()\n', (4047, 4049), False, 'from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis\n'), ((4167, 4184), 'numpy.matmul', 'np.matmul', (['X_t', 'X'], {}), '(X_t, X)\n', (4176, 4184), True, 'import numpy as np\n'), ((4201, 4221), 'numpy.linalg.inv', 'np.linalg.inv', (['X_t_X'], {}), '(X_t_X)\n', (4214, 4221), True, 'import numpy as np\n'), ((4242, 4267), 'numpy.matmul', 'np.matmul', (['X_t_X_inv', 'X_t'], {}), '(X_t_X_inv, X_t)\n', (4251, 4267), True, 'import numpy as np\n'), ((4280, 4307), 'numpy.matmul', 'np.matmul', (['X_t_X_inv_X_t', 'y'], {}), '(X_t_X_inv_X_t, y)\n', (4289, 4307), True, 'import numpy as np\n'), ((4439, 4456), 'numpy.matmul', 'np.matmul', (['X', 'X_t'], {}), '(X, X_t)\n', (4448, 4456), True, 'import numpy as np\n'), ((4473, 4493), 'numpy.linalg.inv', 'np.linalg.inv', (['X_X_t'], {}), '(X_X_t)\n', (4486, 4493), True, 'import numpy as np\n'), ((4514, 4539), 'numpy.matmul', 'np.matmul', (['X_t', 'X_X_t_inv'], {}), '(X_t, X_X_t_inv)\n', (4523, 4539), True, 'import numpy as np\n'), ((4552, 4579), 'numpy.matmul', 'np.matmul', (['X_t_X_X_t_inv', 'y'], {}), '(X_t_X_X_t_inv, y)\n', (4561, 4579), True, 'import numpy as np\n'), ((4673, 4702), 'numpy.linalg.svd', 'svd', ([], {'a': 'X', 'full_matrices': '(False)'}), '(a=X, full_matrices=False)\n', (4676, 4702), False, 'from numpy.linalg import svd\n'), ((4727, 4761), 'numpy.matmul', 'np.matmul', (['(u * s[..., None, :])', 'vh'], {}), '(u * s[..., None, :], vh)\n', (4736, 4761), True, 'import numpy as np\n'), ((4770, 4789), 'numpy.matmul', 'np.matmul', (['u_v.T', 'y'], {}), '(u_v.T, y)\n', (4779, 4789), True, 'import numpy as np\n'), ((5869, 5894), 'numpy.concatenate', 'np.concatenate', (['x'], {'axis': '(0)'}), '(x, axis=0)\n', (5883, 5894), True, 'import numpy as np\n'), ((5903, 5928), 'numpy.concatenate', 'np.concatenate', (['y'], {'axis': '(0)'}), '(y, axis=0)\n', (5917, 5928), True, 'import numpy as np\n'), ((11028, 11058), 'numpy.average', 'np.average', (['missing_values_col'], {}), '(missing_values_col)\n', (11038, 11058), True, 'import numpy as np\n'), ((11821, 11851), 'numpy.average', 'np.average', (['missing_values_row'], {}), '(missing_values_row)\n', (11831, 11851), True, 'import numpy as np\n'), ((13643, 13678), 'sklearn.tree.DecisionTreeClassifier', 'DecisionTreeClassifier', ([], {'max_depth': '(5)'}), '(max_depth=5)\n', (13665, 13678), False, 'from sklearn.tree import DecisionTreeClassifier\n'), ((13801, 13810), 'numpy.abs', 'np.abs', (['w'], {}), '(w)\n', (13807, 13810), True, 'import numpy as np\n'), ((16510, 16549), 'numpy.zeros', 'np.zeros', ([], {'shape': 'n_nodes', 'dtype': 'np.int64'}), '(shape=n_nodes, dtype=np.int64)\n', (16518, 16549), True, 'import numpy as np\n'), ((16566, 16601), 'numpy.zeros', 'np.zeros', ([], {'shape': 'n_nodes', 'dtype': 'bool'}), '(shape=n_nodes, dtype=bool)\n', (16574, 16601), True, 'import numpy as np\n'), ((18701, 18722), 'sklearn.svm.SVC', 'SVC', ([], {'probability': '(True)'}), '(probability=True)\n', (18704, 18722), False, 'from sklearn.svm import SVC\n'), ((19065, 19164), 'sklearn.model_selection.RandomizedSearchCV', 'RandomizedSearchCV', (['clf'], {'param_distributions': 'param_dist', 'n_iter': 'n_iter_search', 'cv': '(5)', 'iid': '(False)'}), '(clf, param_distributions=param_dist, n_iter=\n n_iter_search, cv=5, iid=False)\n', (19083, 19164), False, 'from sklearn.model_selection import RandomizedSearchCV\n'), ((19212, 19223), 'time.time', 'time.time', ([], {}), '()\n', (19221, 19223), False, 'import time\n'), ((19593, 19637), 'numpy.linspace', 'np.linspace', ([], {'start': '(0.0001)', 'stop': '(200)', 'num': '(100)'}), '(start=0.0001, stop=200, num=100)\n', (19604, 19637), True, 'import numpy as np\n'), ((20044, 20073), 'numpy.linalg.svd', 'svd', ([], {'a': 'X', 'full_matrices': '(False)'}), '(a=X, full_matrices=False)\n', (20047, 20073), False, 'from numpy.linalg import svd\n'), ((20147, 20156), 'numpy.sum', 'np.sum', (['s'], {}), '(s)\n', (20153, 20156), True, 'import numpy as np\n'), ((20295, 20311), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(111)'], {}), '(111)\n', (20306, 20311), True, 'import matplotlib.pyplot as plt\n'), ((20867, 20909), 'os.path.join', 'os.path.join', (['dir_path', '"""svd_spectrum.png"""'], {}), "(dir_path, 'svd_spectrum.png')\n", (20879, 20909), False, 'import os\n'), ((20914, 20932), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (20930, 20932), True, 'import matplotlib.pyplot as plt\n'), ((20937, 20961), 'matplotlib.pyplot.savefig', 'plt.savefig', (['output_path'], {}), '(output_path)\n', (20948, 20961), True, 'import matplotlib.pyplot as plt\n'), ((20966, 20977), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (20975, 20977), True, 'import matplotlib.pyplot as plt\n'), ((21276, 21306), 'numpy.linalg.svd', 'svd', ([], {'a': 'XT', 'full_matrices': '(False)'}), '(a=XT, full_matrices=False)\n', (21279, 21306), False, 'from numpy.linalg import svd\n'), ((21488, 21503), 'numpy.matmul', 'np.matmul', (['X', 'u'], {}), '(X, u)\n', (21497, 21503), True, 'import numpy as np\n'), ((21567, 21590), 'sklearn.decomposition.PCA', 'PCA', ([], {'n_components': 'index'}), '(n_components=index)\n', (21570, 21590), False, 'from sklearn.decomposition import PCA\n'), ((21815, 21868), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X', 'y'], {'test_size': '(0.4)', 'random_state': '(0)'}), '(X, y, test_size=0.4, random_state=0)\n', (21831, 21868), False, 'from sklearn.model_selection import train_test_split\n'), ((25564, 25582), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (25580, 25582), False, 'import sys\n'), ((28592, 28645), 'os.path.join', 'os.path.join', (['dir_path', '"""svm_importance_features.pdf"""'], {}), "(dir_path, 'svm_importance_features.pdf')\n", (28604, 28645), False, 'import os\n'), ((28650, 28668), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (28666, 28668), True, 'import matplotlib.pyplot as plt\n'), ((28673, 28697), 'matplotlib.pyplot.savefig', 'plt.savefig', (['output_path'], {}), '(output_path)\n', (28684, 28697), True, 'import matplotlib.pyplot as plt\n'), ((28702, 28713), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (28711, 28713), True, 'import matplotlib.pyplot as plt\n'), ((29280, 29345), 'numpy.hstack', 'np.hstack', (['[top_negative_coefficients, top_positive_coefficients]'], {}), '([top_negative_coefficients, top_positive_coefficients])\n', (29289, 29345), True, 'import numpy as np\n'), ((29377, 29404), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(15, 5)'}), '(figsize=(15, 5))\n', (29387, 29404), True, 'import matplotlib.pyplot as plt\n'), ((29610, 29633), 'numpy.array', 'np.array', (['feature_names'], {}), '(feature_names)\n', (29618, 29633), True, 'import numpy as np\n'), ((29901, 29955), 'os.path.join', 'os.path.join', (['dir_path', '"""svm_importance_features2.pdf"""'], {}), "(dir_path, 'svm_importance_features2.pdf')\n", (29913, 29955), False, 'import os\n'), ((29960, 29978), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (29976, 29978), True, 'import matplotlib.pyplot as plt\n'), ((29983, 30007), 'matplotlib.pyplot.savefig', 'plt.savefig', (['output_path'], {}), '(output_path)\n', (29994, 30007), True, 'import matplotlib.pyplot as plt\n'), ((30012, 30023), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (30021, 30023), True, 'import matplotlib.pyplot as plt\n'), ((30177, 30210), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (30200, 30210), False, 'import warnings\n'), ((30763, 30811), 'os.path.join', 'os.path.join', (['dir_path', '"""garrett_2019_11_24.csv"""'], {}), "(dir_path, 'garrett_2019_11_24.csv')\n", (30775, 30811), False, 'import os\n'), ((30864, 30896), 'pandas.read_csv', 'pd.read_csv', (['data_path'], {'header': '(0)'}), '(data_path, header=0)\n', (30875, 30896), True, 'import pandas as pd\n'), ((30910, 30955), 'numpy.asarray', 'np.asarray', (['data_all.iloc[:, 0]'], {'dtype': 'np.int'}), '(data_all.iloc[:, 0], dtype=np.int)\n', (30920, 30955), True, 'import numpy as np\n'), ((31002, 31050), 'numpy.asarray', 'np.asarray', (['data_all.iloc[:, 1:]'], {'dtype': 'np.float'}), '(data_all.iloc[:, 1:], dtype=np.float)\n', (31012, 31050), True, 'import numpy as np\n'), ((32179, 32212), 'numpy.delete', 'np.delete', (['X', 'remove_cols'], {'axis': '(1)'}), '(X, remove_cols, axis=1)\n', (32188, 32212), True, 'import numpy as np\n'), ((32229, 32262), 'numpy.delete', 'np.delete', (['col_names', 'remove_cols'], {}), '(col_names, remove_cols)\n', (32238, 32262), True, 'import numpy as np\n'), ((32312, 32345), 'numpy.delete', 'np.delete', (['X', 'remove_rows'], {'axis': '(0)'}), '(X, remove_rows, axis=0)\n', (32321, 32345), True, 'import numpy as np\n'), ((32354, 32379), 'numpy.delete', 'np.delete', (['y', 'remove_rows'], {}), '(y, remove_rows)\n', (32363, 32379), True, 'import numpy as np\n'), ((32687, 32705), 'numpy.sum', 'np.sum', (['(y_hat == y)'], {}), '(y_hat == y)\n', (32693, 32705), True, 'import numpy as np\n'), ((32941, 32965), 'numpy.count_nonzero', 'np.count_nonzero', (['(y == 1)'], {}), '(y == 1)\n', (32957, 32965), True, 'import numpy as np\n'), ((32980, 33005), 'numpy.count_nonzero', 'np.count_nonzero', (['(y == -1)'], {}), '(y == -1)\n', (32996, 33005), True, 'import numpy as np\n'), ((33051, 33096), 'numpy.concatenate', 'np.concatenate', (['(X[:count, :], X[-count:, :])'], {}), '((X[:count, :], X[-count:, :]))\n', (33065, 33096), True, 'import numpy as np\n'), ((33108, 33147), 'numpy.concatenate', 'np.concatenate', (['(y[:count], y[-count:])'], {}), '((y[:count], y[-count:]))\n', (33122, 33147), True, 'import numpy as np\n'), ((33330, 33354), 'sklearn.tree.DecisionTreeClassifier', 'DecisionTreeClassifier', ([], {}), '()\n', (33352, 33354), False, 'from sklearn.tree import DecisionTreeClassifier\n'), ((33416, 33428), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (33426, 33428), True, 'import matplotlib.pyplot as plt\n'), ((33433, 33523), 'sklearn.tree.plot_tree', 'plot_tree', (['clf'], {'filled': '(True)', 'feature_names': 'features_names', 'class_names': "['neg', 'pos']"}), "(clf, filled=True, feature_names=features_names, class_names=[\n 'neg', 'pos'])\n", (33442, 33523), False, 'from sklearn.tree import plot_tree\n'), ((33610, 33661), 'os.path.join', 'os.path.join', (['dir_path', '"""plot_tree13_full_data.pdf"""'], {}), "(dir_path, 'plot_tree13_full_data.pdf')\n", (33622, 33661), False, 'import os\n'), ((33691, 33736), 'matplotlib.pyplot.savefig', 'plt.savefig', (['output_path'], {'bbox_inches': '"""tight"""'}), "(output_path, bbox_inches='tight')\n", (33702, 33736), True, 'import matplotlib.pyplot as plt\n'), ((33741, 33752), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (33750, 33752), True, 'import matplotlib.pyplot as plt\n'), ((33771, 33795), 'numpy.linspace', 'np.linspace', (['(0)', '(0.1)', '(100)'], {}), '(0, 0.1, 100)\n', (33782, 33795), True, 'import numpy as np\n'), ((36121, 36145), 'numpy.ones', 'np.ones', (['X_norm.shape[0]'], {}), '(X_norm.shape[0])\n', (36128, 36145), True, 'import numpy as np\n'), ((36159, 36212), 'numpy.concatenate', 'np.concatenate', (['(ones[:, np.newaxis], X_norm)'], {'axis': '(1)'}), '((ones[:, np.newaxis], X_norm), axis=1)\n', (36173, 36212), True, 'import numpy as np\n'), ((36340, 36358), 'numpy.sum', 'np.sum', (['(y_hat == y)'], {}), '(y_hat == y)\n', (36346, 36358), True, 'import numpy as np\n'), ((37985, 38035), 'numpy.concatenate', 'np.concatenate', (['(X_norm[:30, :], X_norm[31:61, :])'], {}), '((X_norm[:30, :], X_norm[31:61, :]))\n', (37999, 38035), True, 'import numpy as np\n'), ((2236, 2255), 'numpy.ones', 'np.ones', (['X.shape[0]'], {}), '(X.shape[0])\n', (2243, 2255), True, 'import numpy as np\n'), ((2268, 2316), 'numpy.concatenate', 'np.concatenate', (['(ones[:, np.newaxis], X)'], {'axis': '(1)'}), '((ones[:, np.newaxis], X), axis=1)\n', (2282, 2316), True, 'import numpy as np\n'), ((2743, 2761), 'numpy.sum', 'np.sum', (['(y_hat == y)'], {}), '(y_hat == y)\n', (2749, 2761), True, 'import numpy as np\n'), ((2868, 2888), 'numpy.matmul', 'np.matmul', (['X', 'self.w'], {}), '(X, self.w)\n', (2877, 2888), True, 'import numpy as np\n'), ((3350, 3365), 'numpy.array', 'np.array', (['probs'], {}), '(probs)\n', (3358, 3365), True, 'import numpy as np\n'), ((5703, 5766), 'numpy.random.choice', 'np.random.choice', (['n_class', 'nr_samples_each_class'], {'replace': '(False)'}), '(n_class, nr_samples_each_class, replace=False)\n', (5719, 5766), True, 'import numpy as np\n'), ((10178, 10204), 'numpy.average', 'np.average', (['all_accuracies'], {}), '(all_accuracies)\n', (10188, 10204), True, 'import numpy as np\n'), ((10206, 10226), 'numpy.average', 'np.average', (['all_aucs'], {}), '(all_aucs)\n', (10216, 10226), True, 'import numpy as np\n'), ((18251, 18298), 'numpy.flatnonzero', 'np.flatnonzero', (["(results['rank_test_score'] == i)"], {}), "(results['rank_test_score'] == i)\n", (18265, 18298), True, 'import numpy as np\n'), ((18806, 18834), 'scipy.stats.expon', 'scipy.stats.expon', ([], {'scale': '(100)'}), '(scale=100)\n', (18823, 18834), False, 'import scipy\n'), ((18863, 18891), 'scipy.stats.expon', 'scipy.stats.expon', ([], {'scale': '(0.1)'}), '(scale=0.1)\n', (18880, 18891), False, 'import scipy\n'), ((20821, 20847), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (20837, 20847), False, 'import os\n'), ((21936, 21959), 'sklearn.decomposition.PCA', 'PCA', ([], {'n_components': 'index'}), '(n_components=index)\n', (21939, 21959), False, 'from sklearn.decomposition import PCA\n'), ((22335, 22358), 'sklearn.decomposition.PCA', 'PCA', ([], {'n_components': 'index'}), '(n_components=index)\n', (22338, 22358), False, 'from sklearn.decomposition import PCA\n'), ((23586, 23598), 'numpy.arange', 'np.arange', (['W'], {}), '(W)\n', (23595, 23598), True, 'import numpy as np\n'), ((24700, 24712), 'numpy.arange', 'np.arange', (['W'], {}), '(W)\n', (24709, 24712), True, 'import numpy as np\n'), ((24944, 24958), 'multiprocessing.cpu_count', 'mp.cpu_count', ([], {}), '()\n', (24956, 24958), True, 'import multiprocessing as mp\n'), ((28546, 28572), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (28562, 28572), False, 'import os\n'), ((29160, 29176), 'numpy.argsort', 'np.argsort', (['coef'], {}), '(coef)\n', (29170, 29176), True, 'import numpy as np\n'), ((29225, 29241), 'numpy.argsort', 'np.argsort', (['coef'], {}), '(coef)\n', (29235, 29241), True, 'import numpy as np\n'), ((29533, 29560), 'numpy.arange', 'np.arange', (['(2 * top_features)'], {}), '(2 * top_features)\n', (29542, 29560), True, 'import numpy as np\n'), ((29701, 29735), 'numpy.arange', 'np.arange', (['(0)', '(1 + 2 * top_features)'], {}), '(0, 1 + 2 * top_features)\n', (29710, 29735), True, 'import numpy as np\n'), ((29855, 29881), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (29871, 29881), False, 'import os\n'), ((30242, 30268), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (30258, 30268), False, 'import os\n'), ((30975, 30992), 'numpy.unique', 'np.unique', (['labels'], {}), '(labels)\n', (30984, 30992), True, 'import numpy as np\n'), ((32614, 32638), 'numpy.matmul', 'np.matmul', (['X_norm', 'w_hat'], {}), '(X_norm, w_hat)\n', (32623, 32638), True, 'import numpy as np\n'), ((33564, 33590), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (33580, 33590), False, 'import os\n'), ((33811, 33833), 'sklearn.linear_model.LassoLars', 'LassoLars', ([], {'alpha': 'alpha'}), '(alpha=alpha)\n', (33820, 33833), False, 'from sklearn.linear_model import LassoLars\n'), ((34009, 34033), 'numpy.array', 'np.array', (['features_names'], {}), '(features_names)\n', (34017, 34033), True, 'import numpy as np\n'), ((34902, 34913), 'time.time', 'time.time', ([], {}), '()\n', (34911, 34913), False, 'import time\n'), ((35130, 35148), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (35146, 35148), False, 'import sys\n'), ((36267, 36291), 'numpy.matmul', 'np.matmul', (['X_ones', 'w_hat'], {}), '(X_ones, w_hat)\n', (36276, 36291), True, 'import numpy as np\n'), ((2705, 2725), 'numpy.matmul', 'np.matmul', (['X', 'self.w'], {}), '(X, self.w)\n', (2714, 2725), True, 'import numpy as np\n'), ((3669, 3677), 'sklearn.gaussian_process.kernels.RBF', 'RBF', (['(1.0)'], {}), '(1.0)\n', (3672, 3677), False, 'from sklearn.gaussian_process.kernels import RBF\n'), ((7867, 7916), 'numpy.random.choice', 'np.random.choice', (['n_class', 'n_class'], {'replace': '(False)'}), '(n_class, n_class, replace=False)\n', (7883, 7916), True, 'import numpy as np\n'), ((8559, 8591), 'numpy.concatenate', 'np.concatenate', (['bottom_x'], {'axis': '(0)'}), '(bottom_x, axis=0)\n', (8573, 8591), True, 'import numpy as np\n'), ((8612, 8641), 'numpy.concatenate', 'np.concatenate', (['top_x'], {'axis': '(0)'}), '(top_x, axis=0)\n', (8626, 8641), True, 'import numpy as np\n'), ((8665, 8697), 'numpy.concatenate', 'np.concatenate', (['bottom_y'], {'axis': '(0)'}), '(bottom_y, axis=0)\n', (8679, 8697), True, 'import numpy as np\n'), ((8718, 8747), 'numpy.concatenate', 'np.concatenate', (['top_y'], {'axis': '(0)'}), '(top_y, axis=0)\n', (8732, 8747), True, 'import numpy as np\n'), ((9521, 9551), 'numpy.concatenate', 'np.concatenate', (['x_test'], {'axis': '(0)'}), '(x_test, axis=0)\n', (9535, 9551), True, 'import numpy as np\n'), ((9573, 9603), 'numpy.concatenate', 'np.concatenate', (['y_test'], {'axis': '(0)'}), '(y_test, axis=0)\n', (9587, 9603), True, 'import numpy as np\n'), ((9976, 10043), 'sklearn.metrics.roc_auc_score', 'sklearn.metrics.roc_auc_score', ([], {'y_true': 'y_test', 'y_score': 'y_probs[:, 1]'}), '(y_true=y_test, y_score=y_probs[:, 1])\n', (10005, 10043), False, 'import sklearn\n'), ((12815, 12842), 'numpy.count_nonzero', 'np.count_nonzero', (['col_clean'], {}), '(col_clean)\n', (12831, 12842), True, 'import numpy as np\n'), ((13247, 13265), 'numpy.mean', 'np.mean', (['col_clean'], {}), '(col_clean)\n', (13254, 13265), True, 'import numpy as np\n'), ((13284, 13301), 'numpy.std', 'np.std', (['col_clean'], {}), '(col_clean)\n', (13290, 13301), True, 'import numpy as np\n'), ((23287, 23315), 'itertools.combinations', 'itertools.combinations', (['s', 'i'], {}), '(s, i)\n', (23309, 23315), False, 'import itertools\n'), ((37859, 37897), 'sklearn.model_selection.cross_val_score', 'cross_val_score', (['clf', 'X_cv', 'y_cv'], {'cv': '(6)'}), '(clf, X_cv, y_cv, cv=6)\n', (37874, 37897), False, 'from sklearn.model_selection import cross_val_score\n'), ((38177, 38218), 'sklearn.model_selection.cross_val_score', 'cross_val_score', (['clf', 'X_norm2', 'y_cv'], {'cv': '(6)'}), '(clf, X_norm2, y_cv, cv=6)\n', (38192, 38218), False, 'from sklearn.model_selection import cross_val_score\n'), ((19673, 19716), 'sklearn.svm.SVC', 'SVC', ([], {'kernel': '"""linear"""', 'C': 'C', 'probability': '(True)'}), "(kernel='linear', C=C, probability=True)\n", (19676, 19716), False, 'from sklearn.svm import SVC\n'), ((35101, 35112), 'time.time', 'time.time', ([], {}), '()\n', (35110, 35112), False, 'import time\n'), ((2572, 2592), 'numpy.matmul', 'np.matmul', (['X', 'self.w'], {}), '(X, self.w)\n', (2581, 2592), True, 'import numpy as np\n'), ((8986, 9027), 'numpy.concatenate', 'np.concatenate', (['(bottom_x, top_x)'], {'axis': '(0)'}), '((bottom_x, top_x), axis=0)\n', (9000, 9027), True, 'import numpy as np\n'), ((9054, 9095), 'numpy.concatenate', 'np.concatenate', (['(bottom_y, top_y)'], {'axis': '(0)'}), '((bottom_y, top_y), axis=0)\n', (9068, 9095), True, 'import numpy as np\n'), ((14928, 14972), 'sklearn.model_selection.cross_val_score', 'cross_val_score', (['clf', 'X_cv_short', 'y_cv'], {'cv': '(6)'}), '(clf, X_cv_short, y_cv, cv=6)\n', (14943, 14972), False, 'from sklearn.model_selection import cross_val_score\n'), ((19356, 19367), 'time.time', 'time.time', ([], {}), '()\n', (19365, 19367), False, 'import time\n'), ((3073, 3082), 'numpy.abs', 'np.abs', (['y'], {}), '(y)\n', (3079, 3082), True, 'import numpy as np\n'), ((3273, 3282), 'numpy.abs', 'np.abs', (['y'], {}), '(y)\n', (3279, 3282), True, 'import numpy as np\n')]