code stringlengths 31 1.05M | apis list | extract_api stringlengths 97 1.91M |
|---|---|---|
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, division
import operator
import numpy as np
from zarr.compat import integer_types, PY2, reduce
def normalize_shape(shape):
"""Convenience function to normalize the `shape` argument."""
if shape is None:
raise TypeError('shape is None')
# handle 1D convenience form
if isinstance(shape, integer_types):
shape = (int(shape),)
# normalize
shape = tuple(int(s) for s in shape)
return shape
# code to guess chunk shape, adapted from h5py
CHUNK_BASE = 64*1024 # Multiplier by which chunks are adjusted
CHUNK_MIN = 128*1024 # Soft lower limit (128k)
CHUNK_MAX = 16*1024*1024 # Hard upper limit (16M)
def guess_chunks(shape, typesize):
""" Guess an appropriate chunk layout for a dataset, given its shape and
the size of each element in bytes. Will allocate chunks only as large
as MAX_SIZE. Chunks are generally close to some power-of-2 fraction of
each axis, slightly favoring bigger values for the last index.
Undocumented and subject to change without warning.
"""
ndims = len(shape)
chunks = np.array(shape, dtype='=f8')
# Determine the optimal chunk size in bytes using a PyTables expression.
# This is kept as a float.
dset_size = np.product(chunks)*typesize
target_size = CHUNK_BASE * (2**np.log10(dset_size/(1024.*1024)))
if target_size > CHUNK_MAX:
target_size = CHUNK_MAX
elif target_size < CHUNK_MIN:
target_size = CHUNK_MIN
idx = 0
while True:
# Repeatedly loop over the axes, dividing them by 2. Stop when:
# 1a. We're smaller than the target chunk size, OR
# 1b. We're within 50% of the target chunk size, AND
# 2. The chunk is smaller than the maximum chunk size
chunk_bytes = np.product(chunks)*typesize
if (chunk_bytes < target_size or
abs(chunk_bytes-target_size)/target_size < 0.5) and \
chunk_bytes < CHUNK_MAX:
break
if np.product(chunks) == 1:
break # Element size larger than CHUNK_MAX
chunks[idx % ndims] = np.ceil(chunks[idx % ndims] / 2.0)
idx += 1
return tuple(int(x) for x in chunks)
def normalize_chunks(chunks, shape, typesize):
"""Convenience function to normalize the `chunks` argument for an array
with the given `shape`."""
# N.B., expect shape already normalized
# handle auto-chunking
if chunks is None or chunks is True:
return guess_chunks(shape, typesize)
# handle 1D convenience form
if isinstance(chunks, integer_types):
chunks = (int(chunks),)
# handle bad dimensionality
if len(chunks) > len(shape):
raise ValueError('too many dimensions in chunks')
# handle underspecified chunks
if len(chunks) < len(shape):
# assume chunks across remaining dimensions
chunks += shape[len(chunks):]
# handle None in chunks
chunks = tuple(s if c is None else int(c)
for s, c in zip(shape, chunks))
return chunks
# noinspection PyTypeChecker
def is_total_slice(item, shape):
"""Determine whether `item` specifies a complete slice of array with the
given `shape`. Used to optimize __setitem__ operations on the Chunk
class."""
# N.B., assume shape is normalized
if item == Ellipsis:
return True
if item == slice(None):
return True
if isinstance(item, slice):
item = item,
if isinstance(item, tuple):
return all(
(isinstance(s, slice) and
((s == slice(None)) or
((s.stop - s.start == l) and (s.step in [1, None]))))
for s, l in zip(item, shape)
)
else:
raise TypeError('expected slice or tuple of slices, found %r' % item)
def normalize_axis_selection(item, l):
"""Convenience function to normalize a selection within a single axis
of size `l`."""
if isinstance(item, int):
if item < 0:
# handle wraparound
item = l + item
if item > (l - 1) or item < 0:
raise IndexError('index out of bounds: %s' % item)
return item
elif isinstance(item, slice):
if item.step is not None and item.step != 1:
raise NotImplementedError('slice with step not supported')
start = 0 if item.start is None else item.start
stop = l if item.stop is None else item.stop
if start < 0:
start = l + start
if stop < 0:
stop = l + stop
if start < 0 or stop < 0:
raise IndexError('index out of bounds: %s, %s' % (start, stop))
if start >= l:
raise IndexError('index out of bounds: %s, %s' % (start, stop))
if stop > l:
stop = l
if stop < start:
raise IndexError('index out of bounds: %s, %s' % (start, stop))
return slice(start, stop)
else:
raise TypeError('expected integer or slice, found: %r' % item)
# noinspection PyTypeChecker
def normalize_array_selection(item, shape):
"""Convenience function to normalize a selection within an array with
the given `shape`."""
# normalize item
if isinstance(item, integer_types):
item = (int(item),)
elif isinstance(item, slice):
item = (item,)
elif item == Ellipsis:
item = (slice(None),)
# handle tuple of indices/slices
if isinstance(item, tuple):
# determine start and stop indices for all axes
selection = tuple(normalize_axis_selection(i, l)
for i, l in zip(item, shape))
# fill out selection if not completely specified
if len(selection) < len(shape):
selection += tuple(slice(0, l) for l in shape[len(selection):])
return selection
else:
raise TypeError('expected indices or slice, found: %r' % item)
def get_chunk_range(selection, chunks):
"""Convenience function to get a range over all chunk indices,
for iterating over chunks."""
chunk_range = [range(s.start//l, int(np.ceil(s.stop/l)))
if isinstance(s, slice)
else range(s//l, (s//l)+1)
for s, l in zip(selection, chunks)]
return chunk_range
def normalize_resize_args(old_shape, *args):
# normalize new shape argument
if len(args) == 1:
new_shape = args[0]
else:
new_shape = args
if isinstance(new_shape, int):
new_shape = (new_shape,)
else:
new_shape = tuple(new_shape)
if len(new_shape) != len(old_shape):
raise ValueError('new shape must have same number of dimensions')
# handle None in new_shape
new_shape = tuple(s if n is None else int(n)
for s, n in zip(old_shape, new_shape))
return new_shape
def human_readable_size(size):
if size < 2**10:
return '%s' % size
elif size < 2**20:
return '%.1fK' % (size / float(2**10))
elif size < 2**30:
return '%.1fM' % (size / float(2**20))
elif size < 2**40:
return '%.1fG' % (size / float(2**30))
elif size < 2**50:
return '%.1fT' % (size / float(2**40))
else:
return '%.1fP' % (size / float(2**50))
def normalize_order(order):
order = str(order).upper()
if order not in ['C', 'F']:
raise ValueError("order must be either 'C' or 'F', found: %r" % order)
return order
def normalize_storage_path(path):
if path:
# convert backslash to forward slash
path = path.replace('\\', '/')
# ensure no leading slash
while len(path) > 0 and path[0] == '/':
path = path[1:]
# ensure no trailing slash
while len(path) > 0 and path[-1] == '/':
path = path[:-1]
# collapse any repeated slashes
previous_char = None
collapsed = ''
for char in path:
if char == '/' and previous_char == '/':
pass
else:
collapsed += char
previous_char = char
path = collapsed
# don't allow path segments with just '.' or '..'
segments = path.split('/')
if any([s in {'.', '..'} for s in segments]):
raise ValueError("path containing '.' or '..' segment not allowed")
else:
path = ''
return path
def buffer_size(v):
from array import array as _stdlib_array
if PY2 and isinstance(v, _stdlib_array): # pragma: no cover
# special case array.array because does not support buffer
# interface in PY2
return v.buffer_info()[1] * v.itemsize
else:
v = memoryview(v)
return reduce(operator.mul, v.shape) * v.itemsize
| [
"numpy.product",
"numpy.ceil",
"numpy.log10",
"zarr.compat.reduce",
"numpy.array"
] | [((1165, 1193), 'numpy.array', 'np.array', (['shape'], {'dtype': '"""=f8"""'}), "(shape, dtype='=f8')\n", (1173, 1193), True, 'import numpy as np\n'), ((1319, 1337), 'numpy.product', 'np.product', (['chunks'], {}), '(chunks)\n', (1329, 1337), True, 'import numpy as np\n'), ((2178, 2212), 'numpy.ceil', 'np.ceil', (['(chunks[idx % ndims] / 2.0)'], {}), '(chunks[idx % ndims] / 2.0)\n', (2185, 2212), True, 'import numpy as np\n'), ((1382, 1419), 'numpy.log10', 'np.log10', (['(dset_size / (1024.0 * 1024))'], {}), '(dset_size / (1024.0 * 1024))\n', (1390, 1419), True, 'import numpy as np\n'), ((1855, 1873), 'numpy.product', 'np.product', (['chunks'], {}), '(chunks)\n', (1865, 1873), True, 'import numpy as np\n'), ((2066, 2084), 'numpy.product', 'np.product', (['chunks'], {}), '(chunks)\n', (2076, 2084), True, 'import numpy as np\n'), ((8784, 8813), 'zarr.compat.reduce', 'reduce', (['operator.mul', 'v.shape'], {}), '(operator.mul, v.shape)\n', (8790, 8813), False, 'from zarr.compat import integer_types, PY2, reduce\n'), ((6167, 6186), 'numpy.ceil', 'np.ceil', (['(s.stop / l)'], {}), '(s.stop / l)\n', (6174, 6186), True, 'import numpy as np\n')] |
# Copyright 2020 (c) Cognizant Digital Business, Evolutionary AI. All rights reserved. Issued under the Apache 2.0 License.
import numpy as np
np.show_config()
| [
"numpy.show_config"
] | [((144, 160), 'numpy.show_config', 'np.show_config', ([], {}), '()\n', (158, 160), True, 'import numpy as np\n')] |
from __future__ import unicode_literals
from __future__ import absolute_import
from __future__ import division
from time import time
import logging
from hcache import cached
from limix_math.linalg import sum2diag
from numpy import set_printoptions
from numpy import argmin
from numpy import zeros
from numpy import array
from .util import greek_letter
from .dists import Joint
from .base import EP
from ._minimize_scalar import find_minimum
# K = Q (v S + e I) Q.T
class OverdispersionEP(EP):
"""
.. math::
K = Q (v S + e I) Q.T
M = svd_U svd_S svd_V.T
\\tilde \\beta = svd_S^{1/2} svd_V.T \\beta
\\tilde M = svd_U svd_S^{1/2} \\tilde \\beta
m = M \\beta
m = \\tilde M \\tilde \\beta
"""
def __init__(self, M, Q0, Q1, S0, Q0S0Q0t=None):
super(OverdispersionEP, self).__init__(M, Q0, S0, Q0S0Q0t=Q0S0Q0t)
self._logger = logging.getLogger(__name__)
nsamples = M.shape[0]
self._joint = Joint(nsamples)
self._Q1 = Q1
self._e = None
def initialize_hyperparams(self):
raise NotImplementedError
# Getters and setters
@property
def noise_ratio(self):
e = self.environmental_variance
i = self.instrumental_variance
return e / (e + i)
@noise_ratio.setter
def noise_ratio(self, value):
gr = self.genetic_ratio
i = self.instrumental_variance
self.environmental_variance = i * value / (1 - value)
self.genetic_ratio = gr
@property
def environmental_variance(self):
if self._e is None:
self.initialize_hyperparams()
return self._e
@environmental_variance.setter
def environmental_variance(self, value):
self.clear_cache('_lml_components')
self.clear_cache('_L')
self.clear_cache('_update')
self.clear_cache('_A0')
self.clear_cache('diagK')
self.clear_cache('K')
self._e = value
@property
def instrumental_variance(self):
return 1.
@property
def real_variance(self):
return self.genetic_variance + self.environmental_variance
@real_variance.setter
def real_variance(self, value):
c = value / (self.genetic_variance + self.environmental_variance)
self.genetic_variance *= c
self.environmental_variance *= c
@property
def environmental_genetic_ratio(self):
e = self.environmental_variance
v = self.genetic_variance
return e / (e + v)
@environmental_genetic_ratio.setter
def environmental_genetic_ratio(self, value):
t = self.real_variance
self.genetic_variance = t * (1 - value)
self.environmental_variance = t * value
@property
def genetic_ratio(self):
e = self.environmental_variance
i = self.instrumental_variance
v = self.genetic_variance
return v / (e + i + v)
@genetic_ratio.setter
def genetic_ratio(self, value):
e = self.environmental_variance
i = self.instrumental_variance
c = e + i
self.genetic_variance = value * c / (1 - value)
# Optimization related methods
def _get_optimal_delta(self, real_variance):
rvs = array(self._real_variances)
i = argmin(abs(rvs - real_variance))
return self._environmental_genetic_ratios[i]
def _eg_delta_cost(self, delta):
self.environmental_genetic_ratio = delta
self._optimize_beta()
c = -self.lml()
self._logger.debug("_environmental_genetic_cost:cost: %.15f", c)
return c
def _environmental_genetic_delta_cost(self, delta):
self._logger.debug("_environmental_genetic_cost:delta: %.15f.", delta)
return self._eg_delta_cost(delta)
def _noise_ratio_cost(self, nr):
self.noise_ratio = nr
self._optimize_beta()
c = -self.lml()
self._logger.debug("_noise_ratio_cost:nr_cost: %.10f %.15f", nr, c)
return c
def _find_best_noise_ratio(self):
start = time()
a, b = 1e-3, 1 - 1e-3
nr = self.noise_ratio
nr, nfev = find_minimum(self._noise_ratio_cost, nr, a=a, b=b,
rtol=0, atol=1e-4)
self.noise_ratio = nr
self._logger.debug("End of noise_ratio optimization (%.3f seconds" +
", %d function calls).", time() - start, nfev)
def _genetic_ratio_cost(self, gr):
self._logger.debug("_genetic_ratio_cost:gr: %.10f", gr)
self.genetic_ratio = gr
self._find_best_noise_ratio()
return -self.lml()
def optimize(self, progress=None):
start = time()
self._logger.debug("Start of optimization.")
# self._logger.debug(self.__str__())
a, b = 1e-3, 1 - 1e-3
gr = self.genetic_ratio
def func(gr):
if progress:
progress.update(func.i)
func.i += 1
return self._genetic_ratio_cost(gr)
func.i = 0
gr, nfev = find_minimum(func, gr, a=a, b=b, rtol=0, atol=1e-4)
self.genetic_ratio = gr
self._find_best_noise_ratio()
self._optimize_beta()
# self._logger.debug(self.__str__())
self._logger.debug("End of optimization (%.3f seconds" +
", %d function calls).", time() - start, nfev)
# Key but Intermediary Matrix Definitions
@cached
def _A0(self):
""":math:`e \\mathrm I`"""
return self._e
@cached
def _A1(self):
""":math:`(e \\mathrm I + \\tilde{\\mathrm T}^{-1})^{-1}`"""
ttau = self._sites.tau
return ttau / (self.environmental_variance * ttau + 1)
@cached
def _A2(self):
""":math:`\\tilde{\\mathrm T}^{-1} \\mathrm A_1`"""
ttau = self._sites.tau
return 1 / (self.environmental_variance * ttau + 1)
@cached
def K(self):
""":math:`K = (v Q S Q.T + e I)`"""
return sum2diag(self.genetic_variance * self._Q0S0Q0t(),
self.environmental_variance)
@cached
def diagK(self):
return (self.genetic_variance * self._diagQ0S0Q0t() +
self.environmental_variance)
@cached
def _Q0B1Q0t(self):
if self.genetic_variance < 1e-6:
nsamples = self._Q0.shape[0]
return zeros((nsamples, nsamples))
return super(OverdispersionEP, self)._Q0B1Q0t()
def __repr__(self):
v = self.genetic_variance
e = self.environmental_variance
beta = self.beta
M = self.M
Q0 = self._Q0
Q1 = self._Q1
S0 = self._S0
tvar = self.total_variance
set_printoptions(precision=3, threshold=10)
def indent(s):
final = []
for si in s.split('\n'):
final.append(' ' + si)
return '\n'.join(final)
cvar = self.covariates_variance
ivar = self.instrumental_variance
h2 = self.heritability
gr = self.genetic_ratio
nr = self.noise_ratio
s = """
Prior:
Normal(M {b}.T, {v} * Kinship + {e} * I)
Definitions:
Kinship = Q0 S0 Q0.T
I = environment
M = covariates effect
Input data:
M:
{M}
Q0:
{Q0}
Q1:
{Q1}
S0: {S0}
Statistics (latent space):
Total variance: {tvar}
Instrumental variance: {ivar}
Covariates variance: {cvar}
Heritability: {h2}
Genetic ratio: {gr}
Noise ratio: {nr}
""".format(v="%.4f" % v, e="%.4f" % e, b=beta, Q0=indent(bytes(Q0)),
Q1=indent(bytes(Q1)), S0=bytes(S0), M=indent(bytes(M)),
tvar="%.4f" % tvar, cvar="%.4f" % cvar, h2="%.4f" % h2,
ivar="%.4f" % ivar, gr="%.4f" % gr, nr="%.4f" % nr)
set_printoptions(edgeitems=3, infstr='inf', linewidth=75, nanstr='nan',
precision=8, suppress=False, threshold=1000,
formatter=None)
return s
def __str__(self):
return self.__unicode__().encode('utf-8')
def __unicode__(self):
v = self.genetic_variance
e = self.environmental_variance
beta = self.beta
M = self.M
Q0 = self._Q0
Q1 = self._Q1
S0 = self._S0
tvar = self.total_variance
set_printoptions(precision=3, threshold=10)
def indent(s):
final = []
for si in s.split('\n'):
final.append(' ' + si)
return '\n'.join(final)
cvar = self.covariates_variance
ivar = self.instrumental_variance
h2 = self.heritability
gr = self.genetic_ratio
nr = self.noise_ratio
var_sym = unichr(0x3bd).encode('utf-8')
s = """
Latent phenotype:
f_i = o_i + u_i + e_i
Definitions:
o: fixed-effects signal
M {b}.T
u: background signal
Normal(0, {v} * Kinship)
e: environmental signal
Normal(0, {e} * I)
Log marginal likelihood: {lml}
Statistics (latent space):
Total variance: {tvar} {vs}_o + {vs}_u + {vs}_e + {vs}_{eps}
Instrumental variance: {ivar} {vs}_{eps}
Covariates variance: {cvar} {vs}_o
Heritability: {h2} {vs}_u / ({vs}_o + {vs}_u + {vs}_e)
Genetic ratio: {gr} {vs}_u / ({vs}_u + {vs}_e + {vs}_{eps})
Noise ratio: {nr} {vs}_e / ({vs}_e + {vs}_{eps})
""".format(v="%7.4f" % v, e="%7.4f" % e, b=beta, Q0=indent(bytes(Q0)),
Q1=indent(bytes(Q1)), S0=bytes(S0), M=indent(bytes(M)),
tvar="%7.4f" % tvar, cvar="%7.4f" % cvar, h2="%7.4f" % h2,
ivar="%7.4f" % ivar, gr="%7.4f" % gr, nr="%7.4f" % nr,
vs=var_sym, eps=greek_letter('epsilon'),
lml="%9.6f" % self.lml())
set_printoptions(edgeitems=3, infstr='inf', linewidth=75, nanstr='nan',
precision=8, suppress=False, threshold=1000,
formatter=None)
return s
| [
"logging.getLogger",
"numpy.array",
"numpy.zeros",
"time.time",
"numpy.set_printoptions"
] | [((908, 935), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (925, 935), False, 'import logging\n'), ((3253, 3280), 'numpy.array', 'array', (['self._real_variances'], {}), '(self._real_variances)\n', (3258, 3280), False, 'from numpy import array\n'), ((4058, 4064), 'time.time', 'time', ([], {}), '()\n', (4062, 4064), False, 'from time import time\n'), ((4688, 4694), 'time.time', 'time', ([], {}), '()\n', (4692, 4694), False, 'from time import time\n'), ((6716, 6759), 'numpy.set_printoptions', 'set_printoptions', ([], {'precision': '(3)', 'threshold': '(10)'}), '(precision=3, threshold=10)\n', (6732, 6759), False, 'from numpy import set_printoptions\n'), ((7807, 7943), 'numpy.set_printoptions', 'set_printoptions', ([], {'edgeitems': '(3)', 'infstr': '"""inf"""', 'linewidth': '(75)', 'nanstr': '"""nan"""', 'precision': '(8)', 'suppress': '(False)', 'threshold': '(1000)', 'formatter': 'None'}), "(edgeitems=3, infstr='inf', linewidth=75, nanstr='nan',\n precision=8, suppress=False, threshold=1000, formatter=None)\n", (7823, 7943), False, 'from numpy import set_printoptions\n'), ((8336, 8379), 'numpy.set_printoptions', 'set_printoptions', ([], {'precision': '(3)', 'threshold': '(10)'}), '(precision=3, threshold=10)\n', (8352, 8379), False, 'from numpy import set_printoptions\n'), ((9797, 9933), 'numpy.set_printoptions', 'set_printoptions', ([], {'edgeitems': '(3)', 'infstr': '"""inf"""', 'linewidth': '(75)', 'nanstr': '"""nan"""', 'precision': '(8)', 'suppress': '(False)', 'threshold': '(1000)', 'formatter': 'None'}), "(edgeitems=3, infstr='inf', linewidth=75, nanstr='nan',\n precision=8, suppress=False, threshold=1000, formatter=None)\n", (9813, 9933), False, 'from numpy import set_printoptions\n'), ((6380, 6407), 'numpy.zeros', 'zeros', (['(nsamples, nsamples)'], {}), '((nsamples, nsamples))\n', (6385, 6407), False, 'from numpy import zeros\n'), ((4409, 4415), 'time.time', 'time', ([], {}), '()\n', (4413, 4415), False, 'from time import time\n'), ((5373, 5379), 'time.time', 'time', ([], {}), '()\n', (5377, 5379), False, 'from time import time\n')] |
import numpy
from matplotlib import pyplot
def forward_difference(f, x0, h):
return (f(x0+h) - f(x0)) / h
def backward_difference(f, x0, h):
return (f(x0) - f(x0-h)) / h
def central_difference(f, x0, h):
return (f(x0+h) - f(x0-h)) / (2*h)
def euler(f, x_end, y0, N):
x, dx = numpy.linspace(0, x_end, N+1, retstep=True)
y = numpy.zeros((len(y0),N+1))
y[:,0] = y0
for n in range(N):
y[:,n+1] = y[:,n] + dx * f(x[n], y[:,n])
return x, dx, y
if __name__=="__main__":
h = 0.5
print("Forward difference, h=",h, "y'=",
forward_difference(numpy.exp, 0, h))
print("Backward difference, h=",h, "y'=",
backward_difference(numpy.exp, 0, h))
print("Central difference, h=",h, "y'=",
central_difference(numpy.exp, 0, h))
h = 0.05
print("Forward difference, h=",h, "y'=",
forward_difference(numpy.exp, 0, h))
print("Backward difference, h=",h, "y'=",
backward_difference(numpy.exp, 0, h))
print("Central difference, h=",h, "y'=",
central_difference(numpy.exp, 0, h))
h_all = 0.5/2**numpy.arange(1,10)
errors_forward = numpy.zeros_like(h_all)
errors_backward = numpy.zeros_like(h_all)
errors_central = numpy.zeros_like(h_all)
for i, h in enumerate(h_all):
errors_forward[i] = abs(1 - forward_difference(numpy.exp, 0, h))
errors_backward[i] = abs(1 - backward_difference(numpy.exp, 0, h))
errors_central[i] = abs(1 - central_difference(numpy.exp, 0, h))
pyplot.figure(figsize=(12,6))
pyplot.loglog(h_all, errors_forward, 'kx', label="Forward")
pyplot.loglog(h_all, errors_backward, 'bo', label="Backward")
pyplot.loglog(h_all, errors_central, 'r^', label="Central")
pyplot.loglog(h_all, h_all/h_all[0]*errors_forward[0], 'b-',
label=r"$\propto h$")
pyplot.loglog(h_all, (h_all/h_all[0])**2*errors_central[0], 'g-',
label=r"$\propto h^2$")
pyplot.xlabel(r"$h$")
pyplot.ylabel("Error")
pyplot.legend(loc="upper left")
pyplot.show()
def f_sin(x, y):
return -numpy.sin(x)
print("Euler's Method")
x, dx, y = euler(f_sin, 0.5, [1], 5)
print("dx=", dx, "y(0.5)=", y[0,-1])
x, dx, y = euler(f_sin, 0.5, [1], 50)
print("dx=", dx, "y(0.5)=", y[0,-1])
Npoints = 5*2**numpy.arange(1,10)
dx_all = 0.5/Npoints
errors = numpy.zeros_like(dx_all)
for i, N in enumerate(Npoints):
x, dx, y = euler(f_sin, 0.5, [1], N)
errors[i] = abs(y[0,-1] - numpy.cos(0.5))
dx_all[i] = dx
pyplot.figure(figsize=(12,6))
pyplot.loglog(dx_all, errors, 'kx')
pyplot.loglog(dx_all, errors[0]*(dx_all/dx_all[0])**1, 'b-',
label=r"$\propto \Delta x$")
pyplot.legend(loc='upper left')
pyplot.xlabel(r"$\Delta x$")
pyplot.ylabel("Error")
pyplot.show()
def f_circle(x, y):
dydx = numpy.zeros_like(y)
dydx[0] = -y[1]
dydx[1] = y[0]
return dydx
y0 = numpy.array([1, 0])
x, dx, y = euler(f_circle, 50, y0, 500)
pyplot.figure(figsize=(8,8))
pyplot.plot(y[0,:], y[1,:])
pyplot.show()
x, dx, y = euler(f_circle, 50, y0, 5000)
pyplot.figure(figsize=(8,8))
pyplot.plot(y[0,:], y[1,:])
pyplot.show() | [
"matplotlib.pyplot.loglog",
"matplotlib.pyplot.ylabel",
"numpy.arange",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"numpy.array",
"numpy.linspace",
"matplotlib.pyplot.figure",
"numpy.cos",
"numpy.sin",
"numpy.zeros_like",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.show"
] | [((293, 338), 'numpy.linspace', 'numpy.linspace', (['(0)', 'x_end', '(N + 1)'], {'retstep': '(True)'}), '(0, x_end, N + 1, retstep=True)\n', (307, 338), False, 'import numpy\n'), ((1152, 1175), 'numpy.zeros_like', 'numpy.zeros_like', (['h_all'], {}), '(h_all)\n', (1168, 1175), False, 'import numpy\n'), ((1198, 1221), 'numpy.zeros_like', 'numpy.zeros_like', (['h_all'], {}), '(h_all)\n', (1214, 1221), False, 'import numpy\n'), ((1243, 1266), 'numpy.zeros_like', 'numpy.zeros_like', (['h_all'], {}), '(h_all)\n', (1259, 1266), False, 'import numpy\n'), ((1526, 1556), 'matplotlib.pyplot.figure', 'pyplot.figure', ([], {'figsize': '(12, 6)'}), '(figsize=(12, 6))\n', (1539, 1556), False, 'from matplotlib import pyplot\n'), ((1560, 1619), 'matplotlib.pyplot.loglog', 'pyplot.loglog', (['h_all', 'errors_forward', '"""kx"""'], {'label': '"""Forward"""'}), "(h_all, errors_forward, 'kx', label='Forward')\n", (1573, 1619), False, 'from matplotlib import pyplot\n'), ((1624, 1685), 'matplotlib.pyplot.loglog', 'pyplot.loglog', (['h_all', 'errors_backward', '"""bo"""'], {'label': '"""Backward"""'}), "(h_all, errors_backward, 'bo', label='Backward')\n", (1637, 1685), False, 'from matplotlib import pyplot\n'), ((1690, 1749), 'matplotlib.pyplot.loglog', 'pyplot.loglog', (['h_all', 'errors_central', '"""r^"""'], {'label': '"""Central"""'}), "(h_all, errors_central, 'r^', label='Central')\n", (1703, 1749), False, 'from matplotlib import pyplot\n'), ((1754, 1845), 'matplotlib.pyplot.loglog', 'pyplot.loglog', (['h_all', '(h_all / h_all[0] * errors_forward[0])', '"""b-"""'], {'label': '"""$\\\\propto h$"""'}), "(h_all, h_all / h_all[0] * errors_forward[0], 'b-', label=\n '$\\\\propto h$')\n", (1767, 1845), False, 'from matplotlib import pyplot\n'), ((1859, 1958), 'matplotlib.pyplot.loglog', 'pyplot.loglog', (['h_all', '((h_all / h_all[0]) ** 2 * errors_central[0])', '"""g-"""'], {'label': '"""$\\\\propto h^2$"""'}), "(h_all, (h_all / h_all[0]) ** 2 * errors_central[0], 'g-',\n label='$\\\\propto h^2$')\n", (1872, 1958), False, 'from matplotlib import pyplot\n'), ((1971, 1991), 'matplotlib.pyplot.xlabel', 'pyplot.xlabel', (['"""$h$"""'], {}), "('$h$')\n", (1984, 1991), False, 'from matplotlib import pyplot\n'), ((1997, 2019), 'matplotlib.pyplot.ylabel', 'pyplot.ylabel', (['"""Error"""'], {}), "('Error')\n", (2010, 2019), False, 'from matplotlib import pyplot\n'), ((2024, 2055), 'matplotlib.pyplot.legend', 'pyplot.legend', ([], {'loc': '"""upper left"""'}), "(loc='upper left')\n", (2037, 2055), False, 'from matplotlib import pyplot\n'), ((2060, 2073), 'matplotlib.pyplot.show', 'pyplot.show', ([], {}), '()\n', (2071, 2073), False, 'from matplotlib import pyplot\n'), ((2399, 2423), 'numpy.zeros_like', 'numpy.zeros_like', (['dx_all'], {}), '(dx_all)\n', (2415, 2423), False, 'import numpy\n'), ((2582, 2612), 'matplotlib.pyplot.figure', 'pyplot.figure', ([], {'figsize': '(12, 6)'}), '(figsize=(12, 6))\n', (2595, 2612), False, 'from matplotlib import pyplot\n'), ((2616, 2651), 'matplotlib.pyplot.loglog', 'pyplot.loglog', (['dx_all', 'errors', '"""kx"""'], {}), "(dx_all, errors, 'kx')\n", (2629, 2651), False, 'from matplotlib import pyplot\n'), ((2656, 2757), 'matplotlib.pyplot.loglog', 'pyplot.loglog', (['dx_all', '(errors[0] * (dx_all / dx_all[0]) ** 1)', '"""b-"""'], {'label': '"""$\\\\propto \\\\Delta x$"""'}), "(dx_all, errors[0] * (dx_all / dx_all[0]) ** 1, 'b-', label=\n '$\\\\propto \\\\Delta x$')\n", (2669, 2757), False, 'from matplotlib import pyplot\n'), ((2768, 2799), 'matplotlib.pyplot.legend', 'pyplot.legend', ([], {'loc': '"""upper left"""'}), "(loc='upper left')\n", (2781, 2799), False, 'from matplotlib import pyplot\n'), ((2804, 2832), 'matplotlib.pyplot.xlabel', 'pyplot.xlabel', (['"""$\\\\Delta x$"""'], {}), "('$\\\\Delta x$')\n", (2817, 2832), False, 'from matplotlib import pyplot\n'), ((2837, 2859), 'matplotlib.pyplot.ylabel', 'pyplot.ylabel', (['"""Error"""'], {}), "('Error')\n", (2850, 2859), False, 'from matplotlib import pyplot\n'), ((2864, 2877), 'matplotlib.pyplot.show', 'pyplot.show', ([], {}), '()\n', (2875, 2877), False, 'from matplotlib import pyplot\n'), ((3018, 3037), 'numpy.array', 'numpy.array', (['[1, 0]'], {}), '([1, 0])\n', (3029, 3037), False, 'import numpy\n'), ((3086, 3115), 'matplotlib.pyplot.figure', 'pyplot.figure', ([], {'figsize': '(8, 8)'}), '(figsize=(8, 8))\n', (3099, 3115), False, 'from matplotlib import pyplot\n'), ((3119, 3148), 'matplotlib.pyplot.plot', 'pyplot.plot', (['y[0, :]', 'y[1, :]'], {}), '(y[0, :], y[1, :])\n', (3130, 3148), False, 'from matplotlib import pyplot\n'), ((3151, 3164), 'matplotlib.pyplot.show', 'pyplot.show', ([], {}), '()\n', (3162, 3164), False, 'from matplotlib import pyplot\n'), ((3214, 3243), 'matplotlib.pyplot.figure', 'pyplot.figure', ([], {'figsize': '(8, 8)'}), '(figsize=(8, 8))\n', (3227, 3243), False, 'from matplotlib import pyplot\n'), ((3247, 3276), 'matplotlib.pyplot.plot', 'pyplot.plot', (['y[0, :]', 'y[1, :]'], {}), '(y[0, :], y[1, :])\n', (3258, 3276), False, 'from matplotlib import pyplot\n'), ((3279, 3292), 'matplotlib.pyplot.show', 'pyplot.show', ([], {}), '()\n', (3290, 3292), False, 'from matplotlib import pyplot\n'), ((2922, 2941), 'numpy.zeros_like', 'numpy.zeros_like', (['y'], {}), '(y)\n', (2938, 2941), False, 'import numpy\n'), ((1112, 1131), 'numpy.arange', 'numpy.arange', (['(1)', '(10)'], {}), '(1, 10)\n', (1124, 1131), False, 'import numpy\n'), ((2117, 2129), 'numpy.sin', 'numpy.sin', (['x'], {}), '(x)\n', (2126, 2129), False, 'import numpy\n'), ((2342, 2361), 'numpy.arange', 'numpy.arange', (['(1)', '(10)'], {}), '(1, 10)\n', (2354, 2361), False, 'import numpy\n'), ((2539, 2553), 'numpy.cos', 'numpy.cos', (['(0.5)'], {}), '(0.5)\n', (2548, 2553), False, 'import numpy\n')] |
""" Pretty-print a table comparing DF vector threshold versus accuracy and cost """
import numpy as np
from pyscf import scf
from chemftr import df
from chemftr.molecule import rank_reduced_ccsd_t, cas_to_pyscf, pyscf_to_cas
def generate_costing_table(pyscf_mf,name='molecule',thresh_range=[0.0001],dE=0.001,chi=10,beta=20, use_kernel=True,no_triples=False):
""" Print a table to file for testing how various DF thresholds impact cost, accuracy, etc.
Args:
pyscf_mf - PySCF mean field object
name (str) - file will be saved to 'double_factorization_<name>.txt'
thresh_range (list of floats) - list of thresholds to try for DF algorithm
dE (float) - max allowable phase error (default: 0.001)
chi (int) - number of bits for representation of coefficients (default: 10)
beta (int) - not sure, but 20 was deemed sufficient for Li Hamiltonian (default: 20)
use_kernel (bool) - re-do SCF prior to estimating CCSD(T) error? Will use canonical orbitals
and full ERIs for the one-body contributions, using rank-reduced ERIs for two-body
no_triples (bool) - if True, skip the (T) correction, doing only rank-reduced CCSD
Returns:
None
"""
DE = dE # max allowable phase error
CHI = chi # number of bits for representation of coefficients
BETA = beta # not sure what we want here, but 20 was good enough for Li Hamiltonian
if isinstance(pyscf_mf, scf.rohf.ROHF):
num_alpha, num_beta = pyscf_mf.nelec
assert num_alpha + num_beta == pyscf_mf.mol.nelectron
else:
assert pyscf_mf.mol.nelectron % 2 == 0
num_alpha = pyscf_mf.mol.nelectron // 2
num_beta = num_alpha
num_orb = len(pyscf_mf.mo_coeff)
num_spinorb = num_orb * 2
cas_info = "CAS((%sa, %sb), %so)" % (num_alpha, num_beta, num_orb)
try:
assert num_orb ** 4 == len(pyscf_mf._eri.flatten())
except AssertionError:
# ERIs are not in correct form in pyscf_mf._eri, so this is a quick hack to prep system
pyscf_mol, pyscf_mf = cas_to_pyscf(*pyscf_to_cas(pyscf_mf))
# Reference calculation (eri_rr= None is full rank / exact ERIs)
escf, ecor, etot = rank_reduced_ccsd_t(pyscf_mf, eri_rr = None, use_kernel=use_kernel, no_triples=no_triples)
exact_ecor = ecor
exact_etot = etot
filename = 'double_factorization_'+name+'.txt'
with open(filename,'w') as f:
print("\n Double low rank factorization data for '"+name+"'.",file=f)
print(" [*] using "+cas_info,file=f)
print(" [+] E(SCF): %18.8f" % escf,file=f)
if no_triples:
print(" [+] Active space CCSD E(cor): %18.8f" % ecor,file=f)
print(" [+] Active space CCSD E(tot): %18.8f" % etot,file=f)
else:
print(" [+] Active space CCSD(T) E(cor): %18.8f" % ecor,file=f)
print(" [+] Active space CCSD(T) E(tot): %18.8f" % etot,file=f)
print("{}".format('='*139),file=f)
if no_triples:
print("{:^12} {:^18} {:^12} {:^12} {:^12} {:^24} {:^20} {:^20}".format('threshold','||ERI - DF||','L','eigenvectors','lambda','CCSD error (mEh)','logical qubits', 'Toffoli count'),file=f)
else:
print("{:^12} {:^18} {:^12} {:^12} {:^12} {:^24} {:^20} {:^20}".format('threshold','||ERI - DF||','L','eigenvectors','lambda','CCSD(T) error (mEh)','logical qubits', 'Toffoli count'),file=f)
print("{}".format('-'*139),file=f)
for thresh in thresh_range:
# First, up: lambda and CCSD(T)
eri_rr, LR, L, Lxi = df.rank_reduce(pyscf_mf._eri, thresh=thresh)
lam = df.compute_lambda(pyscf_mf, LR)
escf, ecor, etot = rank_reduced_ccsd_t(pyscf_mf, eri_rr, use_kernel=use_kernel, no_triples=no_triples)
error = (etot - exact_etot)*1E3 # to mEh
l2_norm_error_eri = np.linalg.norm(eri_rr - pyscf_mf._eri) # ERI reconstruction error
# now do costing
stps1 = df.compute_cost(num_spinorb, lam, DE, L=L, Lxi=Lxi, chi=CHI, beta=BETA, stps=20000)[0]
df_cost, df_total_cost, df_logical_qubits = df.compute_cost(num_spinorb, lam, DE, L=L, Lxi=Lxi, chi=CHI, beta=BETA, stps=stps1)
with open(filename,'a') as f:
print("{:^12.6f} {:^18.4e} {:^12} {:^12} {:^12.1f} {:^24.2f} {:^20} {:^20.1e}".format(thresh,l2_norm_error_eri,L,Lxi,lam,error, df_logical_qubits, df_total_cost),file=f)
with open(filename,'a') as f:
print("{}".format('='*139),file=f)
| [
"chemftr.df.rank_reduce",
"chemftr.molecule.rank_reduced_ccsd_t",
"chemftr.df.compute_cost",
"chemftr.molecule.pyscf_to_cas",
"chemftr.df.compute_lambda",
"numpy.linalg.norm"
] | [((2562, 2654), 'chemftr.molecule.rank_reduced_ccsd_t', 'rank_reduced_ccsd_t', (['pyscf_mf'], {'eri_rr': 'None', 'use_kernel': 'use_kernel', 'no_triples': 'no_triples'}), '(pyscf_mf, eri_rr=None, use_kernel=use_kernel,\n no_triples=no_triples)\n', (2581, 2654), False, 'from chemftr.molecule import rank_reduced_ccsd_t, cas_to_pyscf, pyscf_to_cas\n'), ((4310, 4354), 'chemftr.df.rank_reduce', 'df.rank_reduce', (['pyscf_mf._eri'], {'thresh': 'thresh'}), '(pyscf_mf._eri, thresh=thresh)\n', (4324, 4354), False, 'from chemftr import df\n'), ((4370, 4401), 'chemftr.df.compute_lambda', 'df.compute_lambda', (['pyscf_mf', 'LR'], {}), '(pyscf_mf, LR)\n', (4387, 4401), False, 'from chemftr import df\n'), ((4429, 4517), 'chemftr.molecule.rank_reduced_ccsd_t', 'rank_reduced_ccsd_t', (['pyscf_mf', 'eri_rr'], {'use_kernel': 'use_kernel', 'no_triples': 'no_triples'}), '(pyscf_mf, eri_rr, use_kernel=use_kernel, no_triples=\n no_triples)\n', (4448, 4517), False, 'from chemftr.molecule import rank_reduced_ccsd_t, cas_to_pyscf, pyscf_to_cas\n'), ((4591, 4629), 'numpy.linalg.norm', 'np.linalg.norm', (['(eri_rr - pyscf_mf._eri)'], {}), '(eri_rr - pyscf_mf._eri)\n', (4605, 4629), True, 'import numpy as np\n'), ((4845, 4932), 'chemftr.df.compute_cost', 'df.compute_cost', (['num_spinorb', 'lam', 'DE'], {'L': 'L', 'Lxi': 'Lxi', 'chi': 'CHI', 'beta': 'BETA', 'stps': 'stps1'}), '(num_spinorb, lam, DE, L=L, Lxi=Lxi, chi=CHI, beta=BETA,\n stps=stps1)\n', (4860, 4932), False, 'from chemftr import df\n'), ((4706, 4793), 'chemftr.df.compute_cost', 'df.compute_cost', (['num_spinorb', 'lam', 'DE'], {'L': 'L', 'Lxi': 'Lxi', 'chi': 'CHI', 'beta': 'BETA', 'stps': '(20000)'}), '(num_spinorb, lam, DE, L=L, Lxi=Lxi, chi=CHI, beta=BETA,\n stps=20000)\n', (4721, 4793), False, 'from chemftr import df\n'), ((2305, 2327), 'chemftr.molecule.pyscf_to_cas', 'pyscf_to_cas', (['pyscf_mf'], {}), '(pyscf_mf)\n', (2317, 2327), False, 'from chemftr.molecule import rank_reduced_ccsd_t, cas_to_pyscf, pyscf_to_cas\n')] |
import unittest
import numpy as np
from fit1d.common.model import ModelMock
from fit1d.common.fit1d import FitData
class TestFitData(unittest.TestCase):
def setUp(self):
self.x = np.array([1,2, 3, 4])
self.y = np.array([10,20, 30, 40])
self.model = ModelMock({"param1": 5.5})
def test_fit_data_empty_init(self):
fit_ref = FitData()
self.assertTrue(isinstance(fit_ref, FitData))
def test_fit_data_partial_init(self):
fit_ref = FitData(model=self.model, x=self.x)
self.assertTrue(isinstance(fit_ref, FitData))
def test_fit_data_full_init(self):
fit_ref = FitData(model=self.model, x=self.x, y=self.y,
y_fit=self.y, error_vector=self.x, rms=0.5)
self.assertTrue(isinstance(fit_ref, FitData))
def test_fit_results_equal(self):
fit_res1 = FitData(model=self.model, x=self.x, y=self.y,
y_fit=self.y, error_vector=self.x, rms=0.5)
fit_res2 = FitData(model=self.model, x=self.x, y=self.y,
y_fit=self.y, error_vector=self.x, rms=0.5)
self.assertTrue(fit_res1 == fit_res2)
def test_fit_results_non_equal(self):
fit_res1 = FitData(model=self.model, x=self.x, y=self.y,
y_fit=self.y, error_vector=self.x-1, rms=0.5)
fit_res2 = FitData(model=self.model, x=self.x, y=self.y,
y_fit=self.y, error_vector=self.x, rms=0.5)
self.assertFalse(fit_res1 == fit_res2)
| [
"numpy.array",
"fit1d.common.fit1d.FitData",
"fit1d.common.model.ModelMock"
] | [((193, 215), 'numpy.array', 'np.array', (['[1, 2, 3, 4]'], {}), '([1, 2, 3, 4])\n', (201, 215), True, 'import numpy as np\n'), ((232, 258), 'numpy.array', 'np.array', (['[10, 20, 30, 40]'], {}), '([10, 20, 30, 40])\n', (240, 258), True, 'import numpy as np\n'), ((279, 305), 'fit1d.common.model.ModelMock', 'ModelMock', (["{'param1': 5.5}"], {}), "({'param1': 5.5})\n", (288, 305), False, 'from fit1d.common.model import ModelMock\n'), ((365, 374), 'fit1d.common.fit1d.FitData', 'FitData', ([], {}), '()\n', (372, 374), False, 'from fit1d.common.fit1d import FitData\n'), ((490, 525), 'fit1d.common.fit1d.FitData', 'FitData', ([], {'model': 'self.model', 'x': 'self.x'}), '(model=self.model, x=self.x)\n', (497, 525), False, 'from fit1d.common.fit1d import FitData\n'), ((638, 732), 'fit1d.common.fit1d.FitData', 'FitData', ([], {'model': 'self.model', 'x': 'self.x', 'y': 'self.y', 'y_fit': 'self.y', 'error_vector': 'self.x', 'rms': '(0.5)'}), '(model=self.model, x=self.x, y=self.y, y_fit=self.y, error_vector=\n self.x, rms=0.5)\n', (645, 732), False, 'from fit1d.common.fit1d import FitData\n'), ((866, 960), 'fit1d.common.fit1d.FitData', 'FitData', ([], {'model': 'self.model', 'x': 'self.x', 'y': 'self.y', 'y_fit': 'self.y', 'error_vector': 'self.x', 'rms': '(0.5)'}), '(model=self.model, x=self.x, y=self.y, y_fit=self.y, error_vector=\n self.x, rms=0.5)\n', (873, 960), False, 'from fit1d.common.fit1d import FitData\n'), ((1002, 1096), 'fit1d.common.fit1d.FitData', 'FitData', ([], {'model': 'self.model', 'x': 'self.x', 'y': 'self.y', 'y_fit': 'self.y', 'error_vector': 'self.x', 'rms': '(0.5)'}), '(model=self.model, x=self.x, y=self.y, y_fit=self.y, error_vector=\n self.x, rms=0.5)\n', (1009, 1096), False, 'from fit1d.common.fit1d import FitData\n'), ((1227, 1325), 'fit1d.common.fit1d.FitData', 'FitData', ([], {'model': 'self.model', 'x': 'self.x', 'y': 'self.y', 'y_fit': 'self.y', 'error_vector': '(self.x - 1)', 'rms': '(0.5)'}), '(model=self.model, x=self.x, y=self.y, y_fit=self.y, error_vector=\n self.x - 1, rms=0.5)\n', (1234, 1325), False, 'from fit1d.common.fit1d import FitData\n'), ((1365, 1459), 'fit1d.common.fit1d.FitData', 'FitData', ([], {'model': 'self.model', 'x': 'self.x', 'y': 'self.y', 'y_fit': 'self.y', 'error_vector': 'self.x', 'rms': '(0.5)'}), '(model=self.model, x=self.x, y=self.y, y_fit=self.y, error_vector=\n self.x, rms=0.5)\n', (1372, 1459), False, 'from fit1d.common.fit1d import FitData\n')] |
import numpy as np
from quantities import Hz
from neo import AnalogSignal as AnalogSignal
n = np.array([[0.1, 0.1, 0.1, 0.1],
[-2.0, -2.0, -2.0, -4.0],
[0.1, 0.1, 0.1, 0.1],
[-0.1, -0.1, -0.1, -0.1],
[-0.1, -0.1, -0.1, -0.1],
[-3.0, -3.0, -3.0, -3.0],
[0.1, 0.1, 0.1, 0.1],
[0.1, 0.1, 0.1, 0.1]])
a = AnalogSignal(n, sampling_rate=1000*Hz, units='V')
print(n)
print(n[1, 3])
print(n.shape)
print(n[:, 0])
print(a)
print(a[1, 3])
print(a.magnitude.shape)
print(a.magnitude[:, 0])
| [
"numpy.array",
"neo.AnalogSignal"
] | [((95, 307), 'numpy.array', 'np.array', (['[[0.1, 0.1, 0.1, 0.1], [-2.0, -2.0, -2.0, -4.0], [0.1, 0.1, 0.1, 0.1], [-\n 0.1, -0.1, -0.1, -0.1], [-0.1, -0.1, -0.1, -0.1], [-3.0, -3.0, -3.0, -\n 3.0], [0.1, 0.1, 0.1, 0.1], [0.1, 0.1, 0.1, 0.1]]'], {}), '([[0.1, 0.1, 0.1, 0.1], [-2.0, -2.0, -2.0, -4.0], [0.1, 0.1, 0.1, \n 0.1], [-0.1, -0.1, -0.1, -0.1], [-0.1, -0.1, -0.1, -0.1], [-3.0, -3.0, \n -3.0, -3.0], [0.1, 0.1, 0.1, 0.1], [0.1, 0.1, 0.1, 0.1]])\n', (103, 307), True, 'import numpy as np\n'), ((401, 452), 'neo.AnalogSignal', 'AnalogSignal', (['n'], {'sampling_rate': '(1000 * Hz)', 'units': '"""V"""'}), "(n, sampling_rate=1000 * Hz, units='V')\n", (413, 452), True, 'from neo import AnalogSignal as AnalogSignal\n')] |
import tensorflow as tf
import numpy as np
import os
import pickle
import gzip
import urllib.request
import keras
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Conv2D, MaxPooling2D, Dropout
from keras.layers.normalization import BatchNormalization
from keras.regularizers import l2
from keras.utils import np_utils
from keras.models import load_model
model = Sequential()
nb_filters = 64
num_labels = 10
layers = [Conv2D(nb_filters, (5, 5), strides=(2, 2), padding="same",
input_shape=(28, 28, 1)),
Activation('relu'),
Conv2D(nb_filters, (3, 3), strides=(2, 2), padding="valid"),
Activation('relu'),
Conv2D(nb_filters, (3, 3), strides=(1, 1), padding="valid"),
Activation('relu'),
Flatten(),
Dense(32),
Activation('relu'),
Dropout(.5),
Dense(num_labels)]
for layer in layers:
model.add(layer)
keras.backend.set_learning_phase(False)
print("Model type is: ", type(model))
fake_data = np.random.rand(28, 28, 1, 32)
print("Data type is: ", type(fake_data)) | [
"keras.layers.Conv2D",
"numpy.random.rand",
"keras.layers.Flatten",
"keras.models.Sequential",
"keras.layers.Dropout",
"keras.layers.Activation",
"keras.layers.Dense",
"keras.backend.set_learning_phase"
] | [((437, 449), 'keras.models.Sequential', 'Sequential', ([], {}), '()\n', (447, 449), False, 'from keras.models import Sequential\n'), ((995, 1034), 'keras.backend.set_learning_phase', 'keras.backend.set_learning_phase', (['(False)'], {}), '(False)\n', (1027, 1034), False, 'import keras\n'), ((1085, 1114), 'numpy.random.rand', 'np.random.rand', (['(28)', '(28)', '(1)', '(32)'], {}), '(28, 28, 1, 32)\n', (1099, 1114), True, 'import numpy as np\n'), ((493, 580), 'keras.layers.Conv2D', 'Conv2D', (['nb_filters', '(5, 5)'], {'strides': '(2, 2)', 'padding': '"""same"""', 'input_shape': '(28, 28, 1)'}), "(nb_filters, (5, 5), strides=(2, 2), padding='same', input_shape=(28,\n 28, 1))\n", (499, 580), False, 'from keras.layers import Conv2D, MaxPooling2D, Dropout\n'), ((605, 623), 'keras.layers.Activation', 'Activation', (['"""relu"""'], {}), "('relu')\n", (615, 623), False, 'from keras.layers import Dense, Dropout, Activation, Flatten\n'), ((635, 694), 'keras.layers.Conv2D', 'Conv2D', (['nb_filters', '(3, 3)'], {'strides': '(2, 2)', 'padding': '"""valid"""'}), "(nb_filters, (3, 3), strides=(2, 2), padding='valid')\n", (641, 694), False, 'from keras.layers import Conv2D, MaxPooling2D, Dropout\n'), ((706, 724), 'keras.layers.Activation', 'Activation', (['"""relu"""'], {}), "('relu')\n", (716, 724), False, 'from keras.layers import Dense, Dropout, Activation, Flatten\n'), ((736, 795), 'keras.layers.Conv2D', 'Conv2D', (['nb_filters', '(3, 3)'], {'strides': '(1, 1)', 'padding': '"""valid"""'}), "(nb_filters, (3, 3), strides=(1, 1), padding='valid')\n", (742, 795), False, 'from keras.layers import Conv2D, MaxPooling2D, Dropout\n'), ((807, 825), 'keras.layers.Activation', 'Activation', (['"""relu"""'], {}), "('relu')\n", (817, 825), False, 'from keras.layers import Dense, Dropout, Activation, Flatten\n'), ((837, 846), 'keras.layers.Flatten', 'Flatten', ([], {}), '()\n', (844, 846), False, 'from keras.layers import Dense, Dropout, Activation, Flatten\n'), ((858, 867), 'keras.layers.Dense', 'Dense', (['(32)'], {}), '(32)\n', (863, 867), False, 'from keras.layers import Dense, Dropout, Activation, Flatten\n'), ((879, 897), 'keras.layers.Activation', 'Activation', (['"""relu"""'], {}), "('relu')\n", (889, 897), False, 'from keras.layers import Dense, Dropout, Activation, Flatten\n'), ((909, 921), 'keras.layers.Dropout', 'Dropout', (['(0.5)'], {}), '(0.5)\n', (916, 921), False, 'from keras.layers import Conv2D, MaxPooling2D, Dropout\n'), ((932, 949), 'keras.layers.Dense', 'Dense', (['num_labels'], {}), '(num_labels)\n', (937, 949), False, 'from keras.layers import Dense, Dropout, Activation, Flatten\n')] |
"""
Auxiliar retrievers parsing
---------------------------
Tools and utilities to parse heterogenous ways to give retriever information
in order to obtain retriever objects.
"""
import numpy as np
from retrievers import BaseRetriever
from collectionretrievers import RetrieverManager
from pySpatialTools.Discretization import _discretization_parsing_creation
###############################################################################
######################## Main paser creation functions ########################
###############################################################################
################################## Retrievers #################################
def _retrieverobject_parsing_creation(retriever_info):
"""Function which uniforms the retriever info to be useful in other
parts of the code.
Parameters
----------
retriever_info: pst.BaseRetriever or tuple
Variable which contains the retriever information. The standarts input
of that variable are:
* Retriever object
* (Retriever class, main_info)
* (Retriever class, main_info, pars_ret)
* (Retriever class, main_info, pars_ret, autolocs)
Returns
-------
retriever_info: pst.BaseRetriever
the retriever instance.
"""
if isinstance(retriever_info, BaseRetriever):
pass
else:
assert(type(retriever_info) == tuple)
assert(isinstance(retriever_info[0], object))
pars_ret = {}
if len(retriever_info) >= 3:
pars_ret = retriever_info[2]
if len(retriever_info) == 4:
pars_ret['autolocs'] = retriever_info[3]
retriever_info = retriever_info[0](retriever_info[1], **pars_ret)
assert(isinstance(retriever_info, BaseRetriever))
return retriever_info
def _retrievermanager_parsing_creation(retriever_info):
"""Function which uniforms the retriever info to be useful in other
parts of the code.
Parameters
----------
retriever_info: pst.BaseRetriever or tuple
Variable which contains the retriever information. The standarts input
of that variable are:
* Retriever object
* Retriever objects
* RetrieverManager objects
Returns
-------
retriever_info: pst.BaseRetriever
the retriever instance.
"""
if isinstance(retriever_info, BaseRetriever):
retriever_info = RetrieverManager(retriever_info)
elif type(retriever_info) == list:
assert(all([isinstance(e, BaseRetriever) for e in retriever_info]))
retriever_info = RetrieverManager(retriever_info)
else:
assert(isinstance(retriever_info, RetrieverManager))
assert(isinstance(retriever_info, RetrieverManager))
return retriever_info
def _retriever_parsing_creation(retriever_info):
"""Function which uniforms the retriever info to be useful in other
parts of the code.
Parameters
----------
retriever_info: pst.BaseRetriever or tuple
Variable which contains the retriever information. The standarts input
of that variable are:
* Retriever object
* (Retriever class, main_info)
* (Retriever class, main_info, pars_ret)
* (Retriever class, main_info, pars_ret, autolocs)
Returns
-------
retriever_info: pst.BaseRetriever
the retriever instance.
"""
if isinstance(retriever_info, RetrieverManager):
pass
elif isinstance(retriever_info, BaseRetriever):
retriever_info = _retrievermanager_parsing_creation(retriever_info)
elif type(retriever_info) == list:
r = [_retrieverobject_parsing_creation(ret) for ret in retriever_info]
retriever_info = _retrievermanager_parsing_creation(r)
else:
retriever_info = _retrieverobject_parsing_creation(retriever_info)
retriever_info = _retrievermanager_parsing_creation(retriever_info)
assert(isinstance(retriever_info, RetrieverManager))
return retriever_info
###############################################################################
################## Creation of automatic discretization maps ##################
###############################################################################
def create_m_in_inverse_discretization(discretization_info):
"""Create in_map for inverse discretization.
Parameters
----------
discretization_info: tuple or pst.BaseSpatialDiscretizor
It is defined by a discretization object or a tuple of locations,
regions and discretization object. The standard inputs of that
function parameter are:
* (discretizator, locs)
* (locs, regions)
* disc
* locs, regs, disc
Returns
-------
m_in_inverse_discretazation: function
the function which formats the input of the retriever.
"""
## 0. Parsing discretization information input
locs, regions, disc = _discretization_parsing_creation(discretization_info)
## 1. Building map
def m_in_inverse_discretazation(self, idxs):
"""Inverse application of the discretization information."""
new_idxs = []
for i in idxs:
new_idxs.append(np.where(regions == i)[0])
return new_idxs
return m_in_inverse_discretazation
def create_m_in_direct_discretization(discretization_info):
"""Create in_map for direct discretization.
Parameters
----------
discretization_info: tuple or pst.BaseSpatialDiscretizor
It is defined by a discretization object or a tuple of locations,
regions and discretization object. The standard inputs of that
function parameter are:
* (discretizator, locs)
* (locs, regions)
* disc
* locs, regs, disc
Returns
-------
m_in_direct_discretazation: function
the function which formats the input of the retriever.
"""
## 0. Parsing discretization information input
locs, regions, disc = _discretization_parsing_creation(discretization_info)
## 1. Building map
if disc is not None:
def m_in_direct_discretazation(self, idxs):
"""Direct application of the discretization information."""
return [disc.discretize(locs[i]) for i in idxs]
else:
def m_in_direct_discretazation(self, idxs):
"""Direct application of the discretization information."""
return [np.array(regions[e]) for e in idxs]
return m_in_direct_discretazation
def create_m_out_inverse_discretization(discretization_info):
"""Create out_map for inverse discretization.
Parameters
----------
discretization_info: tuple or pst.BaseSpatialDiscretizor
It is defined by a discretization object or a tuple of locations,
regions and discretization object. The standard inputs of that
function parameter are:
* (discretizator, locs)
* (locs, regions)
* disc
* locs, regs, disc
Returns
-------
m_out_inverse_discretization: function
the function which formats the output of the retriever.
"""
## 0. Parsing discretization information input
locs, regions, disc = _discretization_parsing_creation(discretization_info)
## 1. Building map
if type(regions) == np.ndarray:
def m_out_inverse_discretization(self, idxs, neighs_info):
"""This out_map for retrievers change the size of neighbourhood by
substituting the regions_id or groups_id in the neighs_info for the
elements which belong to this groups.
"""
neighs, dists = neighs_info
neighs_o, dists_o = [], []
for iss_i in range(len(neighs)):
neighs_p, dists_p = [], []
for i in range(len(neighs[iss_i])):
neighs_ip = np.where(regions == neighs[iss_i][i])[0]
neighs_p.append(neighs_ip)
if dists[iss_i] is not None:
sh = len(neighs_ip), 1
dists_p.append(np.ones(sh) * dists[iss_i][i])
if neighs_p:
neighs_p = np.concatenate(neighs_p)
if dists_p:
dists_p = np.concatenate(dists_p)
else:
dists_p = np.ones((0, 1))
neighs_o.append(neighs_p)
dists_o.append(dists_p)
return neighs_o, dists_o
return m_out_inverse_discretization
def create_m_out_direct_discretization(discretization_info):
"""Create out_map for inverse discretization.
Parameters
----------
discretization_info: tuple or pst.BaseSpatialDiscretizor
It is defined by a discretization object or a tuple of locations,
regions and discretization object. The standard inputs of that
function parameter are:
* (discretizator, locs)
* (locs, regions)
* disc
* locs, regs, disc
Returns
-------
m_out_direct_discretization: function
the function which formats the output of the retriever.
"""
## 0. Parsing discretization information input
locs, regions, disc = _discretization_parsing_creation(discretization_info)
## 1. Building map
if disc is None:
def m_out_direct_discretization(self, idxs, neighs_info):
"""This out_map for retrievers don't change the size of
neighbourhood, only substitutes the element id for the group or
regions id. It is useful for PhantomFeatures and direct distance
features. Distance don't change.
Parameters
----------
neighs_info: tuple (neighs, dists)
the neighbourhood information.
Returns
-------
neighs_info: tuple (neighs, dists)
the neighbourhood information.
"""
neighs, dists = neighs_info
neighs_o = []
for iss_i in range(len(neighs)):
neighs_p = []
for i in range(len(neighs[iss_i])):
neighs_ip = np.array([regions[neighs[iss_i][i]]]).ravel()
neighs_p.append(neighs_ip)
if neighs_p:
neighs_p = np.concatenate(neighs_p)
neighs_o.append(neighs_p)
return neighs_o, dists
else:
def m_out_direct_discretization(self, idxs, neighs_info):
"""This out_map for retrievers don't change the size of
neighbourhood, only substitutes the element id for the group or
regions id. It is useful for PhantomFeatures and direct distance
features. Distance don't change.
Parameters
----------
neighs_info: tuple (neighs, dists)
the neighbourhood information.
Returns
-------
neighs_info: tuple (neighs, dists)
the neighbourhood information.
"""
neighs, dists = neighs_info
neighs_o = []
for iss_i in range(len(neighs)):
neighs_p = []
for i in range(len(neighs[iss_i])):
neighs_ip = disc.discretize(locs[neighs[iss_i][i]])
neighs_p.append(np.array([neighs_ip]).ravel())
if neighs_p:
neighs_p = np.concatenate(neighs_p)
neighs_o.append(neighs_p)
return neighs_o, dists
return m_out_direct_discretization
| [
"pySpatialTools.Discretization._discretization_parsing_creation",
"numpy.ones",
"collectionretrievers.RetrieverManager",
"numpy.where",
"numpy.array",
"numpy.concatenate"
] | [((5014, 5067), 'pySpatialTools.Discretization._discretization_parsing_creation', '_discretization_parsing_creation', (['discretization_info'], {}), '(discretization_info)\n', (5046, 5067), False, 'from pySpatialTools.Discretization import _discretization_parsing_creation\n'), ((6084, 6137), 'pySpatialTools.Discretization._discretization_parsing_creation', '_discretization_parsing_creation', (['discretization_info'], {}), '(discretization_info)\n', (6116, 6137), False, 'from pySpatialTools.Discretization import _discretization_parsing_creation\n'), ((7316, 7369), 'pySpatialTools.Discretization._discretization_parsing_creation', '_discretization_parsing_creation', (['discretization_info'], {}), '(discretization_info)\n', (7348, 7369), False, 'from pySpatialTools.Discretization import _discretization_parsing_creation\n'), ((9337, 9390), 'pySpatialTools.Discretization._discretization_parsing_creation', '_discretization_parsing_creation', (['discretization_info'], {}), '(discretization_info)\n', (9369, 9390), False, 'from pySpatialTools.Discretization import _discretization_parsing_creation\n'), ((2455, 2487), 'collectionretrievers.RetrieverManager', 'RetrieverManager', (['retriever_info'], {}), '(retriever_info)\n', (2471, 2487), False, 'from collectionretrievers import RetrieverManager\n'), ((2628, 2660), 'collectionretrievers.RetrieverManager', 'RetrieverManager', (['retriever_info'], {}), '(retriever_info)\n', (2644, 2660), False, 'from collectionretrievers import RetrieverManager\n'), ((6524, 6544), 'numpy.array', 'np.array', (['regions[e]'], {}), '(regions[e])\n', (6532, 6544), True, 'import numpy as np\n'), ((5283, 5305), 'numpy.where', 'np.where', (['(regions == i)'], {}), '(regions == i)\n', (5291, 5305), True, 'import numpy as np\n'), ((8287, 8311), 'numpy.concatenate', 'np.concatenate', (['neighs_p'], {}), '(neighs_p)\n', (8301, 8311), True, 'import numpy as np\n'), ((8370, 8393), 'numpy.concatenate', 'np.concatenate', (['dists_p'], {}), '(dists_p)\n', (8384, 8393), True, 'import numpy as np\n'), ((8446, 8461), 'numpy.ones', 'np.ones', (['(0, 1)'], {}), '((0, 1))\n', (8453, 8461), True, 'import numpy as np\n'), ((10439, 10463), 'numpy.concatenate', 'np.concatenate', (['neighs_p'], {}), '(neighs_p)\n', (10453, 10463), True, 'import numpy as np\n'), ((11568, 11592), 'numpy.concatenate', 'np.concatenate', (['neighs_p'], {}), '(neighs_p)\n', (11582, 11592), True, 'import numpy as np\n'), ((7973, 8010), 'numpy.where', 'np.where', (['(regions == neighs[iss_i][i])'], {}), '(regions == neighs[iss_i][i])\n', (7981, 8010), True, 'import numpy as np\n'), ((10286, 10323), 'numpy.array', 'np.array', (['[regions[neighs[iss_i][i]]]'], {}), '([regions[neighs[iss_i][i]]])\n', (10294, 10323), True, 'import numpy as np\n'), ((8196, 8207), 'numpy.ones', 'np.ones', (['sh'], {}), '(sh)\n', (8203, 8207), True, 'import numpy as np\n'), ((11477, 11498), 'numpy.array', 'np.array', (['[neighs_ip]'], {}), '([neighs_ip])\n', (11485, 11498), True, 'import numpy as np\n')] |
from sleep_tracking.utils import get_root_directory
import os
from abc import ABC, abstractmethod
import pandas as pd
import numpy as np
from typing import List
class AbstractFeature(ABC):
WINDOW_SIZE = 10 * 30 - 15
EPOCH_DURATION = 30
def __init__(self, name):
self.name = name
@abstractmethod
def build(self, subject):
pass
def get_file_location(self, subject):
return os.path.join(get_root_directory(),
"data/features/%s_%s.out" % (subject, self.name))
def write(self, subject_ids: List[int]) -> None:
for subject in subject_ids:
features_df = self.build(subject)
features_df.to_csv(self.get_file_location(subject), index=False)
def load(self, subject_ids: List[int]) -> pd.DataFrame:
features = []
for subject in subject_ids:
feature_df = pd.read_csv(self.get_file_location(subject))
feature_df['subject'] = subject
feature_df = feature_df.reindex(columns=['subject'] + feature_df.columns[:-1].to_list())
features.append(feature_df)
return pd.concat(features, ignore_index=True)
def find_epoch_window(self, psg_epoch_timestamp, measurement_timestamps):
start_time = psg_epoch_timestamp - self.WINDOW_SIZE
end_time = psg_epoch_timestamp + self.EPOCH_DURATION + self.WINDOW_SIZE
timestamps_ravel = measurement_timestamps.ravel()
indices_in_range = np.unravel_index(np.where((timestamps_ravel > start_time) & (timestamps_ravel < end_time)),
measurement_timestamps.shape)
return indices_in_range[0][0]
@staticmethod
def interpolate(measurement_timestamps, measurement_values):
interpolated_timestamps = np.arange(np.amin(measurement_timestamps),
np.amax(measurement_timestamps), 1)
interpolated_values = np.apply_along_axis(
lambda x: np.interp(interpolated_timestamps, measurement_timestamps, x), 0,
np.atleast_2d(measurement_values.T).T)
return interpolated_timestamps, interpolated_values
| [
"numpy.atleast_2d",
"numpy.amin",
"numpy.where",
"sleep_tracking.utils.get_root_directory",
"pandas.concat",
"numpy.interp",
"numpy.amax"
] | [((1141, 1179), 'pandas.concat', 'pd.concat', (['features'], {'ignore_index': '(True)'}), '(features, ignore_index=True)\n', (1150, 1179), True, 'import pandas as pd\n'), ((439, 459), 'sleep_tracking.utils.get_root_directory', 'get_root_directory', ([], {}), '()\n', (457, 459), False, 'from sleep_tracking.utils import get_root_directory\n'), ((1501, 1574), 'numpy.where', 'np.where', (['((timestamps_ravel > start_time) & (timestamps_ravel < end_time))'], {}), '((timestamps_ravel > start_time) & (timestamps_ravel < end_time))\n', (1509, 1574), True, 'import numpy as np\n'), ((1816, 1847), 'numpy.amin', 'np.amin', (['measurement_timestamps'], {}), '(measurement_timestamps)\n', (1823, 1847), True, 'import numpy as np\n'), ((1893, 1924), 'numpy.amax', 'np.amax', (['measurement_timestamps'], {}), '(measurement_timestamps)\n', (1900, 1924), True, 'import numpy as np\n'), ((2002, 2063), 'numpy.interp', 'np.interp', (['interpolated_timestamps', 'measurement_timestamps', 'x'], {}), '(interpolated_timestamps, measurement_timestamps, x)\n', (2011, 2063), True, 'import numpy as np\n'), ((2080, 2115), 'numpy.atleast_2d', 'np.atleast_2d', (['measurement_values.T'], {}), '(measurement_values.T)\n', (2093, 2115), True, 'import numpy as np\n')] |
import threading
import settings as s
from collections import namedtuple, deque
from api.actions import Actions
from analytics_frame import Analytics
from api.agent_analytics_frame import AgentAnalyticsFrameAPI
import random
import math
import copy
from sklearn.preprocessing import MinMaxScaler
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
DEVICE = torch.device("cpu") # use CPU rather than Cuda GPU to power agent
EXPERIENCE = namedtuple("Experience",
field_names=["state", "action", "reward", "next_state"])
GAMMA = 0.999
is_calc_grad = False
class LearnerAgent(AgentAnalyticsFrameAPI):
agent_instance = None
@staticmethod
def create_agent_instance(game_inst):
if LearnerAgent.agent_instance is None:
LearnerAgent.agent_instance = LearnerAgent(game_inst, EpsilonGreedyStrategy(s.EPSILON_START, s.EPSILON_END, s.EPSILON_DECAY))
@staticmethod
def run_decision():
thread = threading.Thread(target=LearnerAgent.agent_instance.decide)
thread.start()
@staticmethod
def reset():
LearnerAgent.agent_instance.reset_agent()
def __init__(self, pacman_inst, learning_strat):
self.api = pacman_inst
self.learning_strat = learning_strat
self.learning_rate = None
self.policy_net = Network(pacman_inst)
self.target_net = Network(pacman_inst)
self.target_net.load_state_dict(self.policy_net.state_dict())
self.target_net.eval()
self.memory = ReplayMemory(s.REPLAY_MEMORY_SIZE)
self.current_state = self.get_game_vals(True)
self.prev_decision = None
self.ghost_list = []
self.pellet_tuple = ()
self.power_tuple = ()
self.power_active = False
self.decision = None
self.decision_type = ""
self.decision_count = 0
def reset_agent(self):
self.policy_net = Network(self.api)
self.target_net = Network(self.api)
self.target_net.load_state_dict(self.policy_net.state_dict())
self.target_net.eval()
self.learning_rate = None
self.memory = ReplayMemory(s.REPLAY_MEMORY_SIZE)
self.current_state = self.get_game_vals(True)
self.prev_decision = None
self.ghost_list = []
self.pellet_tuple = ()
self.power_tuple = ()
self.power_active = False
self.decision = None
self.decision_type = ""
self.decision_count = 0
def decide(self):
state = self.get_game_vals(True)
rate = self.learning_strat.get_rate()
decision = None
if random.random() > rate:
with torch.no_grad():
output = self.policy_net(state).tolist()
best_decision = (Actions.UP, -1000000)
for action in self.api.getAvailableActions(None):
if output[action.value] > best_decision[1]:
best_decision = (action, output[action.value])
decision = best_decision[0]
self.decision_type = "EXPLOITATION"
#print("Calculated decision: " + str(decision))
else:
decision = random.choice(self.api.getAvailableActions(self.prev_decision))
self.decision_type = "EXPLORATION"
#print("Random decision: " + str(decision))
self.choose_action(decision)
self.prev_decision = decision
self.memory.add(self.current_state.unsqueeze(0), torch.tensor([[decision.value]]),
torch.tensor([[self.api.getReward()]]), state.unsqueeze(0))
if self.memory.can_provide_sample(s.REPLAY_BATCH_SIZE) and safe_batch():
torch.autograd.set_detect_anomaly(True)
toggle_safe_batch()
transitions = self.memory.sample(s.REPLAY_BATCH_SIZE)
batch = EXPERIENCE(*zip(*transitions))
non_final_mask = torch.tensor(tuple(map(lambda s: s is not None,
batch.next_state)), device=DEVICE, dtype=torch.bool)
non_final_next_states = torch.cat([s for s in batch.next_state
if s is not None])
state_batch = torch.cat(batch.state).clone()
action_batch = torch.cat(batch.action).clone()
reward_batch = torch.cat(batch.reward).clone()
state_action_values = self.policy_net(state_batch).gather(1, action_batch).clone() #this line fails to compute gradient
next_state_values = torch.zeros(s.REPLAY_BATCH_SIZE, device=DEVICE)
next_state_values[non_final_mask] = self.target_net(non_final_next_states).max(1)[0].detach().clone()
expected_state_action_values = next_state_values * GAMMA
for i in range(s.REPLAY_BATCH_SIZE):
expected_state_action_values[i] = expected_state_action_values[i] + reward_batch[i][0]
expected_state_action_values = expected_state_action_values.unsqueeze(1)
loss = F.smooth_l1_loss(state_action_values.clone(), expected_state_action_values).clone()
optimizer = optim.RMSprop(self.policy_net.parameters(),
lr=self.init_learning_rate() if self.learning_rate is None else self.learning_rate)
optimizer.zero_grad()
loss.backward() # BUG: this fails after a few runs
for param in self.policy_net.parameters():
param.grad.data.clamp_(-1, 1)
optimizer.step()
toggle_safe_batch()
self.current_state = state
def choose_action(self, decision):
if decision is Actions.UP:
self.decision = "UP"
self.api.moveUp()
elif decision is Actions.DOWN:
self.decision = "DOWN"
self.api.moveDown()
elif decision is Actions.LEFT:
self.decision = "LEFT"
self.api.moveLeft()
elif decision is Actions.RIGHT:
self.decision = "RIGHT"
self.api.moveRight()
self.decision_count += 1
def get_game_vals(self, normalize):
ghost_list = self.api.getGhostsGridCoords()
pellet_tuple = self.api.getNearestPelletGridCoords()
power_tuple = self.api.getNearestPowerPelletGridCoords()
power_active = self.api.isPowerPelletActive()
values = [ghost_list[0][0], ghost_list[0][1], ghost_list[1][0], ghost_list[1][1], ghost_list[2][0],
ghost_list[2][1], ghost_list[3][0], ghost_list[3][1], pellet_tuple[0], pellet_tuple[1],
power_tuple[0], power_tuple[1], s.GRID_H if power_active else -s.GRID_H]
value_length = len(values)
if normalize:
values.append(-s.GRID_H)
values.append(s.GRID_H)
values = MinMaxScaler(feature_range=(-1, 1)).fit_transform(np.array(values).reshape(-1, 1)).reshape(len(values),).tolist()
tensor = torch.Tensor(values[:value_length])
self.ghost_list = ghost_list
self.pellet_tuple = pellet_tuple
self.power_tuple = power_tuple
self.power_active = power_active
return tensor
def init_learning_rate(self):
self.learning_rate = Analytics.analytics_instance.learning_rate
return self.learning_rate
# -- -- -- AGENT API FUNCTIONS -- -- -- #
def get_network_structure(self):
return [13, 10, 10, 8, 4]
def get_activation_vals(self, layer_index):
try:
return self.policy_net.full_node_dist[layer_index]
except IndexError:
return None
def get_weights(self, layer_index):
try:
return next((weights[1] for weights in self.policy_net.full_weight_dist if weights[0] == layer_index), None)
# return self.policy_net.full_weight_dist[layer_index]
except IndexError:
return None
def get_logic_count(self):
return self.decision_count
def get_ghost_coords(self):
return self.ghost_list
def get_nearest_pellet_coords(self):
return self.pellet_tuple
def get_nearest_power_pellet_coords(self):
return self.power_tuple
def get_power_pellet_active_status(self):
return self.power_active
def get_decision(self):
return self.decision, self.decision_type
def set_learning_rate(self, learning_rate):
pass
def set_target_score(self, target_score):
self.api.setTarHighScore(target_score)
def set_game_start_pos(self, pos_dict, centered_start):
self.api.set_start_pos(pos_dict, centered_start)
def stop_sim(self):
pass
def start_sim(self):
self.api.gameStart()
def safe_batch():
return not is_calc_grad
def toggle_safe_batch():
global is_calc_grad
is_calc_grad = not is_calc_grad
class Network(nn.Module):
def __init__(self, pacmanInst):
super(Network, self).__init__()
self.input = nn.Linear(13, 10)
self.h1 = nn.Linear(10, 10)
self.h2 = nn.Linear(10, 8)
self.output = nn.Linear(8, 4)
self.squishifier = nn.Tanh()
self.api = pacmanInst
self.full_node_dist = []
self.full_weight_dist = []
def forward(self, x):
input_is_batch = isinstance(x.tolist()[0], list)
node_dist = [self.squishifier(x).tolist()]
weight_dist = []
for index, layer in [(0, self.input), (1, self.h1), (2, self.h2), (3, self.output)]:
x = layer(x)
x = self.squishifier(x)
if not input_is_batch:
node_dist.append(x.tolist())
weight_dist.append((index, layer.weight.tolist()))
if not input_is_batch:
self.full_node_dist = node_dist
self.full_weight_dist = weight_dist
return x
class ReplayMemory:
def __init__(self, capacity):
self.capacity = capacity
self.memory = deque(maxlen=capacity)
self.push_count = 0
def add(self,state, action, reward, next_state):
if len(self.memory) >= self.capacity:
self.memory[self.push_count % self.capacity] = EXPERIENCE(state,action,reward,next_state)
else:
self.memory.append(EXPERIENCE(state,action,reward,next_state))
self.push_count += 1
def sample(self, batch_size):
sampled_exp = random.sample(self.memory, batch_size)
return sampled_exp
def can_provide_sample(self, batch_size):
return len(self.memory) >= batch_size
def __len__(self):
return len(self.memory)
class EpsilonGreedyStrategy:
def __init__(self, start, end, decay):
self.start = start
self.end = end
self.decay = decay
self.step_count = 0
self.threshold = 0
def get_rate(self):
self.threshold = self.end + (self.start - self.end) * math.exp(-1 * self.step_count / self.decay)
self.step_count += 1
return self.threshold
| [
"math.exp",
"random.sample",
"collections.namedtuple",
"collections.deque",
"torch.nn.Tanh",
"torch.autograd.set_detect_anomaly",
"torch.Tensor",
"torch.tensor",
"torch.no_grad",
"numpy.array",
"torch.nn.Linear",
"threading.Thread",
"random.random",
"sklearn.preprocessing.MinMaxScaler",
... | [((422, 441), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (434, 441), False, 'import torch\n'), ((501, 586), 'collections.namedtuple', 'namedtuple', (['"""Experience"""'], {'field_names': "['state', 'action', 'reward', 'next_state']"}), "('Experience', field_names=['state', 'action', 'reward',\n 'next_state'])\n", (511, 586), False, 'from collections import namedtuple, deque\n'), ((1008, 1067), 'threading.Thread', 'threading.Thread', ([], {'target': 'LearnerAgent.agent_instance.decide'}), '(target=LearnerAgent.agent_instance.decide)\n', (1024, 1067), False, 'import threading\n'), ((7076, 7111), 'torch.Tensor', 'torch.Tensor', (['values[:value_length]'], {}), '(values[:value_length])\n', (7088, 7111), False, 'import torch\n'), ((9092, 9109), 'torch.nn.Linear', 'nn.Linear', (['(13)', '(10)'], {}), '(13, 10)\n', (9101, 9109), True, 'import torch.nn as nn\n'), ((9128, 9145), 'torch.nn.Linear', 'nn.Linear', (['(10)', '(10)'], {}), '(10, 10)\n', (9137, 9145), True, 'import torch.nn as nn\n'), ((9164, 9180), 'torch.nn.Linear', 'nn.Linear', (['(10)', '(8)'], {}), '(10, 8)\n', (9173, 9180), True, 'import torch.nn as nn\n'), ((9203, 9218), 'torch.nn.Linear', 'nn.Linear', (['(8)', '(4)'], {}), '(8, 4)\n', (9212, 9218), True, 'import torch.nn as nn\n'), ((9246, 9255), 'torch.nn.Tanh', 'nn.Tanh', ([], {}), '()\n', (9253, 9255), True, 'import torch.nn as nn\n'), ((10069, 10091), 'collections.deque', 'deque', ([], {'maxlen': 'capacity'}), '(maxlen=capacity)\n', (10074, 10091), False, 'from collections import namedtuple, deque\n'), ((10505, 10543), 'random.sample', 'random.sample', (['self.memory', 'batch_size'], {}), '(self.memory, batch_size)\n', (10518, 10543), False, 'import random\n'), ((2679, 2694), 'random.random', 'random.random', ([], {}), '()\n', (2692, 2694), False, 'import random\n'), ((3548, 3580), 'torch.tensor', 'torch.tensor', (['[[decision.value]]'], {}), '([[decision.value]])\n', (3560, 3580), False, 'import torch\n'), ((3761, 3800), 'torch.autograd.set_detect_anomaly', 'torch.autograd.set_detect_anomaly', (['(True)'], {}), '(True)\n', (3794, 3800), False, 'import torch\n'), ((4172, 4229), 'torch.cat', 'torch.cat', (['[s for s in batch.next_state if s is not None]'], {}), '([s for s in batch.next_state if s is not None])\n', (4181, 4229), False, 'import torch\n'), ((4628, 4675), 'torch.zeros', 'torch.zeros', (['s.REPLAY_BATCH_SIZE'], {'device': 'DEVICE'}), '(s.REPLAY_BATCH_SIZE, device=DEVICE)\n', (4639, 4675), False, 'import torch\n'), ((2720, 2735), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (2733, 2735), False, 'import torch\n'), ((11021, 11064), 'math.exp', 'math.exp', (['(-1 * self.step_count / self.decay)'], {}), '(-1 * self.step_count / self.decay)\n', (11029, 11064), False, 'import math\n'), ((4313, 4335), 'torch.cat', 'torch.cat', (['batch.state'], {}), '(batch.state)\n', (4322, 4335), False, 'import torch\n'), ((4371, 4394), 'torch.cat', 'torch.cat', (['batch.action'], {}), '(batch.action)\n', (4380, 4394), False, 'import torch\n'), ((4430, 4453), 'torch.cat', 'torch.cat', (['batch.reward'], {}), '(batch.reward)\n', (4439, 4453), False, 'import torch\n'), ((6944, 6979), 'sklearn.preprocessing.MinMaxScaler', 'MinMaxScaler', ([], {'feature_range': '(-1, 1)'}), '(feature_range=(-1, 1))\n', (6956, 6979), False, 'from sklearn.preprocessing import MinMaxScaler\n'), ((6994, 7010), 'numpy.array', 'np.array', (['values'], {}), '(values)\n', (7002, 7010), True, 'import numpy as np\n')] |
#!/usr/bin/env python3
from imutils.video import VideoStream
import cv2
import argparse
import imutils
import time
import sys
import socket
import imagezmq
from math import acos, pi, cos, asin, sin, sqrt
from threading import Thread
import robot_controller
import asyncio
import numpy as np
iter_count = 0
dist_1 = 0
dist_2 = 0
class ARTags:
global robot1_angle
global robot2_angle
def __init__(self, object_order):
self.ref_ID = 0
self.object_order = object_order
self.ref_marker_side_len = 7 #cm
self.distance_ratio = 0 #pixels per centimeter
self.num_markers = 7
self.coord_dict = self.initialize_coord_dict()
self.obstacle_ahead = 0
self.frame = None
self.object1, self.object2, self.object3, self.object4 = self.object_order[0], self.object_order[1], self.object_order[2], self.object_order[3]
self.robot1 = None
self.robot2 = None
# iter_count = 0
def initialize_coord_dict(self):
coord_dict = dict({})
for i in range(self.num_markers):
coord_dict[i] = [[(0,0),(0,0),(0,0),(0,0)], (0,0), (0,0)]
return coord_dict
def euc_dist(self, point1, point2):
'''
Find the distance between POINT1 and POINT2, both of which are tuples (x,y) in unit pixels
'''
return ((point1[0]-point2[0])**2 + (point1[1]-point2[1])**2)**(1/2)
def identify_ref_marker(self, color=(0, 0, 255)):
'''
Identifies the top_left_point, top_right_point, bottom_left_point, bottom_right_point, center, front_center of the REFERENCE MARKER
denoted by int MARKER_ID. FRAME is the current frame recorded by the camera
Calculates the distance ratio, aka pixels to cm ratio
Returns the CENTER of the REFERENCE MARKER
'''
corners_list = self.coord_dict[self.ref_ID][0]
corners = np.reshape(corners_list, (4, 2))
edge_len = self.euc_dist(corners[0], corners[1])
self.distance_ratio = edge_len/self.ref_marker_side_len
def identify_marker(self, marker_ID, color=(0, 255, 0)):
'''
Find the corners and centers of each marker with MARKER_ID int.
Make visual boxes around each marker
Return a tuple with CENTER and FRONT CENTRE coordinates
'''
corners_list = self.coord_dict[marker_ID][0]
corners = corners_list.reshape((4, 2))
(top_left, top_right, bottom_right, bottom_left) = corners
# Convert each x and y value into an int
top_left_point = (int(top_left[0]), int(top_left[1]))
top_right_point = (int(top_right[0]), int(top_right[1]))
bottom_left_point = (int(bottom_left[0]), int(bottom_left[1]))
bottom_right_point = (int(bottom_right[0]), int(bottom_right[1]))
# Draw bounding box around each AR Tag for visual purposes
self.frame = cv2.line(self.frame, top_left_point, top_right_point, color, 2)
self.frame = cv2.line(self.frame, top_right_point, bottom_right_point, color, 2)
self.frame = cv2.line(self.frame, bottom_right_point, bottom_left_point, color, 2)
self.frame = cv2.line(self.frame, bottom_left_point, top_left_point, color, 2)
# Find the center of the AR Tag
cX = int((top_left[0] + bottom_right[0])//2)
cY = int((top_left[1] + bottom_right[1])//2)
# Find the center front of the AR Tag
front_X = int((top_left[0] + top_right[0])//2)
front_Y = int((top_left[1] + top_right[1])//2)
self.frame = cv2.circle(self.frame, (cX, cY), 4, (0, 0, 255), -1)
return ((cX, cY), (front_X, front_Y))
def angle_between_markers1(self, from_center, to_center, from_front, robot):
'''
Finds the ANGLE that the robot needs to turn to face in the direction of the object,
using coorindate tuples FROM_CENTER, FROM_FRONT and TO_CENTER and the cosine rule
'''
a = self.euc_dist(from_front, from_center)
b = self.euc_dist(from_front, to_center)
c = self.euc_dist(from_center, to_center)
if a == 0 or b == 0 or c == 0 or (abs((a**2 + b**2 - c**2) / (2*a*b)) > 1):
# print("error in angle calculation w arccos, using last")
return robot.orient, robot.angle
angle = (acos((a**2 + b**2 - c**2) / (2*a*b)) * 180 / pi)
if ((from_front[0] - from_center[0]) * (to_center[1] - from_center[1])) - ((from_front[1] - from_center[1]) * (to_center[0] - from_center[0])) >= 0:
robot.orient = False
return False, angle
else:
robot.orient = True
return True, angle
def angle_between_markers2(self, negative, intermediate_angle, from_to_distance, robot):
if intermediate_angle == 0:
return 4
if intermediate_angle == robot.angle:
if robot.orient:
return -robot.angle - 1
else:
return robot.angle
c = sqrt(from_to_distance**2 + (14*self.distance_ratio)**2 - 2*from_to_distance*(14*self.distance_ratio)*cos(intermediate_angle*pi/180))
sanity = (from_to_distance * sin(intermediate_angle*pi/180))/c
if abs(sanity) > 1:
print("error in angle calculation w arcsin, using last")
if robot.orient:
return -robot.angle - 1
else:
return robot.angle
else:
desired_angle = (asin(sanity)*180/pi)
if negative:
return -desired_angle - 1
else:
return desired_angle
def update_corners(self, marker_dict, marker_params):
'''
MARKER_DICT is a dictionary of all the markers provided by the Aruco library.
MARKER_PARAMS is provided by the Aruco library as well.
Identifies all the markers, draws bounding boxes around them and updates the coord_dict dictionary
'''
# Corners and IDs only shows the AR tags that are visible at that instant
(corners, ids, rejected) = cv2.aruco.detectMarkers(self.frame, marker_dict, parameters=marker_params)
# print("IDs in the frame right now are ", ids)
if len(corners) > 0:
# flatten the ArUco IDs list
ids = ids.flatten()
# Therefore coordinate dict should also only have tags that are visible in the FRAME
#self.coord_dict = dict((idx, [corner]) for idx, corner in zip(ids, corners))
for idx, tag_corners in zip(ids, corners):
if idx > 7:
return;
idx_value = self.coord_dict[idx]
idx_value[0] = tag_corners
center, front_point = self.identify_marker(idx)
idx_value[1] = center
idx_value[2] = front_point
self.identify_ref_marker()
def assign_targets(self):
'''
Determine which OBJECT ROBOT1 and ROBOT2 should pick up first respectively,
depending on the order of the blocks and the distance between the robots and the blocks
assigns targets to the robots
'''
# Calculate the distance between the robots and the objects
dist_11 = self.euc_dist(self.coord_dict[self.robot1.id][1], self.coord_dict[self.object1][1])
dist_22 = self.euc_dist(self.coord_dict[self.robot2.id][1], self.coord_dict[self.object2][1])
dist_12 = self.euc_dist(self.coord_dict[self.robot1.id][1], self.coord_dict[self.object2][1])
dist_21 = self.euc_dist(self.coord_dict[self.robot2.id][1], self.coord_dict[self.object1][1])
# Calculate the total distance for each combination of robot-object assignments
dist_11_22 = dist_11 + dist_22
dist_12_21 = dist_12 + dist_21
print("dist_11_22 is ", dist_11_22)
print("dist_12_21 is ", dist_12_21)
# Assigns robots to objects based on the shortest total distance traveled
if dist_11_22 < dist_12_21:
self.robot1.dist = dist_11
self.robot2.dist = dist_22
self.robot1.target = self.object1
self.robot2.target = self.object2
else:
self.robot1.dist = dist_12
self.robot2.dist = dist_21
self.robot1.target = self.object2
self.robot2.target = self.object1
self.object_order.pop(0)
self.object_order.pop(0)
# given a robot, returns the angle to it's target
def find_angle(self, robot):
negative, inter_angle = self.angle_between_markers1(self.coord_dict[robot.id][1], self.coord_dict[robot.target][1], self.coord_dict[robot.id][2], robot)
angle = self.angle_between_markers2(negative, inter_angle, self.euc_dist(self.coord_dict[robot.id][2], self.coord_dict[robot.target][2]), robot)
return angle
def setup(cam_src):
'''
Sets up the camera to send footage to the server.
'''
sender = imagezmq.ImageSender(connect_to="tcp://localhost:5555")
cam_id = socket.gethostname()
vs = VideoStream(src=cam_src, framerate=30).start()
time.sleep(2.0)
print("video started")
start_time = time.time()
return vs, sender, cam_id
async def update_frame(cam_src, vs, sender, cam_id, task, marker_dict, marker_params):
'''
Updates the video frame based on the current position of the markers.
'''
p = 0
global iter_count
while True:
## CAMERA STUFF ##
new_vs = vs.read()
if np.array_equal(new_vs, task.frame):
print("camera not updating")
task.frame = new_vs
# If for some reason we cannot find the task frame, try again.
if task.frame is None:
print("reading video stream failed, trying again")
vs.stop()
vs, sender, cami_id = setup(cam_src)
task.frame = vs.read()
task.frame = imutils.resize(task.frame, width=1000)
task.update_corners(marker_dict, marker_params)
## CONTROL LOGIC ##
# start of run, need to get targets
if iter_count == 0:
task.assign_targets()
print("robot 1's target is", task.robot1.target)
print("robot 2's target is", task.robot2.target)
# update robots
for robot in [task.robot1, task.robot2]:
if not robot.finished:
# get new distance
robot.dist = task.euc_dist(task.coord_dict[robot.id][1], task.coord_dict[robot.target][1])
if robot.pick and not robot.depositing: # robot is holding object and waiting for drop off angle
robot.arrived = 0
robot.prev_target = robot.target
robot.target = task.ref_ID
robot.drive_cautious = 0
robot.dist = task.euc_dist(task.coord_dict[robot.id][1], task.coord_dict[robot.target][1])
print(robot.id, "is is heading to drop off")
# if robot that has an object has signaled a drop off
if robot.depositing and not robot.pick and not robot.arrived:
robot.target = robot.prev_target
robot.depositing = 0
# if robot that has an object has signaled a drop off
if robot.depositing and not robot.pick and robot.arrived:
robot.depositing = 0
robot.arrived = 0
robot.drive_cautious = 0
if len(task.object_order) > 0:
robot.target = task.object_order.pop(0)
robot.dist = task.euc_dist(task.coord_dict[robot.id][1], task.coord_dict[robot.target][1])
print(robot.id, "'s new target is ", robot.target)
else:
robot.finished = 1
robot.ready = 0
await robot.disconnect()
print(robot.id, " is FINISHED")
# update robot angles
angle = task.find_angle(robot)
robot.angle = angle
if robot.depositing == 0: # robot is always ready when not holding something
if robot.finished:
robot.ready = 0
else:
robot.ready = 1
if robot.pick and not robot.depositing and not robot.finished: # update ready and depositing state to start drop off
robot.ready = 1
robot.depositing = 1
# at object
if (robot.dist / task.distance_ratio) < 20 and robot.depositing and robot.id == 1: # signal arrive for drop off
if p == 0:
print(robot.id, "is at drop off point")
p += 1
robot.arrived = 1
# at object
if (robot.dist / task.distance_ratio) < 20 and robot.depositing and robot.id == 2: # signal arrive for drop off
if p == 0:
print(robot.id, "is at drop off point")
p += 1
robot.arrived = 1
if (robot.dist / task.distance_ratio) < 9.5 and not robot.depositing and robot.id == 1: # signal arrive for pick up
if p == 0:
print(robot.id, "is at object")
p += 1
robot.arrived = 1
if (robot.dist / task.distance_ratio) < 9.5 and not robot.depositing and robot.id == 2: # signal arrive for pick up
if p == 0:
print(robot.id, "is at object")
p += 1
robot.arrived = 1
elif (robot.dist / task.distance_ratio) >= 14 and not robot.depositing: # need to set arrive correctly again in back up
robot.arrived = 0
robot.drive_cautious = 0
# close enough to start driving cautiously
if (robot.dist / task.distance_ratio) < 30 and robot.id == 2:
if p == 1:
print(robot.id, "is close to the object")
p += 1
robot.drive_cautious = 1
if (robot.dist / task.distance_ratio) < 30 and robot.id == 1:
if p == 1:
print(robot.id, "is close to the object")
p += 1
robot.drive_cautious = 1
if robot.target == 100:
robot.ready = 0
iter_count+=1
sender.send_image(cam_id, new_vs)
await asyncio.sleep(0.05)
async def main(cam_src, order=[3, 4, 5, 6]):
marker_dict = cv2.aruco.Dictionary_get(cv2.aruco.DICT_4X4_50)
marker_params = cv2.aruco.DetectorParameters_create()
vs, sender, cam_id = setup(cam_src)
address1 = "C0:98:E5:49:30:01"
address2 = "C0:98:E5:49:30:02"
robot1 = robot_controller.RobotController(address1)
robot1.id = 1
robot2 = robot_controller.RobotController(address2)
robot2.id = 2
while not robot1.client.is_connected:
try:
print(f"Trying to connect to {robot1.address}")
await robot1.client.connect()
except Exception as e:
print(f"connection error on 1, address is", address1, "trying again")
while not robot2.client.is_connected:
try:
print(f"Trying to connect to {robot2.address}")
await robot2.client.connect()
except Exception as e:
print(f"connection error on 2, address is", address2, "trying again")
task = ARTags(order)
task.robot1 = robot1
task.robot2 = robot2
task_1 = asyncio.create_task(update_frame(cam_src, vs, sender, cam_id, task, marker_dict, marker_params))
task_2 = asyncio.create_task(robot1.send())
task_3 = asyncio.create_task(robot2.send())
print("Starting awaits")
while True:
await task_1
await task_2
await task_3
print("exited loop for some reason")
if __name__ == "__main__":
ap = argparse.ArgumentParser()
ap.add_argument("-o", "--order", nargs='+', type=int, required=False, help="Desired order of the objects. This should be a subset of the numbers 3, 4, 5, and 6. For instance, '-o 3 5 4 6'.")
ap.add_argument("-s", "--cam_src", type=int, required=True, help="Source camera ID")
args = vars(ap.parse_args())
asyncio.run(main(args["cam_src"], [int(_) for _ in args["order"]]))
| [
"math.acos",
"time.sleep",
"math.cos",
"numpy.reshape",
"imutils.video.VideoStream",
"argparse.ArgumentParser",
"cv2.line",
"cv2.aruco.Dictionary_get",
"asyncio.sleep",
"socket.gethostname",
"imagezmq.ImageSender",
"cv2.aruco.detectMarkers",
"cv2.aruco.DetectorParameters_create",
"cv2.circ... | [((8941, 8996), 'imagezmq.ImageSender', 'imagezmq.ImageSender', ([], {'connect_to': '"""tcp://localhost:5555"""'}), "(connect_to='tcp://localhost:5555')\n", (8961, 8996), False, 'import imagezmq\n'), ((9010, 9030), 'socket.gethostname', 'socket.gethostname', ([], {}), '()\n', (9028, 9030), False, 'import socket\n'), ((9091, 9106), 'time.sleep', 'time.sleep', (['(2.0)'], {}), '(2.0)\n', (9101, 9106), False, 'import time\n'), ((9152, 9163), 'time.time', 'time.time', ([], {}), '()\n', (9161, 9163), False, 'import time\n'), ((14811, 14858), 'cv2.aruco.Dictionary_get', 'cv2.aruco.Dictionary_get', (['cv2.aruco.DICT_4X4_50'], {}), '(cv2.aruco.DICT_4X4_50)\n', (14835, 14858), False, 'import cv2\n'), ((14879, 14916), 'cv2.aruco.DetectorParameters_create', 'cv2.aruco.DetectorParameters_create', ([], {}), '()\n', (14914, 14916), False, 'import cv2\n'), ((15046, 15088), 'robot_controller.RobotController', 'robot_controller.RobotController', (['address1'], {}), '(address1)\n', (15078, 15088), False, 'import robot_controller\n'), ((15120, 15162), 'robot_controller.RobotController', 'robot_controller.RobotController', (['address2'], {}), '(address2)\n', (15152, 15162), False, 'import robot_controller\n'), ((16196, 16221), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (16219, 16221), False, 'import argparse\n'), ((1905, 1937), 'numpy.reshape', 'np.reshape', (['corners_list', '(4, 2)'], {}), '(corners_list, (4, 2))\n', (1915, 1937), True, 'import numpy as np\n'), ((2906, 2969), 'cv2.line', 'cv2.line', (['self.frame', 'top_left_point', 'top_right_point', 'color', '(2)'], {}), '(self.frame, top_left_point, top_right_point, color, 2)\n', (2914, 2969), False, 'import cv2\n'), ((2991, 3058), 'cv2.line', 'cv2.line', (['self.frame', 'top_right_point', 'bottom_right_point', 'color', '(2)'], {}), '(self.frame, top_right_point, bottom_right_point, color, 2)\n', (2999, 3058), False, 'import cv2\n'), ((3080, 3149), 'cv2.line', 'cv2.line', (['self.frame', 'bottom_right_point', 'bottom_left_point', 'color', '(2)'], {}), '(self.frame, bottom_right_point, bottom_left_point, color, 2)\n', (3088, 3149), False, 'import cv2\n'), ((3171, 3236), 'cv2.line', 'cv2.line', (['self.frame', 'bottom_left_point', 'top_left_point', 'color', '(2)'], {}), '(self.frame, bottom_left_point, top_left_point, color, 2)\n', (3179, 3236), False, 'import cv2\n'), ((3562, 3614), 'cv2.circle', 'cv2.circle', (['self.frame', '(cX, cY)', '(4)', '(0, 0, 255)', '(-1)'], {}), '(self.frame, (cX, cY), 4, (0, 0, 255), -1)\n', (3572, 3614), False, 'import cv2\n'), ((6056, 6130), 'cv2.aruco.detectMarkers', 'cv2.aruco.detectMarkers', (['self.frame', 'marker_dict'], {'parameters': 'marker_params'}), '(self.frame, marker_dict, parameters=marker_params)\n', (6079, 6130), False, 'import cv2\n'), ((9486, 9520), 'numpy.array_equal', 'np.array_equal', (['new_vs', 'task.frame'], {}), '(new_vs, task.frame)\n', (9500, 9520), True, 'import numpy as np\n'), ((9885, 9923), 'imutils.resize', 'imutils.resize', (['task.frame'], {'width': '(1000)'}), '(task.frame, width=1000)\n', (9899, 9923), False, 'import imutils\n'), ((9040, 9078), 'imutils.video.VideoStream', 'VideoStream', ([], {'src': 'cam_src', 'framerate': '(30)'}), '(src=cam_src, framerate=30)\n', (9051, 9078), False, 'from imutils.video import VideoStream\n'), ((14723, 14742), 'asyncio.sleep', 'asyncio.sleep', (['(0.05)'], {}), '(0.05)\n', (14736, 14742), False, 'import asyncio\n'), ((4320, 4366), 'math.acos', 'acos', (['((a ** 2 + b ** 2 - c ** 2) / (2 * a * b))'], {}), '((a ** 2 + b ** 2 - c ** 2) / (2 * a * b))\n', (4324, 4366), False, 'from math import acos, pi, cos, asin, sin, sqrt\n'), ((5170, 5204), 'math.sin', 'sin', (['(intermediate_angle * pi / 180)'], {}), '(intermediate_angle * pi / 180)\n', (5173, 5204), False, 'from math import acos, pi, cos, asin, sin, sqrt\n'), ((5101, 5135), 'math.cos', 'cos', (['(intermediate_angle * pi / 180)'], {}), '(intermediate_angle * pi / 180)\n', (5104, 5135), False, 'from math import acos, pi, cos, asin, sin, sqrt\n'), ((5467, 5479), 'math.asin', 'asin', (['sanity'], {}), '(sanity)\n', (5471, 5479), False, 'from math import acos, pi, cos, asin, sin, sqrt\n')] |
#%%
import datetime
import time
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
from graspologic.embed import AdjacencySpectralEmbed
from pkg.data import load_split_connectome
from pkg.io import OUT_PATH
from pkg.io import glue as default_glue
from pkg.io import savefig
from pkg.plot import set_theme
from pkg.utils import get_hemisphere_indices
FILENAME = "rdpg_sweep"
DISPLAY_FIGS = True
OUT_PATH = OUT_PATH / FILENAME
def glue(name, var, **kwargs):
default_glue(name, var, FILENAME, **kwargs)
def gluefig(name, fig, **kwargs):
savefig(name, foldername=FILENAME, **kwargs)
glue(name, fig, figure=True)
if not DISPLAY_FIGS:
plt.close()
t0 = time.time()
rng = np.random.default_rng(8888)
#%%
dataset = "maggot_subset"
adj, nodes = load_split_connectome(dataset, weights=False)
left_inds, right_inds = get_hemisphere_indices(nodes)
left_adj = adj[left_inds][:, left_inds]
right_adj = adj[right_inds][:, right_inds]
# AB = adj[left_inds][:, right_inds]
# BA = adj[right_inds][:, left_inds]
#%%
max_rank = 64
ase = AdjacencySpectralEmbed(n_components=max_rank)
left_X, left_Y = ase.fit_transform(left_adj)
right_X, right_Y = ase.fit_transform(right_adj)
#%%
def make_P(X, Y, rank, pad):
P = X[:, :rank] @ Y[:, :rank].T
P[P < pad] = pad
P[P > 1 - pad] = 1 - pad
return P
def compute_log_likelihood(adj, P):
triu_inds = np.triu_indices_from(adj, k=1)
tril_inds = np.tril_indices_from(adj, k=-1)
flat_adj = np.concatenate((adj[triu_inds], adj[tril_inds]))
flat_P = np.concatenate((P[triu_inds], P[tril_inds]))
likelihood = flat_P**flat_adj * (1 - flat_P) ** (1 - flat_adj)
log_likelihood = np.sum(np.log(likelihood))
return log_likelihood
pad = 1 / (len(left_adj) ** 3)
rows = []
for rank in np.arange(1, max_rank):
for source in ["left", "right"]:
if source == "left":
P = make_P(left_X, left_Y, rank, pad)
else:
P = make_P(right_X, right_Y, rank, pad)
for target in ["left", "right"]:
if target == "left":
adj = left_adj
else:
adj = right_adj
log_lik = compute_log_likelihood(adj, P)
rows.append(
{"rank": rank, "log_lik": log_lik, "source": source, "target": target}
)
results = pd.DataFrame(rows)
#%%
set_theme()
fig, axs = plt.subplots(1, 2, figsize=(12, 6), sharey=True)
train = results[results["source"] == results["target"]]
test = results[results["source"] != results["target"]]
ax = axs[0]
sns.lineplot(data=train, x="rank", y="log_lik", hue="target", ax=ax)
ax.set(ylabel="Log likelihood", xlabel="Rank")
ax = axs[1]
sns.lineplot(data=test, x="rank", y="log_lik", hue="target", ax=ax)
ax.set(xlabel="Rank")
idxmaxs = test.groupby("target")["log_lik"].idxmax()
maxs = test.loc[idxmaxs]
x = maxs.iloc[0]["rank"]
y = maxs.iloc[0]["log_lik"]
plt.autoscale(False)
ax.plot((x, x), (ax.get_ylim()[0], y))
maxs
#%%
elapsed = time.time() - t0
delta = datetime.timedelta(seconds=elapsed)
print(f"Script took {delta}")
print(f"Completed at {datetime.datetime.now()}")
| [
"numpy.random.default_rng",
"numpy.log",
"matplotlib.pyplot.autoscale",
"datetime.timedelta",
"numpy.arange",
"matplotlib.pyplot.close",
"numpy.concatenate",
"pandas.DataFrame",
"numpy.tril_indices_from",
"graspologic.embed.AdjacencySpectralEmbed",
"pkg.io.glue",
"numpy.triu_indices_from",
"... | [((725, 736), 'time.time', 'time.time', ([], {}), '()\n', (734, 736), False, 'import time\n'), ((743, 770), 'numpy.random.default_rng', 'np.random.default_rng', (['(8888)'], {}), '(8888)\n', (764, 770), True, 'import numpy as np\n'), ((815, 860), 'pkg.data.load_split_connectome', 'load_split_connectome', (['dataset'], {'weights': '(False)'}), '(dataset, weights=False)\n', (836, 860), False, 'from pkg.data import load_split_connectome\n'), ((886, 915), 'pkg.utils.get_hemisphere_indices', 'get_hemisphere_indices', (['nodes'], {}), '(nodes)\n', (908, 915), False, 'from pkg.utils import get_hemisphere_indices\n'), ((1098, 1143), 'graspologic.embed.AdjacencySpectralEmbed', 'AdjacencySpectralEmbed', ([], {'n_components': 'max_rank'}), '(n_components=max_rank)\n', (1120, 1143), False, 'from graspologic.embed import AdjacencySpectralEmbed\n'), ((1823, 1845), 'numpy.arange', 'np.arange', (['(1)', 'max_rank'], {}), '(1, max_rank)\n', (1832, 1845), True, 'import numpy as np\n'), ((2374, 2392), 'pandas.DataFrame', 'pd.DataFrame', (['rows'], {}), '(rows)\n', (2386, 2392), True, 'import pandas as pd\n'), ((2398, 2409), 'pkg.plot.set_theme', 'set_theme', ([], {}), '()\n', (2407, 2409), False, 'from pkg.plot import set_theme\n'), ((2421, 2469), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(2)'], {'figsize': '(12, 6)', 'sharey': '(True)'}), '(1, 2, figsize=(12, 6), sharey=True)\n', (2433, 2469), True, 'import matplotlib.pyplot as plt\n'), ((2594, 2662), 'seaborn.lineplot', 'sns.lineplot', ([], {'data': 'train', 'x': '"""rank"""', 'y': '"""log_lik"""', 'hue': '"""target"""', 'ax': 'ax'}), "(data=train, x='rank', y='log_lik', hue='target', ax=ax)\n", (2606, 2662), True, 'import seaborn as sns\n'), ((2723, 2790), 'seaborn.lineplot', 'sns.lineplot', ([], {'data': 'test', 'x': '"""rank"""', 'y': '"""log_lik"""', 'hue': '"""target"""', 'ax': 'ax'}), "(data=test, x='rank', y='log_lik', hue='target', ax=ax)\n", (2735, 2790), True, 'import seaborn as sns\n'), ((2946, 2966), 'matplotlib.pyplot.autoscale', 'plt.autoscale', (['(False)'], {}), '(False)\n', (2959, 2966), True, 'import matplotlib.pyplot as plt\n'), ((3052, 3087), 'datetime.timedelta', 'datetime.timedelta', ([], {'seconds': 'elapsed'}), '(seconds=elapsed)\n', (3070, 3087), False, 'import datetime\n'), ((509, 552), 'pkg.io.glue', 'default_glue', (['name', 'var', 'FILENAME'], {}), '(name, var, FILENAME, **kwargs)\n', (521, 552), True, 'from pkg.io import glue as default_glue\n'), ((593, 637), 'pkg.io.savefig', 'savefig', (['name'], {'foldername': 'FILENAME'}), '(name, foldername=FILENAME, **kwargs)\n', (600, 637), False, 'from pkg.io import savefig\n'), ((1425, 1455), 'numpy.triu_indices_from', 'np.triu_indices_from', (['adj'], {'k': '(1)'}), '(adj, k=1)\n', (1445, 1455), True, 'import numpy as np\n'), ((1472, 1503), 'numpy.tril_indices_from', 'np.tril_indices_from', (['adj'], {'k': '(-1)'}), '(adj, k=-1)\n', (1492, 1503), True, 'import numpy as np\n'), ((1519, 1567), 'numpy.concatenate', 'np.concatenate', (['(adj[triu_inds], adj[tril_inds])'], {}), '((adj[triu_inds], adj[tril_inds]))\n', (1533, 1567), True, 'import numpy as np\n'), ((1581, 1625), 'numpy.concatenate', 'np.concatenate', (['(P[triu_inds], P[tril_inds])'], {}), '((P[triu_inds], P[tril_inds]))\n', (1595, 1625), True, 'import numpy as np\n'), ((3027, 3038), 'time.time', 'time.time', ([], {}), '()\n', (3036, 3038), False, 'import time\n'), ((706, 717), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (715, 717), True, 'import matplotlib.pyplot as plt\n'), ((1721, 1739), 'numpy.log', 'np.log', (['likelihood'], {}), '(likelihood)\n', (1727, 1739), True, 'import numpy as np\n'), ((3140, 3163), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (3161, 3163), False, 'import datetime\n')] |
"""
Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
WSO2 Inc. licenses this file to you under the Apache License,
Version 2.0 (the "License"); you may not use this file except
in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
"""
import numpy as np
import pyro
import pyro.contrib.gp as gp
import torch
assert pyro.__version__.startswith('1.0.0')
# pyro.enable_validation(True) # can help with debugging
seed = 42
np.random.seed(seed)
pyro.set_rng_seed(seed)
class GPR:
def __init__(self, dim, lengthscale=10, variance=0.5):
self.dim = dim
self.kernel = gp.kernels.RBF(input_dim=dim, variance=torch.tensor(variance),
lengthscale=torch.tensor(lengthscale))
self.gpr = self.optimizer = self.loss_fn = None
def fit(self, X, y, n_iter=100, learning_rate=0.005):
if X.shape[1] != self.dim:
raise Exception("number of features should be %d, provided %d" % (self.dim, X.shape[1]))
if not torch.is_tensor(X):
X = np.copy(X)
X = torch.tensor(X)
if not torch.is_tensor(y):
y = np.copy(y)
y = torch.tensor(y)
if self.gpr is None:
self.gpr = gp.models.GPRegression(X, y, self.kernel, noise=torch.tensor(0.1))
# initiate the optimizer
self.optimizer = torch.optim.Adam(self.gpr.parameters(), lr=learning_rate)
self.loss_fn = pyro.infer.Trace_ELBO().differentiable_loss
else:
self.gpr.set_data(X, y)
# learning hyper-parameters from the model
losses = []
for i in range(n_iter):
self.optimizer.zero_grad()
loss = self.loss_fn(self.gpr.model, self.gpr.guide)
loss.backward()
self.optimizer.step()
losses.append(loss.item())
return losses
def predict(self, X, return_unc=True):
if X.shape[1] != self.dim:
raise Exception("number of features should be %d, provided %d" % (self.dim, X.shape[1]))
if self.gpr is None:
raise Exception("train the model once first")
X = np.copy(X)
if not torch.is_tensor(X):
X = torch.tensor(X)
with torch.no_grad():
mean, cov = self.gpr(X, full_cov=True, noiseless=False)
mean, cov = mean.numpy(), cov.numpy()
if return_unc:
return mean, np.sqrt(np.diag(cov))
return mean
| [
"numpy.copy",
"pyro.infer.Trace_ELBO",
"numpy.diag",
"torch.is_tensor",
"torch.tensor",
"pyro.set_rng_seed",
"numpy.random.seed",
"torch.no_grad",
"pyro.__version__.startswith"
] | [((736, 772), 'pyro.__version__.startswith', 'pyro.__version__.startswith', (['"""1.0.0"""'], {}), "('1.0.0')\n", (763, 772), False, 'import pyro\n'), ((842, 862), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (856, 862), True, 'import numpy as np\n'), ((863, 886), 'pyro.set_rng_seed', 'pyro.set_rng_seed', (['seed'], {}), '(seed)\n', (880, 886), False, 'import pyro\n'), ((2567, 2577), 'numpy.copy', 'np.copy', (['X'], {}), '(X)\n', (2574, 2577), True, 'import numpy as np\n'), ((1413, 1431), 'torch.is_tensor', 'torch.is_tensor', (['X'], {}), '(X)\n', (1428, 1431), False, 'import torch\n'), ((1449, 1459), 'numpy.copy', 'np.copy', (['X'], {}), '(X)\n', (1456, 1459), True, 'import numpy as np\n'), ((1476, 1491), 'torch.tensor', 'torch.tensor', (['X'], {}), '(X)\n', (1488, 1491), False, 'import torch\n'), ((1508, 1526), 'torch.is_tensor', 'torch.is_tensor', (['y'], {}), '(y)\n', (1523, 1526), False, 'import torch\n'), ((1544, 1554), 'numpy.copy', 'np.copy', (['y'], {}), '(y)\n', (1551, 1554), True, 'import numpy as np\n'), ((1571, 1586), 'torch.tensor', 'torch.tensor', (['y'], {}), '(y)\n', (1583, 1586), False, 'import torch\n'), ((2594, 2612), 'torch.is_tensor', 'torch.is_tensor', (['X'], {}), '(X)\n', (2609, 2612), False, 'import torch\n'), ((2630, 2645), 'torch.tensor', 'torch.tensor', (['X'], {}), '(X)\n', (2642, 2645), False, 'import torch\n'), ((2660, 2675), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (2673, 2675), False, 'import torch\n'), ((1044, 1066), 'torch.tensor', 'torch.tensor', (['variance'], {}), '(variance)\n', (1056, 1066), False, 'import torch\n'), ((1117, 1142), 'torch.tensor', 'torch.tensor', (['lengthscale'], {}), '(lengthscale)\n', (1129, 1142), False, 'import torch\n'), ((1859, 1882), 'pyro.infer.Trace_ELBO', 'pyro.infer.Trace_ELBO', ([], {}), '()\n', (1880, 1882), False, 'import pyro\n'), ((1688, 1705), 'torch.tensor', 'torch.tensor', (['(0.1)'], {}), '(0.1)\n', (1700, 1705), False, 'import torch\n'), ((2848, 2860), 'numpy.diag', 'np.diag', (['cov'], {}), '(cov)\n', (2855, 2860), True, 'import numpy as np\n')] |
import numpy as np
from ..rdkit import smiles_list_to_fingerprints, precursors_from_templates
def tanimoto(fp1, fp2):
a = fp1.sum()
b = fp2.sum()
c = float((fp1&fp2).sum())
return c/(a+b-c)
def pairwise_tanimoto(arr1, arr2, metric=tanimoto):
if arr1.size == 0:
return np.array([[]])
return cdist(arr1, arr2, metric=metric)
def diversity_from_smiles_list(smiles_list, fp_length=2048, fp_radius=2, nproc=1):
fps = smiles_list_to_fingerprints(smiles_list, fp_length=fp_length, fp_radius=fp_radius, nproc=nproc)
similarity = pairwise_tanimoto(fps, fps)
diversity = 1 - similarity
np.fill_diagonal(diversity, np.nan)
return diversity
def diversity(model, test_smiles, templates, topk=100, fp_length=2048, fp_radius=2, nproc=1):
div = []
for smi in test_smiles:
fp = smiles_to_fingerprint(smi, length=fp_length, radius=fp_radius)
pred = model.predict(fp.reshape(1, -1)).reshape(-1)
ind = np.argsort(-pred)[:topk]
precursors = precursors_from_templates(smi, templates[ind], nproc=nproc)
div.append(diversity_from_smiles_list(precursors, nproc=nproc))
return div | [
"numpy.argsort",
"numpy.array",
"numpy.fill_diagonal"
] | [((627, 662), 'numpy.fill_diagonal', 'np.fill_diagonal', (['diversity', 'np.nan'], {}), '(diversity, np.nan)\n', (643, 662), True, 'import numpy as np\n'), ((298, 312), 'numpy.array', 'np.array', (['[[]]'], {}), '([[]])\n', (306, 312), True, 'import numpy as np\n'), ((970, 987), 'numpy.argsort', 'np.argsort', (['(-pred)'], {}), '(-pred)\n', (980, 987), True, 'import numpy as np\n')] |
#!/usr/bin/env python
import numpy as np
from os import path
def createSourceString(config, energy, angle):
'''Creates a source file from a configurator object and a specific
angle and energy.
config: the .yaml file used
energy:
angle:
'''
from utils import getFilenameFromDetails
fname = getFilenameFromDetails({'base': config['run']['basename'],
'keV': energy,
'Cos': angle})
srcstr = 'Version ' + str(config['general']['Version'])
srcstr += '\n'
srcstr += 'Geometry ' + str(config['general']['Geometry'])
srcstr += '\n'
srcstr += 'CheckForOverlaps ' + str(config['general']['CheckForOverlaps'])
srcstr += '\n'
srcstr += 'PhysicsListEM ' + str(config['general']['PhysicsListEM'])
srcstr += '\n'
srcstr += 'StoreCalibrate ' + str(config['general']['StoreCalibrate'])
srcstr += '\n'
srcstr += 'StoreSimulationInfo '
srcstr += str(config['general']['StoreSimulationInfo'])
srcstr += '\n'
srcstr += 'StoreOnlyEventsWithEnergyLoss '
srcstr += str(config['general']['StoreOnlyEventsWithEnergyLoss'])
srcstr += '\n'
srcstr += 'DiscretizeHits ' + str(config['general']['DiscretizeHits'])
srcstr += '\n'
srcstr += '\n'
srcstr += 'Run ' + config['source']['name']
srcstr += '\n'
srcstr += config['source']['name']+'.Filename '
srcstr += config['run']['simdir'] + fname
srcstr += '\n'
srcstr += config['source']['name']+'.NTriggers '
srcstr += str(config['source']['NTriggers'])
srcstr += '\n'
srcstr += config['source']['name']+'.Source One'
srcstr += '\n'
srcstr += 'One.ParticleType ' + str(config['source']['ParticleType'])
srcstr += '\n'
srcstr += 'One.Beam ' + config['source']['Beam'] + ' '
srcstr += str(np.round(np.rad2deg(angle), decimals=2)) + ' 0'
srcstr += '\n'
srcstr += 'One.Spectrum Mono '
srcstr += str(energy)
srcstr += '\n'
srcstr += 'One.Flux ' + str(config['source']['Flux'])
srcstr += '\n'
return srcstr
class configurator():
def __init__(self, path):
self.config = self.loadConfig(path)
def loadConfig(self, path):
import yaml
with open(path, 'r') as f:
config = yaml.load(f)
if config['run']['simdir'][-1] != '/':
config['run']['simdir'] += '/'
if config['run']['srcdir'][-1] != '/':
config['run']['srcdir'] += '/'
return config
@property
def costhetabins(self):
return np.linspace(self.config['run']['costhetamin'],
self.config['run']['costhetamax'],
self.config['run']['costhetanumbins'])
@property
def thetabins(self):
return np.round(np.rad2deg(self.costhetabins), decimals=2)
@property
def ebins(self):
return np.logspace(np.log10(self.config['run']['emin']),
np.log10(self.config['run']['emax']),
self.config['run']['enumbins'])
def createSourceFiles(self, dir=''):
from utils import getFilenameFromDetails
for angle, energy in [(angle, energy)
for angle in self.costhetabins
for energy in self.ebins]:
srcstr = createSourceString(self.config, energy, angle)
basename = self.config['run']['basename']
fname = getFilenameFromDetails({'base': basename,
'keV': energy,
'Cos': angle})
if dir:
fname = dir + '/' + fname + '.source'
else:
fname = self.config['run']['srcdir'] + '/' + fname + '.source'
f = open(path.expandvars(fname), 'w')
f.write(srcstr)
f.close()
| [
"numpy.log10",
"os.path.expandvars",
"yaml.load",
"numpy.linspace",
"numpy.rad2deg",
"utils.getFilenameFromDetails"
] | [((330, 422), 'utils.getFilenameFromDetails', 'getFilenameFromDetails', (["{'base': config['run']['basename'], 'keV': energy, 'Cos': angle}"], {}), "({'base': config['run']['basename'], 'keV': energy,\n 'Cos': angle})\n", (352, 422), False, 'from utils import getFilenameFromDetails\n'), ((2578, 2703), 'numpy.linspace', 'np.linspace', (["self.config['run']['costhetamin']", "self.config['run']['costhetamax']", "self.config['run']['costhetanumbins']"], {}), "(self.config['run']['costhetamin'], self.config['run'][\n 'costhetamax'], self.config['run']['costhetanumbins'])\n", (2589, 2703), True, 'import numpy as np\n'), ((2303, 2315), 'yaml.load', 'yaml.load', (['f'], {}), '(f)\n', (2312, 2315), False, 'import yaml\n'), ((2817, 2846), 'numpy.rad2deg', 'np.rad2deg', (['self.costhetabins'], {}), '(self.costhetabins)\n', (2827, 2846), True, 'import numpy as np\n'), ((2927, 2963), 'numpy.log10', 'np.log10', (["self.config['run']['emin']"], {}), "(self.config['run']['emin'])\n", (2935, 2963), True, 'import numpy as np\n'), ((2992, 3028), 'numpy.log10', 'np.log10', (["self.config['run']['emax']"], {}), "(self.config['run']['emax'])\n", (3000, 3028), True, 'import numpy as np\n'), ((3497, 3568), 'utils.getFilenameFromDetails', 'getFilenameFromDetails', (["{'base': basename, 'keV': energy, 'Cos': angle}"], {}), "({'base': basename, 'keV': energy, 'Cos': angle})\n", (3519, 3568), False, 'from utils import getFilenameFromDetails\n'), ((1858, 1875), 'numpy.rad2deg', 'np.rad2deg', (['angle'], {}), '(angle)\n', (1868, 1875), True, 'import numpy as np\n'), ((3850, 3872), 'os.path.expandvars', 'path.expandvars', (['fname'], {}), '(fname)\n', (3865, 3872), False, 'from os import path\n')] |
import argparse
from numpy.core.fromnumeric import shape
from tool.torch_utils import do_detect
import torch
import torch.backends.cudnn as cudnn
from tool.darknet2pytorch import Darknet
import timeit, time
import os
import numpy as np
import cv2
import json
import random
FRAME_SIZES = [64, 96, 128, 160, 192, 224, 256,
288, 320, 352, 384, 416, 448, 480,
512, 544, 576, 608, 640]
def set_deterministic_behaviour(seed):
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
cudnn.enabled = False
cudnn.deterministic = True
cudnn.benchmark = False
np.random.seed(seed)
random.seed(seed)
def parse_opts():
parser = argparse.ArgumentParser(description='Convert darknet model to pytorch',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--no_cuda', action='store_true',
help='If true, cuda is not used.')
parser.add_argument('--gpu_id', type=int, default=0,
help='GPU id')
parser.add_argument('--n_classes', type=int, default=80,
help='Number of classes in coco dataset')
parser.set_defaults(no_cuda=False)
parser.add_argument('--weights_dir', type=str,
help='Directory containing pytorch weights')
parser.add_argument('--model_config_dir', type=str,
default='cfg/', help='Model config directory')
parser.add_argument('--max_batch_size', type=int, default=32,
help='Maximum batch size')
parser.add_argument('--input_size', type=int,
help='Input size of model')
parser.add_argument('--gt_annotations_path', type=str, default='instances_val2017.json',
help='ground truth annotations file')
parser.add_argument('--dataset_dir', type=str,
default=None, help='dataset dir')
parser.add_argument('--total_iter', type=int,
default=100, help='Total iterations')
parser.add_argument('--log_dir', type=str, default="", help="Log dir")
args = parser.parse_args()
args_dict = args.__dict__
print('{:-^100}'.format('Configurations'))
for key in args_dict.keys():
print("- {}: {}".format(key, args_dict[key]))
print('{:-^100}'.format(''))
return args
def read_image_in_jpg(opts, frame_size, index, batch_size, total_images, images):
_ENCODE_PARAM = [int(cv2.IMWRITE_JPEG_QUALITY), 90]
jpg_files = []
indexes = []
for _ in range(batch_size):
# index = index % total_images
index = random.randint(0, total_images-1)
indexes.append(index)
image_file_name = images[index]["file_name"]
# print(image_file_name, opts.dataset_dir)
img = cv2.imread(os.path.join(opts.dataset_dir, image_file_name))
img = cv2.resize(img, (frame_size, frame_size), cv2.INTER_NEAREST)
jpg_file = cv2.imencode(".jpg", img, _ENCODE_PARAM)[1].tobytes()
jpg_files.append(jpg_file)
print("Images: ", indexes)
return jpg_files
def read_jpg_in_numpy(jpg_files, frame_size):
imgs = []
for jpg_file in jpg_files:
img = cv2.imdecode(np.fromstring(
jpg_file, dtype=np.uint8), cv2.IMREAD_UNCHANGED)
img = cv2.resize(img, (frame_size, frame_size), cv2.INTER_NEAREST)
imgs.append(img)
imgs = np.array(imgs)
return imgs
def test_model_time(opts, model, frame_size, annotations):
output_file = open(f'{opts.log_dir}/profile_latency_{frame_size}.txt'.format(frame_size), 'w')
print("{:<20s},{:<20s},{:<20s}".format(
"ModelSize", "Batch", "InferenceTime"), file=output_file)
images = annotations["images"]
img_idx = 0
total_images = len(images)
for batch in range(1, opts.max_batch_size+1, 1):
print("Processing batch size", batch)
for _ in range(opts.total_iter):
# time.sleep(0.004)
jpg_files = read_image_in_jpg(
opts, frame_size, img_idx, batch, total_images, images)
# input = np.random.rand(batch, frame_size, frame_size, 3)
torch.cuda.synchronize(opts.gpu_id)
start_time = timeit.default_timer()
start_perf = time.perf_counter()
input = read_jpg_in_numpy(jpg_files, frame_size) # dtype is uint8
batch_time = (timeit.default_timer() - start_time) * 1e3
assert input.shape[0] == batch and input.shape[1] == frame_size \
and input.shape[2] == frame_size and input.shape[3] == 3
with torch.no_grad():
output = do_detect(model, input, 0.20, 0.4,
use_cuda=(not opts.no_cuda), gpu_number=opts.gpu_id)
torch.cuda.synchronize(opts.gpu_id)
inference_time = (timeit.default_timer() - start_time) * 1000
perf_time = (time.perf_counter() - start_perf) * 1000
print("Processing batch size:", batch, batch_time, inference_time, perf_time)
print("{:<20d},{:<20d},{:<20.2f}".format(
frame_size, batch, inference_time), file=output_file)
# ms = torch.cuda.memory_summary(device=None, abbreviated=False)
# stats = torch.cuda.memory_stats(device=None)
# print(ms)
# torch.cuda.empty_cache()
output_file.close()
def load_model(opts, frame_size):
cfg_file_path = opts.model_config_dir + \
"/yolov4_" + str(frame_size) + ".cfg"
model = Darknet(cfg_file_path, inference=True)
weight_file = os.path.join(
opts.weights_dir, "yolov4_{}.pth".format(frame_size))
checkpoint = torch.load(
weight_file, map_location='cuda:{}'.format(opts.gpu_id))
model.load_state_dict(checkpoint['state_dict'])
model.eval()
if not opts.no_cuda:
model.cuda(opts.gpu_id)
# Zero grad for parameters
for param in model.parameters():
param.grad = None
return model
if __name__ == "__main__":
opts = parse_opts()
torch.cuda.set_device(opts.gpu_id)
annotations_file_path = opts.gt_annotations_path
with open(annotations_file_path) as annotations_file:
try:
annotations = json.load(annotations_file)
except:
print("annotations file not a json")
exit()
set_deterministic_behaviour(1)
frame_size = opts.input_size
model = load_model(opts, frame_size)
model.print_network()
test_model_time(opts, model, frame_size, annotations)
| [
"tool.darknet2pytorch.Darknet",
"numpy.array",
"torch.cuda.synchronize",
"argparse.ArgumentParser",
"time.perf_counter",
"numpy.random.seed",
"numpy.fromstring",
"random.randint",
"tool.torch_utils.do_detect",
"cv2.resize",
"torch.cuda.set_device",
"torch.cuda.manual_seed_all",
"torch.manual... | [((459, 482), 'torch.manual_seed', 'torch.manual_seed', (['seed'], {}), '(seed)\n', (476, 482), False, 'import torch\n'), ((487, 519), 'torch.cuda.manual_seed_all', 'torch.cuda.manual_seed_all', (['seed'], {}), '(seed)\n', (513, 519), False, 'import torch\n'), ((609, 629), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (623, 629), True, 'import numpy as np\n'), ((634, 651), 'random.seed', 'random.seed', (['seed'], {}), '(seed)\n', (645, 651), False, 'import random\n'), ((684, 815), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Convert darknet model to pytorch"""', 'formatter_class': 'argparse.ArgumentDefaultsHelpFormatter'}), "(description='Convert darknet model to pytorch',\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n", (707, 815), False, 'import argparse\n'), ((3437, 3451), 'numpy.array', 'np.array', (['imgs'], {}), '(imgs)\n', (3445, 3451), True, 'import numpy as np\n'), ((5566, 5604), 'tool.darknet2pytorch.Darknet', 'Darknet', (['cfg_file_path'], {'inference': '(True)'}), '(cfg_file_path, inference=True)\n', (5573, 5604), False, 'from tool.darknet2pytorch import Darknet\n'), ((6092, 6126), 'torch.cuda.set_device', 'torch.cuda.set_device', (['opts.gpu_id'], {}), '(opts.gpu_id)\n', (6113, 6126), False, 'import torch\n'), ((2653, 2688), 'random.randint', 'random.randint', (['(0)', '(total_images - 1)'], {}), '(0, total_images - 1)\n', (2667, 2688), False, 'import random\n'), ((2909, 2969), 'cv2.resize', 'cv2.resize', (['img', '(frame_size, frame_size)', 'cv2.INTER_NEAREST'], {}), '(img, (frame_size, frame_size), cv2.INTER_NEAREST)\n', (2919, 2969), False, 'import cv2\n'), ((3340, 3400), 'cv2.resize', 'cv2.resize', (['img', '(frame_size, frame_size)', 'cv2.INTER_NEAREST'], {}), '(img, (frame_size, frame_size), cv2.INTER_NEAREST)\n', (3350, 3400), False, 'import cv2\n'), ((2846, 2893), 'os.path.join', 'os.path.join', (['opts.dataset_dir', 'image_file_name'], {}), '(opts.dataset_dir, image_file_name)\n', (2858, 2893), False, 'import os\n'), ((3250, 3289), 'numpy.fromstring', 'np.fromstring', (['jpg_file'], {'dtype': 'np.uint8'}), '(jpg_file, dtype=np.uint8)\n', (3263, 3289), True, 'import numpy as np\n'), ((4191, 4226), 'torch.cuda.synchronize', 'torch.cuda.synchronize', (['opts.gpu_id'], {}), '(opts.gpu_id)\n', (4213, 4226), False, 'import torch\n'), ((4252, 4274), 'timeit.default_timer', 'timeit.default_timer', ([], {}), '()\n', (4272, 4274), False, 'import timeit, time\n'), ((4300, 4319), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (4317, 4319), False, 'import timeit, time\n'), ((4813, 4848), 'torch.cuda.synchronize', 'torch.cuda.synchronize', (['opts.gpu_id'], {}), '(opts.gpu_id)\n', (4835, 4848), False, 'import torch\n'), ((6277, 6304), 'json.load', 'json.load', (['annotations_file'], {}), '(annotations_file)\n', (6286, 6304), False, 'import json\n'), ((4635, 4650), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (4648, 4650), False, 'import torch\n'), ((4677, 4766), 'tool.torch_utils.do_detect', 'do_detect', (['model', 'input', '(0.2)', '(0.4)'], {'use_cuda': '(not opts.no_cuda)', 'gpu_number': 'opts.gpu_id'}), '(model, input, 0.2, 0.4, use_cuda=not opts.no_cuda, gpu_number=\n opts.gpu_id)\n', (4686, 4766), False, 'from tool.torch_utils import do_detect\n'), ((2989, 3029), 'cv2.imencode', 'cv2.imencode', (['""".jpg"""', 'img', '_ENCODE_PARAM'], {}), "('.jpg', img, _ENCODE_PARAM)\n", (3001, 3029), False, 'import cv2\n'), ((4424, 4446), 'timeit.default_timer', 'timeit.default_timer', ([], {}), '()\n', (4444, 4446), False, 'import timeit, time\n'), ((4879, 4901), 'timeit.default_timer', 'timeit.default_timer', ([], {}), '()\n', (4899, 4901), False, 'import timeit, time\n'), ((4948, 4967), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (4965, 4967), False, 'import timeit, time\n')] |
import math
import os
import re
import itertools
import matplotlib.cbook as cbook
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.backends.backend_pdf import PdfPages
from matplotlib.font_manager import FontProperties
from scipy import stats
plot_markers = ('D', 'o', '^', 's', 'p', 'd', 'h', '8', r'$\lambda$', '_', '*', 'x',
'H', 'v', '<', '>', '1', '2', '3', '4', '.', '|', '+', ',',)
plot_linestyles = ('-', '--', '-.', ':')
# These are the "Tableau 20" colors as RGB.
# http://tableaufriction.blogspot.ro/2012/11/finally-you-can-use-tableau-data-colors.html
# http://www.randalolson.com/2014/06/28/how-to-make-beautiful-data-visualizations-in-python-with-matplotlib/
tableau20 = [(31, 119, 180), (174, 199, 232), (255, 127, 14), (148, 103, 189),
(44, 160, 44), (227, 119, 194), (214, 39, 40), (255, 152, 150),
(255, 187, 120), (197, 176, 213), (152, 223, 138), (196, 156, 148),
(140, 86, 75), (247, 182, 210), (127, 127, 127), (199, 199, 199),
(188, 189, 34), (219, 219, 141), (23, 190, 207), (158, 218, 229)]
# Scale the RGB values to the [0, 1] range, which is the format matplotlib accepts.
for i in range(len(tableau20)):
r, g, b = tableau20[i]
tableau20[i] = (r / 255., g / 255., b / 255.)
def cnv_ns_to_ms(ns):
return ns / 1000000.0
class Results:
ALGORITHM = 0
DOMAIN = 1
def __init__(self, parsedJson):
self.configuration = (parsedJson['experimentConfiguration']['algorithmName'],
parsedJson['experimentConfiguration']['domainName'])
self.generatedNodes = parsedJson['generatedNodes']
self.expandedNodes = parsedJson['expandedNodes']
self.actions = parsedJson['actions']
self.time = cnv_ns_to_ms(parsedJson['goalAchievementTime'])
def translate_algorithm_name(alg_name):
# Handle hat (^) names
if "HAT" in alg_name:
alg_name = re.sub(r"(.*)_(.*)_(HAT)(.*)", r"\1", alg_name) \
+ re.sub(r"(.*)_(.*)_(HAT)(.*)", r"_$\\hat{\2}$", alg_name).lower() \
+ re.sub(r"(.*)_(.*)_(HAT)(.*)", r"\4", alg_name)
# Specific word formatting
alg_name = alg_name.replace('DYNAMIC_MULTIPLE', 'DM')
alg_name = alg_name.replace('STATIC_MULTIPLE', 'SM')
alg_name = alg_name.replace('STATIC_SINGLE', 'SS')
alg_name = alg_name.replace('DYNAMIC', 'Dynamic')
alg_name = alg_name.replace('WEIGHTED', 'Weighted')
alg_name = alg_name.replace('STATIC', 'Static')
alg_name = alg_name.replace('MULTIPLE', 'Mutliple')
alg_name = alg_name.replace('SINGLE', 'Single')
alg_name = alg_name.replace('LSS_', 'LSS-')
# Handle star (*) names
alg_name = alg_name.replace('_STAR', '*')
# Replace rest of underscores
alg_name = alg_name.replace('_', ' ')
return alg_name
def translate_domain_name(domain_name):
if domain_name is "POINT_ROBOT_WITH_INERTIA":
return "Double Integrator"
# Replace underscores
domain_name = domain_name.replace('_', ' ')
# Convert case
domain_name = domain_name.title()
return domain_name
def translate_instance_name(instance_name, domain):
if domain == "ACROBOT":
return instance_name
else:
# Strip path and extension
name = os.path.splitext(os.path.basename(instance_name))[0]
# Strip ending numbers
if re.match(r'(.*)_[0-9]*', name):
name = name.split('_')[0]
# Convert casing and return
final = re.sub("([a-z])([A-Z])", "\g<1> \g<2>", name).title()
# Special replacements
if final == 'H':
final = 'HBox'
elif final == 'Barto-Big':
final = 'Barto Large'
return final
def translate_domain_instance_name(domain_name, instance_name):
return translate_domain_name(domain_name) + " - " + translate_instance_name(instance_name, domain_name)
def median_confidence_intervals(data):
if not data: # empty
return [0], [0], [0]
bxpstats = cbook.boxplot_stats(data)
confidence_intervals = [[], []]
medians = []
for stat in bxpstats:
confidence_intervals[0].append(stat['cilo'])
confidence_intervals[1].append(stat['cihi'])
medians.append(stat['med'])
confidence_intervals[0] = np.array(confidence_intervals[0])
confidence_intervals[1] = np.array(confidence_intervals[1])
return medians, medians - confidence_intervals[0], confidence_intervals[1] - medians
def mean_confidence_intervals(data):
if not data: # empty
return [0], [0], [0]
means = [np.mean(x) for x in data]
safe_means = np.nan_to_num(means)
std = np.nan_to_num([stats.sem(x) if len(x) > 1 else 0.0 for x in data])
confidence_intervals = stats.t.interval(0.95, len(data) - 1, loc=safe_means, scale=std)
confidence_intervals_low = np.array(
[mean if math.isnan(ci) else ci for mean, ci in zip(means, confidence_intervals[0])])
confidence_intervals_high = np.array(
[mean if math.isnan(ci) else ci for mean, ci in zip(means, confidence_intervals[1])])
return means, means - confidence_intervals_low, confidence_intervals_high - means
def save_plot(plot, filename, lgd=None):
basename, ext = os.path.splitext(filename)
if ext is '.pdf':
pp = PdfPages(filename)
if lgd:
plot.savefig(pp, format='pdf', bbox_inches='tight', bbox_extra_artists=(lgd,))
else:
plot.savefig(pp, format='pdf', bbox_inches='tight')
pp.close()
else:
# Try and save it
if lgd:
plot.savefig(filename, bbox_inches='tight', bbox_extra_artists=(lgd,))
else:
plot.savefig(filename, bbox_inches='tight')
def plot_gat_stacked_bars(data: dict, labels: list, title="", stats_type="median", log10=True):
if stats_type is not "median" and stats_type is not "mean":
print("invalid type passed to plotutils.plot_gat_stacked_bars (must be median or mean)")
return None
gat_name = "goalAchievementTime"
idle_name = "idlePlanningTime"
if gat_name not in data or idle_name not in data:
print("Missing data for plotutils.plot_gat_stacked_bars")
return None
y_gat = data[gat_name]
y_idle = data[idle_name]
if not y_gat: # empty
print("No data provided to plotutils.plot_gat_stacked_bars")
return
if len(y_gat) != len(y_idle):
print("WARNING: Uneven data passed to plotutils.plot_gat_stacked_bars")
x = np.arange(1, len(y_gat) + 1) + 0.1
if stats_type is "median":
gat_stats, gat_stats_confidence_interval_low, gat_stats_confidence_interval_high = \
median_confidence_intervals(y_gat)
idle_stats, idle_stats_confidence_interval_low, idle_stats_confidence_interval_high = \
median_confidence_intervals(y_idle)
else: # assured to be mean
gat_stats, gat_stats_confidence_interval_low, gat_stats_confidence_interval_high = \
mean_confidence_intervals(y_gat)
idle_stats, idle_stats_confidence_interval_low, idle_stats_confidence_interval_high = \
mean_confidence_intervals(y_idle)
width = 0.35
fig, ax = plt.subplots()
gat_bars = ax.bar(x, gat_stats, width, color=tableau20[0], ecolor=tableau20[5], capsize=2,
label="Goal Achievement Time", edgecolor='none',
yerr=(gat_stats_confidence_interval_low, gat_stats_confidence_interval_high))
init_bars = ax.bar(x, idle_stats, width, color=tableau20[1], ecolor=tableau20[3], capsize=2,
label="Idle Planning Time", edgecolor='none',
yerr=(idle_stats_confidence_interval_low, idle_stats_confidence_interval_high))
# Set labels
plt.title(title, fontsize=16)
if log10:
ax.set_yscale('symlog', basey=10)
# ax.set_yscale('log', nonposy='clip')
plt.ylabel("Time log10", fontsize=16)
else:
plt.ylabel("Time (ms)", fontsize=16)
plt.xlabel("Algorithms", fontsize=16)
ax.set_xticks(x + width / 2.)
ax.set_xticklabels(labels, fontsize=14)
ax.autoscale(tight=True)
fig.autofmt_xdate()
lgd = ax.legend(loc='best', frameon=False)
plt.gcf().tight_layout()
return lgd
def plot_node_count_bars(data, labels, title="", stats_type="median", log10=True):
if stats_type is not "median" and stats_type is not "mean":
print("invalid type passed to plotutils.plot_node_count_bars (must be median or mean)")
return None
generated_name = "generatedNodes"
expanded_name = "expandedNodes"
if generated_name not in data or expanded_name not in data:
print("Missing data for plotutils.plot_node_count_bars")
return None
y_generated = data[generated_name]
y_expanded = data[expanded_name]
if not y_generated: # empty
print("No data provided to plotutils.plot_node_count_bars")
return
if len(y_generated) != len(y_expanded):
print("WARNING: Uneven data passed to plotutils.plot_node_count_bars")
x = np.arange(1, len(y_generated) + 1)
if stats_type is "median":
generated_stats, generated_confidence_interval_low, generated_confidence_interval_high = \
median_confidence_intervals(y_generated)
expanded_stats, expanded_confidence_interval_low, expanded_confidence_interval_high = \
median_confidence_intervals(y_expanded)
else: # assured to be mean
generated_stats, generated_confidence_interval_low, generated_confidence_interval_high = \
mean_confidence_intervals(y_generated)
expanded_stats, expanded_confidence_interval_low, expanded_confidence_interval_high = \
mean_confidence_intervals(y_expanded)
width = 0.35
fig, ax = plt.subplots()
generated_count_bars = ax.bar(x, generated_stats, width, color=tableau20[4], ecolor=tableau20[2], capsize=2,
edgecolor='none',
yerr=(generated_confidence_interval_low, generated_confidence_interval_high))
expanded_count_bars = ax.bar(x + width, expanded_stats, width, color=tableau20[10], ecolor=tableau20[6], capsize=2,
edgecolor='none',
yerr=(expanded_confidence_interval_low, expanded_confidence_interval_high))
# Set labels
plt.title(title, fontsize=16)
plt.xlabel("Algorithms", fontsize=16)
if log10:
ax.set_yscale('symlog', basey=10)
plt.ylabel("Node Count log10", fontsize=16)
else:
plt.ylabel("Node Count", fontsize=16)
ax.set_xticks(x + width)
ax.set_xticklabels(labels, fontsize=14)
ax.autoscale(tight=True)
fig.autofmt_xdate()
lgd = ax.legend((generated_count_bars, expanded_count_bars), ('Expanded', 'Generated'), loc='best', frameon=False)
# Add numbers to top of bars
def autolabel(rects):
for rect in rects:
height = rect.get_height()
ax.text(rect.get_x() + rect.get_width() / 2., 1.0 * height, '%d' % int(height), ha='center', va='bottom')
# autolabel(med_bars)
# autolabel(mean_bars)
plt.gcf().tight_layout()
return lgd
def plot_gat_bars(data, labels, title=""):
y = data
if not y: # empty
print("No data provided to plotutils.plot_gat_boxplots")
return
x = np.arange(1, len(y) + 1)
med, med_confidence_interval_low, med_confidence_interval_high = median_confidence_intervals(y)
mean, mean_confidence_interval_low, mean_confidence_interval_high = mean_confidence_intervals(y)
width = 0.35
fig, ax = plt.subplots()
med_bars = ax.bar(x, med, width, color=tableau20[0], ecolor=tableau20[3], capsize=2,
yerr=(med_confidence_interval_low, med_confidence_interval_high))
mean_bars = ax.bar(x + width, mean, width, color=tableau20[1], ecolor=tableau20[3], capsize=2,
yerr=(mean_confidence_interval_low, mean_confidence_interval_high))
# Set labels
plt.title(title)
plt.ylabel("Goal Achievement Time (ms)")
plt.xlabel("Algorithms")
ax.set_xticks(x + width)
ax.set_xticklabels(labels)
fig.autofmt_xdate()
lgd = ax.legend((med_bars, mean_bars), ('Median', 'Mean'), loc='best', frameon=False)
ax.autoscale(tight=True)
# Set ylims so we aren't at the top of the graph space for even data
# low = min(min(y))
# high = max(max(y))
# plt.ylim([math.ceil(low - 0.5 * (high - low)), math.ceil(high + 0.5 * (high - low))])
# Add numbers to top of bars
def autolabel(rects):
for rect in rects:
height = rect.get_height()
ax.text(rect.get_x() + rect.get_width() / 2., 1.0 * height, '%d' % int(height), ha='center', va='bottom')
# autolabel(med_bars)
# autolabel(mean_bars)
plt.gcf().tight_layout()
return lgd
def plot_gat_boxplots(data, labels, title="", showviolin=False):
y = data
if not y: # empty
print("No data provided to plotutils.plot_gat_boxplots")
return
med, confidence_interval_low, confidence_interval_high = median_confidence_intervals(y)
fig, ax = plt.subplots()
plt.boxplot(y, notch=False, labels=labels)
# Plot separate error bars without line to show median confidence intervals
x = np.arange(1, len(y) + 1)
plt.errorbar(x, med, yerr=(confidence_interval_low, confidence_interval_high), fmt='none',
linewidth=3)
if showviolin:
mean, mean_confidence_interval_low, mean_confidence_interval_high = mean_confidence_intervals(y)
plt.violinplot(y, showmeans=True, showmedians=True)
plt.errorbar(x, mean, yerr=(mean_confidence_interval_low, mean_confidence_interval_high), fmt='none',
linewidth=3, color='g')
plt.title(title)
plt.ylabel("Goal Achievement Time (ms)")
plt.xlabel("Algorithms")
fig.autofmt_xdate()
ax.autoscale(tight=True)
# ymin, ymax = plt.ylim()
# plt.ylim(ymin - 0.1, ymax + 0.1)
plt.gcf().tight_layout()
return None
def array_is_all_zero(arr):
is_all_zero = True
for val in arr:
if val != 0:
is_all_zero = False
break
return is_all_zero
# TODO add factor A*
def plot_gat_duration_error(data_dict, astar_data, action_durations, title="", log10=True):
markers = itertools.cycle(plot_markers)
linestyles = itertools.cycle(plot_linestyles)
handles = []
astar_gat_per_duration = astar_data
if not astar_gat_per_duration: # empty
print("No data for A*")
# astar_gat_per_duration_means, astar_confidence_interval_low, astar_confidence_interval_high = \
# mean_confidence_intervals(astar_gat_per_duration)
x = np.arange(1, len(action_durations) + 1)
fig = plt.figure()
ax = plt.subplot()
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.tick_params(direction='out')
ax.get_xaxis().tick_bottom()
ax.get_yaxis().tick_left()
# Plot for each provided algorithm
color_index = 0
for algorithm, algorithm_gat_per_duration in data_dict.items():
if not algorithm_gat_per_duration: # empty
print("No data for " + algorithm)
continue
# print(algorithm_gat_per_duration)
# if log10:
# algorithm_gat_per_duration = [np.log10(gat) for gat in algorithm_gat_per_duration]
algorithm_gat_per_duration_mean, algorithm_confidence_interval_low, algorithm_confidence_interval_high = \
mean_confidence_intervals(algorithm_gat_per_duration)
data_mask = np.isfinite(algorithm_gat_per_duration_mean)
masked_x = x[data_mask]
masked_data = np.array(algorithm_gat_per_duration_mean)[data_mask]
masked_confidence_low = algorithm_confidence_interval_low[data_mask]
masked_confidence_high = algorithm_confidence_interval_high[data_mask]
label = translate_algorithm_name(algorithm)
handle = plt.errorbar(masked_x, masked_data, label=label, color=tableau20[color_index], markeredgecolor='none',
linestyle=next(linestyles), marker=next(markers), clip_on=False,
yerr=(masked_confidence_low, masked_confidence_high))
handles.append((handle, label, masked_data.tolist()))
color_index += 1
# Set labels, sort legend by mean value
handles = sorted(handles, key=lambda handle: handle[2], reverse=True)
ordered_handles = [a[0] for a in handles]
ordered_labels = [a[1] for a in handles]
font_properties = FontProperties()
font_properties.set_size('small')
lgd = plt.legend(handles=ordered_handles, labels=ordered_labels, prop=font_properties, ncol=2, frameon=False,
# loc="upper center",bbox_to_anchor=(0.5, -0.1)
loc='best'
)
plt.xticks(x, [duration if duration - int(duration) > 0 else int(duration) for duration in action_durations])
plt.title(title)
if log10:
plt.yscale('symlog', basey=10)
# plt.yscale('log', basey=10, nonposy='clip')
plt.ylabel("Goal Achievement Time log10")
else:
plt.ylabel("Goal Achievement Time (ms)")
plt.xlabel("Action Duration (ms)")
ax.autoscale(tight=True)
plt.gcf().tight_layout()
return lgd
| [
"matplotlib.pyplot.boxplot",
"matplotlib.pyplot.ylabel",
"matplotlib.cbook.boxplot_stats",
"numpy.array",
"numpy.isfinite",
"scipy.stats.sem",
"matplotlib.pyplot.errorbar",
"numpy.mean",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.yscale",
"itertools.cycle",
"matplotlib.pyplot.gcf",
"os.p... | [((4032, 4057), 'matplotlib.cbook.boxplot_stats', 'cbook.boxplot_stats', (['data'], {}), '(data)\n', (4051, 4057), True, 'import matplotlib.cbook as cbook\n'), ((4309, 4342), 'numpy.array', 'np.array', (['confidence_intervals[0]'], {}), '(confidence_intervals[0])\n', (4317, 4342), True, 'import numpy as np\n'), ((4373, 4406), 'numpy.array', 'np.array', (['confidence_intervals[1]'], {}), '(confidence_intervals[1])\n', (4381, 4406), True, 'import numpy as np\n'), ((4647, 4667), 'numpy.nan_to_num', 'np.nan_to_num', (['means'], {}), '(means)\n', (4660, 4667), True, 'import numpy as np\n'), ((5258, 5284), 'os.path.splitext', 'os.path.splitext', (['filename'], {}), '(filename)\n', (5274, 5284), False, 'import os\n'), ((7227, 7241), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (7239, 7241), True, 'import matplotlib.pyplot as plt\n'), ((7800, 7829), 'matplotlib.pyplot.title', 'plt.title', (['title'], {'fontsize': '(16)'}), '(title, fontsize=16)\n', (7809, 7829), True, 'import matplotlib.pyplot as plt\n'), ((8038, 8075), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Algorithms"""'], {'fontsize': '(16)'}), "('Algorithms', fontsize=16)\n", (8048, 8075), True, 'import matplotlib.pyplot as plt\n'), ((9844, 9858), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (9856, 9858), True, 'import matplotlib.pyplot as plt\n'), ((10438, 10467), 'matplotlib.pyplot.title', 'plt.title', (['title'], {'fontsize': '(16)'}), '(title, fontsize=16)\n', (10447, 10467), True, 'import matplotlib.pyplot as plt\n'), ((10472, 10509), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Algorithms"""'], {'fontsize': '(16)'}), "('Algorithms', fontsize=16)\n", (10482, 10509), True, 'import matplotlib.pyplot as plt\n'), ((11689, 11703), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (11701, 11703), True, 'import matplotlib.pyplot as plt\n'), ((12093, 12109), 'matplotlib.pyplot.title', 'plt.title', (['title'], {}), '(title)\n', (12102, 12109), True, 'import matplotlib.pyplot as plt\n'), ((12114, 12154), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Goal Achievement Time (ms)"""'], {}), "('Goal Achievement Time (ms)')\n", (12124, 12154), True, 'import matplotlib.pyplot as plt\n'), ((12159, 12183), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Algorithms"""'], {}), "('Algorithms')\n", (12169, 12183), True, 'import matplotlib.pyplot as plt\n'), ((13236, 13250), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (13248, 13250), True, 'import matplotlib.pyplot as plt\n'), ((13255, 13297), 'matplotlib.pyplot.boxplot', 'plt.boxplot', (['y'], {'notch': '(False)', 'labels': 'labels'}), '(y, notch=False, labels=labels)\n', (13266, 13297), True, 'import matplotlib.pyplot as plt\n'), ((13415, 13522), 'matplotlib.pyplot.errorbar', 'plt.errorbar', (['x', 'med'], {'yerr': '(confidence_interval_low, confidence_interval_high)', 'fmt': '"""none"""', 'linewidth': '(3)'}), "(x, med, yerr=(confidence_interval_low,\n confidence_interval_high), fmt='none', linewidth=3)\n", (13427, 13522), True, 'import matplotlib.pyplot as plt\n'), ((13881, 13897), 'matplotlib.pyplot.title', 'plt.title', (['title'], {}), '(title)\n', (13890, 13897), True, 'import matplotlib.pyplot as plt\n'), ((13902, 13942), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Goal Achievement Time (ms)"""'], {}), "('Goal Achievement Time (ms)')\n", (13912, 13942), True, 'import matplotlib.pyplot as plt\n'), ((13947, 13971), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Algorithms"""'], {}), "('Algorithms')\n", (13957, 13971), True, 'import matplotlib.pyplot as plt\n'), ((14437, 14466), 'itertools.cycle', 'itertools.cycle', (['plot_markers'], {}), '(plot_markers)\n', (14452, 14466), False, 'import itertools\n'), ((14484, 14516), 'itertools.cycle', 'itertools.cycle', (['plot_linestyles'], {}), '(plot_linestyles)\n', (14499, 14516), False, 'import itertools\n'), ((14872, 14884), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (14882, 14884), True, 'import matplotlib.pyplot as plt\n'), ((14894, 14907), 'matplotlib.pyplot.subplot', 'plt.subplot', ([], {}), '()\n', (14905, 14907), True, 'import matplotlib.pyplot as plt\n'), ((16679, 16695), 'matplotlib.font_manager.FontProperties', 'FontProperties', ([], {}), '()\n', (16693, 16695), False, 'from matplotlib.font_manager import FontProperties\n'), ((16744, 16864), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'handles': 'ordered_handles', 'labels': 'ordered_labels', 'prop': 'font_properties', 'ncol': '(2)', 'frameon': '(False)', 'loc': '"""best"""'}), "(handles=ordered_handles, labels=ordered_labels, prop=\n font_properties, ncol=2, frameon=False, loc='best')\n", (16754, 16864), True, 'import matplotlib.pyplot as plt\n'), ((17090, 17106), 'matplotlib.pyplot.title', 'plt.title', (['title'], {}), '(title)\n', (17099, 17106), True, 'import matplotlib.pyplot as plt\n'), ((17327, 17361), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Action Duration (ms)"""'], {}), "('Action Duration (ms)')\n", (17337, 17361), True, 'import matplotlib.pyplot as plt\n'), ((3395, 3424), 're.match', 're.match', (['"""(.*)_[0-9]*"""', 'name'], {}), "('(.*)_[0-9]*', name)\n", (3403, 3424), False, 'import re\n'), ((4604, 4614), 'numpy.mean', 'np.mean', (['x'], {}), '(x)\n', (4611, 4614), True, 'import numpy as np\n'), ((5320, 5338), 'matplotlib.backends.backend_pdf.PdfPages', 'PdfPages', (['filename'], {}), '(filename)\n', (5328, 5338), False, 'from matplotlib.backends.backend_pdf import PdfPages\n'), ((7941, 7978), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Time log10"""'], {'fontsize': '(16)'}), "('Time log10', fontsize=16)\n", (7951, 7978), True, 'import matplotlib.pyplot as plt\n'), ((7997, 8033), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Time (ms)"""'], {'fontsize': '(16)'}), "('Time (ms)', fontsize=16)\n", (8007, 8033), True, 'import matplotlib.pyplot as plt\n'), ((10574, 10617), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Node Count log10"""'], {'fontsize': '(16)'}), "('Node Count log10', fontsize=16)\n", (10584, 10617), True, 'import matplotlib.pyplot as plt\n'), ((10636, 10673), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Node Count"""'], {'fontsize': '(16)'}), "('Node Count', fontsize=16)\n", (10646, 10673), True, 'import matplotlib.pyplot as plt\n'), ((13669, 13720), 'matplotlib.pyplot.violinplot', 'plt.violinplot', (['y'], {'showmeans': '(True)', 'showmedians': '(True)'}), '(y, showmeans=True, showmedians=True)\n', (13683, 13720), True, 'import matplotlib.pyplot as plt\n'), ((13729, 13858), 'matplotlib.pyplot.errorbar', 'plt.errorbar', (['x', 'mean'], {'yerr': '(mean_confidence_interval_low, mean_confidence_interval_high)', 'fmt': '"""none"""', 'linewidth': '(3)', 'color': '"""g"""'}), "(x, mean, yerr=(mean_confidence_interval_low,\n mean_confidence_interval_high), fmt='none', linewidth=3, color='g')\n", (13741, 13858), True, 'import matplotlib.pyplot as plt\n'), ((15699, 15743), 'numpy.isfinite', 'np.isfinite', (['algorithm_gat_per_duration_mean'], {}), '(algorithm_gat_per_duration_mean)\n', (15710, 15743), True, 'import numpy as np\n'), ((17129, 17159), 'matplotlib.pyplot.yscale', 'plt.yscale', (['"""symlog"""'], {'basey': '(10)'}), "('symlog', basey=10)\n", (17139, 17159), True, 'import matplotlib.pyplot as plt\n'), ((17222, 17263), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Goal Achievement Time log10"""'], {}), "('Goal Achievement Time log10')\n", (17232, 17263), True, 'import matplotlib.pyplot as plt\n'), ((17282, 17322), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Goal Achievement Time (ms)"""'], {}), "('Goal Achievement Time (ms)')\n", (17292, 17322), True, 'import matplotlib.pyplot as plt\n'), ((2109, 2155), 're.sub', 're.sub', (['"""(.*)_(.*)_(HAT)(.*)"""', '"""\\\\4"""', 'alg_name'], {}), "('(.*)_(.*)_(HAT)(.*)', '\\\\4', alg_name)\n", (2115, 2155), False, 'import re\n'), ((8259, 8268), 'matplotlib.pyplot.gcf', 'plt.gcf', ([], {}), '()\n', (8266, 8268), True, 'import matplotlib.pyplot as plt\n'), ((11221, 11230), 'matplotlib.pyplot.gcf', 'plt.gcf', ([], {}), '()\n', (11228, 11230), True, 'import matplotlib.pyplot as plt\n'), ((12905, 12914), 'matplotlib.pyplot.gcf', 'plt.gcf', ([], {}), '()\n', (12912, 12914), True, 'import matplotlib.pyplot as plt\n'), ((14099, 14108), 'matplotlib.pyplot.gcf', 'plt.gcf', ([], {}), '()\n', (14106, 14108), True, 'import matplotlib.pyplot as plt\n'), ((15799, 15840), 'numpy.array', 'np.array', (['algorithm_gat_per_duration_mean'], {}), '(algorithm_gat_per_duration_mean)\n', (15807, 15840), True, 'import numpy as np\n'), ((17396, 17405), 'matplotlib.pyplot.gcf', 'plt.gcf', ([], {}), '()\n', (17403, 17405), True, 'import matplotlib.pyplot as plt\n'), ((1949, 1995), 're.sub', 're.sub', (['"""(.*)_(.*)_(HAT)(.*)"""', '"""\\\\1"""', 'alg_name'], {}), "('(.*)_(.*)_(HAT)(.*)', '\\\\1', alg_name)\n", (1955, 1995), False, 'import re\n'), ((3316, 3347), 'os.path.basename', 'os.path.basename', (['instance_name'], {}), '(instance_name)\n', (3332, 3347), False, 'import os\n'), ((3518, 3565), 're.sub', 're.sub', (['"""([a-z])([A-Z])"""', '"""\\\\g<1> \\\\g<2>"""', 'name'], {}), "('([a-z])([A-Z])', '\\\\g<1> \\\\g<2>', name)\n", (3524, 3565), False, 'import re\n'), ((4694, 4706), 'scipy.stats.sem', 'stats.sem', (['x'], {}), '(x)\n', (4703, 4706), False, 'from scipy import stats\n'), ((4896, 4910), 'math.isnan', 'math.isnan', (['ci'], {}), '(ci)\n', (4906, 4910), False, 'import math\n'), ((5032, 5046), 'math.isnan', 'math.isnan', (['ci'], {}), '(ci)\n', (5042, 5046), False, 'import math\n'), ((2020, 2078), 're.sub', 're.sub', (['"""(.*)_(.*)_(HAT)(.*)"""', '"""_$\\\\\\\\hat{\\\\2}$"""', 'alg_name'], {}), "('(.*)_(.*)_(HAT)(.*)', '_$\\\\\\\\hat{\\\\2}$', alg_name)\n", (2026, 2078), False, 'import re\n')] |
from job.nclimber import NClimber
from math import ceil
from multiprocessing.context import Process
from behavior.oscillator import Oscillator
from multiprocessing import Pool
from util.run import Run
from numpy import floor
import wandb
from job.learner import Learner
from rl_ctrnn.ctrnn import Ctrnn
import itertools
import random
import numpy as np
THREAD_COUNT = 10
WALL_TIMES = [120, 360, 1200]
SEEDS = [random.randint(100000, 999999) for _ in range(50)]
PROGENITORS = [
Ctrnn.from_dict(
{
"time_constants": {0: 1.0, 1: 1.0},
"biases": {0: 5.154455202973727, 1: -10.756384207938911},
"weights": {
0: {0: 5.352730101212875, 1: 16.0},
1: {0: -11.915400080418113, 1: 2.7717190607157542},
},
}
)
]
def init_run(job, wall_time, progenitor, seed) -> Run:
return wandb.init(
project="2021-08-19",
group=str(wall_time),
job_type=job,
config={"wall_time": wall_time, "progenitor": progenitor, "seed": seed},
)
def get_frozen(ctrnn: Ctrnn) -> float:
voltages = ctrnn.make_instance()
behavior = Oscillator(dt=0.01, size=ctrnn.size, duration=10, window=10)
behavior.setup(ctrnn.get_output(voltages))
while behavior.time < behavior.duration:
voltages = ctrnn.step(0.01, voltages)
behavior.grade(ctrnn.get_output(voltages))
return behavior.fitness
def calculate_displacement(a: np.ndarray, b: np.ndarray) -> float:
return np.sqrt(np.sum(np.power(a + -b, 2)))
def hill_climber(wall_time, ctrnn, seed):
run = init_run("hill_climber", wall_time, ctrnn, seed)
m = NClimber(ctrnn, seed, mutation=0.15)
m.setup()
time = 0
distance = 0
data = {
"Time": time,
"fitness": m.attempts[m.best][1],
"distance": 0,
"displacement": 0,
}
for y in range(ctrnn.size):
for x in range(ctrnn.size):
data[f"weight.{x}.{y}"] = ctrnn.weights[x, y]
run.log(data)
a: np.ndarray = m.attempts[0][0].weights
b: np.ndarray = m.attempts[0][0].weights
while time < wall_time:
m.single_step()
b = m.attempts[m.best][0].weights
distance += calculate_displacement(a, b)
a = b
time += int(m.duration * m.samples)
data = {
"Time": time,
"fitness": m.attempts[m.best][1],
"distance": distance,
"displacement": calculate_displacement(ctrnn.weights, b),
}
c = m.attempts[m.best][0]
for y in range(c.size):
for x in range(c.size):
data[f"weight.{x}.{y}"] = c.weights[x, y]
run.log(data)
run.finish()
def reinforcement_learner(wall_time, ctrnn, seed):
run = init_run("rl_learner", wall_time, ctrnn, seed)
m = Learner(ctrnn, seed)
m.behavior.dt = 0.01
m.behavior.duration = wall_time
m.behavior.window = 10
time = -1
while m.behavior.time < m.behavior.duration:
m.iter()
if time != (t := floor(m.behavior.time)): # possible rename `t` to `time`
if t % int(wall_time / 120):
continue
time = t
data = {"Time": t}
data["fitness"] = get_frozen(m.rlctrnn.ctrnn) # m.behavior.fitness
data["distance"] = m.rlctrnn.distance
data["displacement"] = m.calculate_displacement()
for y in range(m.rlctrnn.ctrnn.size):
for x in range(m.rlctrnn.ctrnn.size):
data[f"weight.{x}.{y}"] = m.rlctrnn.center[x, y]
run.log(data)
# run.summary["fitness"] = get_frozen(m.rlctrnn.ctrnn)
run.finish()
if __name__ == "__main__":
def c(args):
print(args)
args[0](*args[1:])
# methods = [random_walker, hill_climber, reinforcement_learner]
args = itertools.product(
[reinforcement_learner, hill_climber], WALL_TIMES, PROGENITORS, SEEDS
)
# p = Pool(2)
# p.map(c, list(args))
args = list(args)
num_threads = ceil(len(args) / THREAD_COUNT)
groups = [args[i::num_threads] for i in range(num_threads)]
for group in groups:
threads = []
for g in group:
threads.append(Process(target=c, args=(g,)))
for _, p in enumerate(threads):
p.start()
for _, p in enumerate(threads):
p.join()
| [
"job.learner.Learner",
"numpy.power",
"itertools.product",
"numpy.floor",
"behavior.oscillator.Oscillator",
"rl_ctrnn.ctrnn.Ctrnn.from_dict",
"multiprocessing.context.Process",
"job.nclimber.NClimber",
"random.randint"
] | [((412, 442), 'random.randint', 'random.randint', (['(100000)', '(999999)'], {}), '(100000, 999999)\n', (426, 442), False, 'import random\n'), ((483, 730), 'rl_ctrnn.ctrnn.Ctrnn.from_dict', 'Ctrnn.from_dict', (["{'time_constants': {(0): 1.0, (1): 1.0}, 'biases': {(0): 5.154455202973727,\n (1): -10.756384207938911}, 'weights': {(0): {(0): 5.352730101212875, (1\n ): 16.0}, (1): {(0): -11.915400080418113, (1): 2.7717190607157542}}}"], {}), "({'time_constants': {(0): 1.0, (1): 1.0}, 'biases': {(0): \n 5.154455202973727, (1): -10.756384207938911}, 'weights': {(0): {(0): \n 5.352730101212875, (1): 16.0}, (1): {(0): -11.915400080418113, (1): \n 2.7717190607157542}}})\n", (498, 730), False, 'from rl_ctrnn.ctrnn import Ctrnn\n'), ((1148, 1208), 'behavior.oscillator.Oscillator', 'Oscillator', ([], {'dt': '(0.01)', 'size': 'ctrnn.size', 'duration': '(10)', 'window': '(10)'}), '(dt=0.01, size=ctrnn.size, duration=10, window=10)\n', (1158, 1208), False, 'from behavior.oscillator import Oscillator\n'), ((1655, 1691), 'job.nclimber.NClimber', 'NClimber', (['ctrnn', 'seed'], {'mutation': '(0.15)'}), '(ctrnn, seed, mutation=0.15)\n', (1663, 1691), False, 'from job.nclimber import NClimber\n'), ((2827, 2847), 'job.learner.Learner', 'Learner', (['ctrnn', 'seed'], {}), '(ctrnn, seed)\n', (2834, 2847), False, 'from job.learner import Learner\n'), ((3861, 3953), 'itertools.product', 'itertools.product', (['[reinforcement_learner, hill_climber]', 'WALL_TIMES', 'PROGENITORS', 'SEEDS'], {}), '([reinforcement_learner, hill_climber], WALL_TIMES,\n PROGENITORS, SEEDS)\n', (3878, 3953), False, 'import itertools\n'), ((1521, 1540), 'numpy.power', 'np.power', (['(a + -b)', '(2)'], {}), '(a + -b, 2)\n', (1529, 1540), True, 'import numpy as np\n'), ((3042, 3064), 'numpy.floor', 'floor', (['m.behavior.time'], {}), '(m.behavior.time)\n', (3047, 3064), False, 'from numpy import floor\n'), ((4241, 4269), 'multiprocessing.context.Process', 'Process', ([], {'target': 'c', 'args': '(g,)'}), '(target=c, args=(g,))\n', (4248, 4269), False, 'from multiprocessing.context import Process\n')] |
# Copyright (c) 2020, TU Wien, Department of Geodesy and Geoinformation
# 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 TU Wien, Department of Geodesy and Geoinformation
# 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 AND CONTRIBUTORS "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 TU WIEN DEPARTMENT OF GEODESY AND
# GEOINFORMATION 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.
"""
Tests for level 1 reader.
"""
import numpy as np
import numpy.testing as nptest
import unittest
import os
from datetime import datetime
import ascat.level1 as level1
float32_nan = np.finfo(np.float32).min
class Test_AscatL1Image(unittest.TestCase):
def setUp(self):
data_path = os.path.join(
os.path.dirname(__file__), 'ascat_test_data', 'eumetsat',
'ASCAT_generic_reader_data')
name_b = os.path.join(data_path, 'bufr',
'M02-ASCA-ASCSZR1B0200-NA-9.1-20100609013900.000000000Z-20130824233100-1280350.bfr')
name_e = os.path.join(data_path, 'eps_nat',
'ASCA_SZR_1B_M02_20100609013900Z_20100609032058Z_R_O_20130824233100Z.nat')
name_n = os.path.join(data_path, 'nc',
'W_XX-EUMETSAT-Darmstadt,SURFACE+SATELLITE,METOPA+ASCAT_C_EUMP_20100609013900_18872_eps_o_125_l1.nc')
name_e11 = os.path.join(data_path, 'eps_nat',
'ASCA_SZR_1B_M02_20071212071500Z_20071212085659Z_R_O_20081225063118Z.nat')
name_e_szf = os.path.join(data_path, 'eps_nat',
'ASCA_SZF_1B_M01_20180611041800Z_20180611055959Z_N_O_20180611050637Z.nat')
name_h = os.path.join(data_path, 'hdf5',
'ASCA_SZF_1B_M01_20180611041800Z_20180611055959Z_N_O_20180611050637Z.h5')
self.image_bufr = level1.AscatL1Image(name_b)
self.image_eps = level1.AscatL1Image(name_e)
self.image_nc = level1.AscatL1Image(name_n)
self.image_eps_fmv11 = level1.AscatL1Image(name_e11)
self.image_e_szf = level1.AscatL1Image(name_e_szf)
self.image_h5_szf = level1.AscatL1Image(name_h)
def tearDown(self):
self.image_nc = None
self.image_bufr = None
self.image_eps = None
self.image_eps_fmv11 = None
self.image_eps_szf = None
self.image_h5_szf = None
def test_image_reading_szx_all_formats(self):
self.reader_bufr = self.image_bufr.read()
self.reader_eps = self.image_eps.read()
self.reader_nc = self.image_nc.read()
nptest.assert_allclose(self.reader_bufr.lat, self.reader_eps.lat,
atol=1e-4)
nptest.assert_allclose(self.reader_eps.lat, self.reader_nc.lat,
atol=1e-4)
nptest.assert_allclose(self.reader_nc.lat, self.reader_bufr.lat,
atol=1e-4)
nptest.assert_allclose(self.reader_bufr.lon, self.reader_eps.lon,
atol=1e-4)
nptest.assert_allclose(self.reader_eps.lon, self.reader_nc.lon,
atol=1e-4)
nptest.assert_allclose(self.reader_nc.lon, self.reader_bufr.lon,
atol=1e-4)
matching = ['jd', 'sat_id', 'abs_line_nr', 'abs_orbit_nr', 'node_num',
'line_num', 'as_des_pass', 'swath', 'azif', 'azim', 'azia',
'incf', 'incm', 'inca', 'sigf', 'sigm', 'siga', 'kpf',
'kpm', 'kpa', 'kpf_quality', 'kpm_quality', 'kpa_quality',
'land_flagf', 'land_flagm', 'land_flaga', 'usable_flagf',
'usable_flagm', 'usable_flaga']
# lists with no data fields or different definition
bufr_none = ['abs_line_nr', 'abs_orbit_nr', 'as_des_pass']
sig = ['sigf', 'sigm', 'siga']
# BUFR files contain less accurate data so we only compare to one 0.1
# accuracy.
for field in matching:
if field not in bufr_none:
# BUFR filters sigma values below -50 dB so for comparison we
# have to mask those values in nc and eps
if field in sig:
sig_mask = (self.reader_eps.data[field] < -50)
self.reader_eps.data[field][sig_mask] = float32_nan
self.reader_nc.data[field][sig_mask] = float32_nan
self.reader_bufr.data[field][sig_mask] = float32_nan
nan_mask = (self.reader_nc.data[field] == float32_nan)
self.reader_eps.data[field][nan_mask] = float32_nan
self.reader_bufr.data[field][nan_mask] = float32_nan
nptest.assert_allclose(self.reader_bufr.data[field],
self.reader_eps.data[field], atol=0.1)
nptest.assert_allclose(self.reader_nc.data[field],
self.reader_bufr.data[field], atol=0.1)
nptest.assert_allclose(self.reader_eps.data[field],
self.reader_nc.data[field], atol=0.1)
def test_image_reading_szf_all_formats(self):
self.reader_eps_szf = self.image_e_szf.read()
self.reader_hdf5_szf = self.image_h5_szf.read()
for szf_img in self.reader_eps_szf:
nptest.assert_allclose(self.reader_eps_szf[szf_img].lat,
self.reader_hdf5_szf[szf_img].lat,
atol=1e-4)
nptest.assert_allclose(self.reader_eps_szf[szf_img].lon,
self.reader_hdf5_szf[szf_img].lon,
atol=1e-4)
matching = ['jd', 'sat_id', 'beam_number', 'abs_orbit_nr',
'as_des_pass', 'azi', 'inc', 'sig', 'land_frac',
'flagfield_rf1', 'flagfield_rf2', 'flagfield_pl',
'flagfield_gen1', 'flagfield_gen2',
'land_flag', 'usable_flag']
for field in matching:
nptest.assert_allclose(
self.reader_eps_szf[szf_img].data[field],
self.reader_hdf5_szf[szf_img].data[field], atol=0.1)
def test_image_reading_szx_eps(self):
self.reader = self.image_eps.read(file_format='.nat')
lat_should = np.array(
[68.91681, 69.005196, 69.09337, 69.18132, 69.26905, 69.35655,
69.443825, 69.53087, 69.61768, 69.704254, 69.79059, 69.87668,
69.962524, 70.04812, 70.13346, 70.218544, 70.303375, 70.38794,
70.47224, 70.55626, 70.640015, 70.723495, 70.806694, 70.88961,
70.97224])
lon_should = np.array(
[168.80144, 168.60977, 168.41656, 168.22179, 168.02544, 167.82748,
167.62794, 167.42676, 167.22394, 167.01947, 166.81332, 166.60548,
166.39592, 166.18465, 165.97163, 165.75685, 165.5403, 165.32195,
165.10178, 164.87979, 164.65594, 164.43024, 164.20264, 163.97314,
163.74171])
sig_should = np.array(
[-13.510671, -13.421737, -13.872492, -14.351357, -14.395881,
-14.382635, -14.860762, -16.108913, -17.354418, -18.86383,
-18.793966, -18.631758, -18.46626, -18.71435, -19.150038,
-19.315845, -19.79865, -19.845669, -19.892258, -20.138796,
-20.151554, -20.154343, -20.165552, -20.013523, -19.238102])
kp_should = np.array(
[0.0307, 0.032, 0.051, 0.0696, 0.0703, 0.0584, 0.045, 0.0464,
0.0615, 0.0477, 0.0323, 0.04, 0.0346, 0.0369, 0.0378, 0.0397,
0.0341, 0.0399, 0.0418, 0.0408, 0.0421, 0.0347, 0.0424, 0.0451,
0.0523])
jd_should = np.array(
[2455356.56875, 2455356.56875, 2455356.56875,
2455356.56875, 2455356.56875, 2455356.56875,
2455356.56875, 2455356.56877169, 2455356.56877169,
2455356.56877169])
nptest.assert_allclose(self.reader.lat[:25], lat_should, atol=1e-5)
nptest.assert_allclose(self.reader.lon[:25], lon_should, atol=1e-5)
nptest.assert_allclose(self.reader.data['sigf'][:25],
sig_should, atol=1e-5)
nptest.assert_allclose(self.reader.data['kpf'][:25],
kp_should, atol=1e-5)
nptest.assert_allclose(self.reader.data['jd'][75:85],
jd_should, atol=1e-5)
def test_image_reading_szx_eps_fmv11(self):
self.reader = self.image_eps_fmv11.read()
lat_should = np.array(
[61.849445, 61.916786, 61.983864, 62.050674, 62.11722, 62.183495,
62.2495, 62.315228, 62.380684, 62.44586, 62.51076, 62.57538,
62.63971, 62.70376, 62.76752, 62.830994, 62.894173, 62.95706,
63.019653, 63.081947, 63.143944, 63.205635, 63.267025, 63.32811,
63.388885])
lon_should = np.array(
[69.18133, 68.991295, 68.80043, 68.60872, 68.41617, 68.22277,
68.028534, 67.833435, 67.63749, 67.44069, 67.243034, 67.04452,
66.84513, 66.64489, 66.44378, 66.2418, 66.03894, 65.83522,
65.630615, 65.42514, 65.21878, 65.01154, 64.80342, 64.59441,
64.38452])
sig_should = np.array(
[-15.008125, -14.547356, -15.067405, -15.340037, -15.381483,
-15.085848, -14.620477, -14.200545, -13.873865, -13.29581,
-12.962119, -12.909232, -12.990307, -13.076723, -13.039384,
-13.010556, -13.238036, -13.045113, -12.981088, -13.003889,
-14.009461, -14.633162, -14.706434, -14.042056, -13.7074])
kp_should = np.array(
[0.052, 0.0417, 0.0462, 0.0264, 0.0308, 0.0296, 0.0363, 0.0348,
0.0377, 0.036, 0.0329, 0.0258, 0.0296, 0.0245, 0.0275, 0.0309,
0.035, 0.0325, 0.0288, 0.0292, 0.0431, 0.0363, 0.0435, 0.0282,
0.0309])
jd_should = np.array(
[2454446.80208333, 2454446.80208333, 2454446.80208333,
2454446.80208333, 2454446.80208333, 2454446.80208333,
2454446.80208333, 2454446.80210505, 2454446.80210505,
2454446.80210505])
nptest.assert_allclose(self.reader.lat[:25], lat_should, atol=1e-5)
nptest.assert_allclose(self.reader.lon[:25], lon_should, atol=1e-5)
nptest.assert_allclose(self.reader.data['sigf'][:25],
sig_should, atol=1e-5)
nptest.assert_allclose(self.reader.data['kpf'][:25],
kp_should, atol=1e-5)
nptest.assert_allclose(self.reader.data['jd'][75:85],
jd_should, atol=1e-5)
def test_image_reading_szf_eps(self):
self.reader = self.image_e_szf.read()
lat_should = np.array(
[64.45502, 64.42318, 64.39127, 64.35929, 64.32724, 64.29512,
64.262924, 64.23065, 64.19831, 64.16589, 64.1334, 64.10083,
64.06819, 64.03547, 64.00268, 63.969807, 63.936855, 63.903828,
63.870724, 63.837536, 63.804276, 63.77093, 63.737507, 63.704002,
63.67042])
lon_should = np.array(
[103.29956, 103.32185, 103.34413, 103.36641, 103.38869,
103.41095, 103.43322, 103.45548, 103.47774, 103.49999,
103.52224, 103.54449, 103.566734, 103.588974, 103.61121,
103.63345, 103.655685, 103.67792, 103.70014, 103.722374,
103.7446, 103.76682, 103.78904, 103.811264, 103.83348])
sig_should = np.array(
[-9.713457, -8.768949, -9.294478, -7.449275, -8.939872,
-7.893198, -8.570546, -8.934691, -7.851117, -7.782818,
-8.33993, -7.539894, -7.833797, -8.465893, -8.244121,
-7.59996, -8.976448, -9.36595, -10.800382, -8.289896,
-9.127579, -9.410345, -7.238986, -8.335969, -7.897769])
jd_should = np.array(
[2458280.67917396, 2458280.67917396, 2458280.67918378,
2458280.67918378, 2458280.67918378, 2458280.67918378,
2458280.67918378, 2458280.67918378, 2458280.67918378,
2458280.67918378])
nptest.assert_allclose(self.reader['img1'].lat[:25],
lat_should, atol=1e-5)
nptest.assert_allclose(self.reader['img1'].lon[:25],
lon_should, atol=1e-5)
nptest.assert_allclose(self.reader['img1'].data['sig'][:25],
sig_should, atol=1e-5)
nptest.assert_allclose(self.reader['img1'].data['jd'][190:200],
jd_should, atol=1e-5)
class Test_AscatL1Bufr(unittest.TestCase):
def setUp(self):
self.data_path = os.path.join(
os.path.dirname(__file__), 'ascat_test_data', 'eumetsat',
'ASCAT_generic_reader_data', 'bufr')
self.image_bufr = level1.AscatL1Bufr(self.data_path, eo_portal=True)
def tearDown(self):
self.image_bufr = None
def test_image_reading(self):
data, meta, timestamp, lon, lat, time_var = self.image_bufr.read(
datetime(2010, 6, 9, 1, 39))
assert lon.shape == (267648,)
assert lat.shape == (267648,)
def test_get_orbit_start_date(self):
filename = os.path.join(self.data_path,
'M02-ASCA-ASCSZR1B0200-NA-9.1-20100609013900.000000000Z-20130824233100-1280350.bfr')
orbit_start = self.image_bufr._get_orbit_start_date(filename)
orbit_start_should = datetime(2010, 6, 9, 1, 39)
assert orbit_start == orbit_start_should
def test_tstamp_for_daterange(self):
tstamps = self.image_bufr.tstamps_for_daterange(datetime(2010, 6, 8),
datetime(2010, 6, 10))
tstamps_should = [datetime(2010, 6, 9, 1, 39)]
assert tstamps == tstamps_should
class Test_AscatL1Eps(unittest.TestCase):
def setUp(self):
self.data_path = os.path.join(
os.path.dirname(__file__), 'ascat_test_data', 'eumetsat',
'ASCAT_generic_reader_data', 'eps_nat')
self.image_eps = level1.AscatL1Eps(self.data_path, eo_portal=True)
def tearDown(self):
self.image_eps = None
def test_image_reading(self):
data, meta, timestamp, lon, lat, time_var = self.image_eps.read(
datetime(2010, 6, 9, 1, 39))
assert lon.shape == (267648,)
assert lat.shape == (267648,)
def test_image_reading_szf(self):
szf_dict = self.image_eps.read(
datetime(2018, 6, 11, 4, 18))
szf_dict['img1'].lon
assert szf_dict['img1'].lon.shape == (1383552,)
assert szf_dict['img1'].lat.shape == (1383552,)
def test_get_orbit_start_date(self):
filename = os.path.join(self.data_path,
'ASCA_SZR_1B_M02_20100609013900Z_20100609032058Z_R_O_20130824233100Z.nat')
orbit_start = self.image_eps._get_orbit_start_date(filename)
orbit_start_should = datetime(2010, 6, 9, 1, 39)
assert orbit_start == orbit_start_should
def test_tstamp_for_daterange(self):
tstamps = self.image_eps.tstamps_for_daterange(
datetime(2010, 6, 8), datetime(2010, 6, 10))
tstamps_should = [datetime(2010, 6, 9, 1, 39)]
assert tstamps == tstamps_should
class Test_AscatL1Nc(unittest.TestCase):
def setUp(self):
self.data_path = os.path.join(
os.path.dirname(__file__), 'ascat_test_data', 'eumetsat',
'ASCAT_generic_reader_data', 'nc')
self.image_nc = level1.AscatL1Nc(self.data_path, eo_portal=True)
def tearDown(self):
self.image_nc = None
def test_image_reading(self):
data, meta, timestamp, lon, lat, time_var = self.image_nc.read(
datetime(2010, 6, 9, 1, 39))
assert lon.shape == (267648,)
assert lat.shape == (267648,)
def test_get_orbit_start_date(self):
filename = os.path.join(self.data_path,
'W_XX-EUMETSAT-Darmstadt,SURFACE+SATELLITE,METOPA+ASCAT_C_EUMP_20100609013900_18872_eps_o_125_l1.nc')
orbit_start = self.image_nc._get_orbit_start_date(filename)
orbit_start_should = datetime(2010, 6, 9, 1, 39)
assert orbit_start == orbit_start_should
def test_tstamp_for_daterange(self):
tstamps = self.image_nc.tstamps_for_daterange(datetime(2010, 6, 8),
datetime(2010, 6, 10))
tstamps_should = [datetime(2010, 6, 9, 1, 39)]
assert tstamps == tstamps_should
class Test_AscatL1Hdf5(unittest.TestCase):
def setUp(self):
self.data_path = os.path.join(
os.path.dirname(__file__), 'ascat_test_data', 'eumetsat',
'ASCAT_generic_reader_data', 'hdf5')
self.image_h5 = level1.AscatL1Hdf5(self.data_path, eo_portal=True)
def tearDown(self):
self.image_h5 = None
def test_image_reading(self):
szf_dict = self.image_h5.read(
datetime(2018, 6, 11, 4, 18))
szf_dict['img1'].lon
assert szf_dict['img1'].lon.shape == (1383552,)
assert szf_dict['img1'].lat.shape == (1383552,)
def test_get_orbit_start_date(self):
filename = os.path.join(self.data_path,
'ASCA_SZF_1B_M01_20180611041800Z_20180611055959Z_N_O_20180611050637Z.h5')
orbit_start = self.image_h5._get_orbit_start_date(filename)
orbit_start_should = datetime(2018, 6, 11, 4, 18)
assert orbit_start == orbit_start_should
def test_tstamp_for_daterange(self):
tstamps = self.image_h5.tstamps_for_daterange(datetime(2018, 6, 10),
datetime(2018, 6, 12))
tstamps_should = [datetime(2018, 6, 11, 4, 18)]
assert tstamps == tstamps_should
| [
"datetime.datetime",
"ascat.level1.AscatL1Hdf5",
"ascat.level1.AscatL1Image",
"ascat.level1.AscatL1Eps",
"numpy.testing.assert_allclose",
"os.path.join",
"numpy.array",
"os.path.dirname",
"ascat.level1.AscatL1Nc",
"ascat.level1.AscatL1Bufr",
"numpy.finfo"
] | [((1829, 1849), 'numpy.finfo', 'np.finfo', (['np.float32'], {}), '(np.float32)\n', (1837, 1849), True, 'import numpy as np\n'), ((2085, 2210), 'os.path.join', 'os.path.join', (['data_path', '"""bufr"""', '"""M02-ASCA-ASCSZR1B0200-NA-9.1-20100609013900.000000000Z-20130824233100-1280350.bfr"""'], {}), "(data_path, 'bufr',\n 'M02-ASCA-ASCSZR1B0200-NA-9.1-20100609013900.000000000Z-20130824233100-1280350.bfr'\n )\n", (2097, 2210), False, 'import os\n'), ((2249, 2362), 'os.path.join', 'os.path.join', (['data_path', '"""eps_nat"""', '"""ASCA_SZR_1B_M02_20100609013900Z_20100609032058Z_R_O_20130824233100Z.nat"""'], {}), "(data_path, 'eps_nat',\n 'ASCA_SZR_1B_M02_20100609013900Z_20100609032058Z_R_O_20130824233100Z.nat')\n", (2261, 2362), False, 'import os\n'), ((2406, 2546), 'os.path.join', 'os.path.join', (['data_path', '"""nc"""', '"""W_XX-EUMETSAT-Darmstadt,SURFACE+SATELLITE,METOPA+ASCAT_C_EUMP_20100609013900_18872_eps_o_125_l1.nc"""'], {}), "(data_path, 'nc',\n 'W_XX-EUMETSAT-Darmstadt,SURFACE+SATELLITE,METOPA+ASCAT_C_EUMP_20100609013900_18872_eps_o_125_l1.nc'\n )\n", (2418, 2546), False, 'import os\n'), ((2588, 2701), 'os.path.join', 'os.path.join', (['data_path', '"""eps_nat"""', '"""ASCA_SZR_1B_M02_20071212071500Z_20071212085659Z_R_O_20081225063118Z.nat"""'], {}), "(data_path, 'eps_nat',\n 'ASCA_SZR_1B_M02_20071212071500Z_20071212085659Z_R_O_20081225063118Z.nat')\n", (2600, 2701), False, 'import os\n'), ((2751, 2864), 'os.path.join', 'os.path.join', (['data_path', '"""eps_nat"""', '"""ASCA_SZF_1B_M01_20180611041800Z_20180611055959Z_N_O_20180611050637Z.nat"""'], {}), "(data_path, 'eps_nat',\n 'ASCA_SZF_1B_M01_20180611041800Z_20180611055959Z_N_O_20180611050637Z.nat')\n", (2763, 2864), False, 'import os\n'), ((2912, 3021), 'os.path.join', 'os.path.join', (['data_path', '"""hdf5"""', '"""ASCA_SZF_1B_M01_20180611041800Z_20180611055959Z_N_O_20180611050637Z.h5"""'], {}), "(data_path, 'hdf5',\n 'ASCA_SZF_1B_M01_20180611041800Z_20180611055959Z_N_O_20180611050637Z.h5')\n", (2924, 3021), False, 'import os\n'), ((3075, 3102), 'ascat.level1.AscatL1Image', 'level1.AscatL1Image', (['name_b'], {}), '(name_b)\n', (3094, 3102), True, 'import ascat.level1 as level1\n'), ((3128, 3155), 'ascat.level1.AscatL1Image', 'level1.AscatL1Image', (['name_e'], {}), '(name_e)\n', (3147, 3155), True, 'import ascat.level1 as level1\n'), ((3180, 3207), 'ascat.level1.AscatL1Image', 'level1.AscatL1Image', (['name_n'], {}), '(name_n)\n', (3199, 3207), True, 'import ascat.level1 as level1\n'), ((3240, 3269), 'ascat.level1.AscatL1Image', 'level1.AscatL1Image', (['name_e11'], {}), '(name_e11)\n', (3259, 3269), True, 'import ascat.level1 as level1\n'), ((3298, 3329), 'ascat.level1.AscatL1Image', 'level1.AscatL1Image', (['name_e_szf'], {}), '(name_e_szf)\n', (3317, 3329), True, 'import ascat.level1 as level1\n'), ((3358, 3385), 'ascat.level1.AscatL1Image', 'level1.AscatL1Image', (['name_h'], {}), '(name_h)\n', (3377, 3385), True, 'import ascat.level1 as level1\n'), ((3808, 3886), 'numpy.testing.assert_allclose', 'nptest.assert_allclose', (['self.reader_bufr.lat', 'self.reader_eps.lat'], {'atol': '(0.0001)'}), '(self.reader_bufr.lat, self.reader_eps.lat, atol=0.0001)\n', (3830, 3886), True, 'import numpy.testing as nptest\n'), ((3924, 4000), 'numpy.testing.assert_allclose', 'nptest.assert_allclose', (['self.reader_eps.lat', 'self.reader_nc.lat'], {'atol': '(0.0001)'}), '(self.reader_eps.lat, self.reader_nc.lat, atol=0.0001)\n', (3946, 4000), True, 'import numpy.testing as nptest\n'), ((4038, 4115), 'numpy.testing.assert_allclose', 'nptest.assert_allclose', (['self.reader_nc.lat', 'self.reader_bufr.lat'], {'atol': '(0.0001)'}), '(self.reader_nc.lat, self.reader_bufr.lat, atol=0.0001)\n', (4060, 4115), True, 'import numpy.testing as nptest\n'), ((4154, 4232), 'numpy.testing.assert_allclose', 'nptest.assert_allclose', (['self.reader_bufr.lon', 'self.reader_eps.lon'], {'atol': '(0.0001)'}), '(self.reader_bufr.lon, self.reader_eps.lon, atol=0.0001)\n', (4176, 4232), True, 'import numpy.testing as nptest\n'), ((4270, 4346), 'numpy.testing.assert_allclose', 'nptest.assert_allclose', (['self.reader_eps.lon', 'self.reader_nc.lon'], {'atol': '(0.0001)'}), '(self.reader_eps.lon, self.reader_nc.lon, atol=0.0001)\n', (4292, 4346), True, 'import numpy.testing as nptest\n'), ((4384, 4461), 'numpy.testing.assert_allclose', 'nptest.assert_allclose', (['self.reader_nc.lon', 'self.reader_bufr.lon'], {'atol': '(0.0001)'}), '(self.reader_nc.lon, self.reader_bufr.lon, atol=0.0001)\n', (4406, 4461), True, 'import numpy.testing as nptest\n'), ((7621, 7903), 'numpy.array', 'np.array', (['[68.91681, 69.005196, 69.09337, 69.18132, 69.26905, 69.35655, 69.443825, \n 69.53087, 69.61768, 69.704254, 69.79059, 69.87668, 69.962524, 70.04812,\n 70.13346, 70.218544, 70.303375, 70.38794, 70.47224, 70.55626, 70.640015,\n 70.723495, 70.806694, 70.88961, 70.97224]'], {}), '([68.91681, 69.005196, 69.09337, 69.18132, 69.26905, 69.35655, \n 69.443825, 69.53087, 69.61768, 69.704254, 69.79059, 69.87668, 69.962524,\n 70.04812, 70.13346, 70.218544, 70.303375, 70.38794, 70.47224, 70.55626,\n 70.640015, 70.723495, 70.806694, 70.88961, 70.97224])\n', (7629, 7903), True, 'import numpy as np\n'), ((7978, 8281), 'numpy.array', 'np.array', (['[168.80144, 168.60977, 168.41656, 168.22179, 168.02544, 167.82748, \n 167.62794, 167.42676, 167.22394, 167.01947, 166.81332, 166.60548, \n 166.39592, 166.18465, 165.97163, 165.75685, 165.5403, 165.32195, \n 165.10178, 164.87979, 164.65594, 164.43024, 164.20264, 163.97314, 163.74171\n ]'], {}), '([168.80144, 168.60977, 168.41656, 168.22179, 168.02544, 167.82748,\n 167.62794, 167.42676, 167.22394, 167.01947, 166.81332, 166.60548, \n 166.39592, 166.18465, 165.97163, 165.75685, 165.5403, 165.32195, \n 165.10178, 164.87979, 164.65594, 164.43024, 164.20264, 163.97314, \n 163.74171])\n', (7986, 8281), True, 'import numpy as np\n'), ((8350, 8676), 'numpy.array', 'np.array', (['[-13.510671, -13.421737, -13.872492, -14.351357, -14.395881, -14.382635, -\n 14.860762, -16.108913, -17.354418, -18.86383, -18.793966, -18.631758, -\n 18.46626, -18.71435, -19.150038, -19.315845, -19.79865, -19.845669, -\n 19.892258, -20.138796, -20.151554, -20.154343, -20.165552, -20.013523, \n -19.238102]'], {}), '([-13.510671, -13.421737, -13.872492, -14.351357, -14.395881, -\n 14.382635, -14.860762, -16.108913, -17.354418, -18.86383, -18.793966, -\n 18.631758, -18.46626, -18.71435, -19.150038, -19.315845, -19.79865, -\n 19.845669, -19.892258, -20.138796, -20.151554, -20.154343, -20.165552, \n -20.013523, -19.238102])\n', (8358, 8676), True, 'import numpy as np\n'), ((8743, 8958), 'numpy.array', 'np.array', (['[0.0307, 0.032, 0.051, 0.0696, 0.0703, 0.0584, 0.045, 0.0464, 0.0615, \n 0.0477, 0.0323, 0.04, 0.0346, 0.0369, 0.0378, 0.0397, 0.0341, 0.0399, \n 0.0418, 0.0408, 0.0421, 0.0347, 0.0424, 0.0451, 0.0523]'], {}), '([0.0307, 0.032, 0.051, 0.0696, 0.0703, 0.0584, 0.045, 0.0464, \n 0.0615, 0.0477, 0.0323, 0.04, 0.0346, 0.0369, 0.0378, 0.0397, 0.0341, \n 0.0399, 0.0418, 0.0408, 0.0421, 0.0347, 0.0424, 0.0451, 0.0523])\n', (8751, 8958), True, 'import numpy as np\n'), ((9022, 9201), 'numpy.array', 'np.array', (['[2455356.56875, 2455356.56875, 2455356.56875, 2455356.56875, 2455356.56875,\n 2455356.56875, 2455356.56875, 2455356.56877169, 2455356.56877169, \n 2455356.56877169]'], {}), '([2455356.56875, 2455356.56875, 2455356.56875, 2455356.56875, \n 2455356.56875, 2455356.56875, 2455356.56875, 2455356.56877169, \n 2455356.56877169, 2455356.56877169])\n', (9030, 9201), True, 'import numpy as np\n'), ((9253, 9321), 'numpy.testing.assert_allclose', 'nptest.assert_allclose', (['self.reader.lat[:25]', 'lat_should'], {'atol': '(1e-05)'}), '(self.reader.lat[:25], lat_should, atol=1e-05)\n', (9275, 9321), True, 'import numpy.testing as nptest\n'), ((9329, 9397), 'numpy.testing.assert_allclose', 'nptest.assert_allclose', (['self.reader.lon[:25]', 'lon_should'], {'atol': '(1e-05)'}), '(self.reader.lon[:25], lon_should, atol=1e-05)\n', (9351, 9397), True, 'import numpy.testing as nptest\n'), ((9405, 9482), 'numpy.testing.assert_allclose', 'nptest.assert_allclose', (["self.reader.data['sigf'][:25]", 'sig_should'], {'atol': '(1e-05)'}), "(self.reader.data['sigf'][:25], sig_should, atol=1e-05)\n", (9427, 9482), True, 'import numpy.testing as nptest\n'), ((9521, 9596), 'numpy.testing.assert_allclose', 'nptest.assert_allclose', (["self.reader.data['kpf'][:25]", 'kp_should'], {'atol': '(1e-05)'}), "(self.reader.data['kpf'][:25], kp_should, atol=1e-05)\n", (9543, 9596), True, 'import numpy.testing as nptest\n'), ((9635, 9711), 'numpy.testing.assert_allclose', 'nptest.assert_allclose', (["self.reader.data['jd'][75:85]", 'jd_should'], {'atol': '(1e-05)'}), "(self.reader.data['jd'][75:85], jd_should, atol=1e-05)\n", (9657, 9711), True, 'import numpy.testing as nptest\n'), ((9863, 10152), 'numpy.array', 'np.array', (['[61.849445, 61.916786, 61.983864, 62.050674, 62.11722, 62.183495, 62.2495, \n 62.315228, 62.380684, 62.44586, 62.51076, 62.57538, 62.63971, 62.70376,\n 62.76752, 62.830994, 62.894173, 62.95706, 63.019653, 63.081947, \n 63.143944, 63.205635, 63.267025, 63.32811, 63.388885]'], {}), '([61.849445, 61.916786, 61.983864, 62.050674, 62.11722, 62.183495, \n 62.2495, 62.315228, 62.380684, 62.44586, 62.51076, 62.57538, 62.63971, \n 62.70376, 62.76752, 62.830994, 62.894173, 62.95706, 63.019653, \n 63.081947, 63.143944, 63.205635, 63.267025, 63.32811, 63.388885])\n', (9871, 10152), True, 'import numpy as np\n'), ((10225, 10503), 'numpy.array', 'np.array', (['[69.18133, 68.991295, 68.80043, 68.60872, 68.41617, 68.22277, 68.028534, \n 67.833435, 67.63749, 67.44069, 67.243034, 67.04452, 66.84513, 66.64489,\n 66.44378, 66.2418, 66.03894, 65.83522, 65.630615, 65.42514, 65.21878, \n 65.01154, 64.80342, 64.59441, 64.38452]'], {}), '([69.18133, 68.991295, 68.80043, 68.60872, 68.41617, 68.22277, \n 68.028534, 67.833435, 67.63749, 67.44069, 67.243034, 67.04452, 66.84513,\n 66.64489, 66.44378, 66.2418, 66.03894, 65.83522, 65.630615, 65.42514, \n 65.21878, 65.01154, 64.80342, 64.59441, 64.38452])\n', (10233, 10503), True, 'import numpy as np\n'), ((10577, 10903), 'numpy.array', 'np.array', (['[-15.008125, -14.547356, -15.067405, -15.340037, -15.381483, -15.085848, -\n 14.620477, -14.200545, -13.873865, -13.29581, -12.962119, -12.909232, -\n 12.990307, -13.076723, -13.039384, -13.010556, -13.238036, -13.045113, \n -12.981088, -13.003889, -14.009461, -14.633162, -14.706434, -14.042056,\n -13.7074]'], {}), '([-15.008125, -14.547356, -15.067405, -15.340037, -15.381483, -\n 15.085848, -14.620477, -14.200545, -13.873865, -13.29581, -12.962119, -\n 12.909232, -12.990307, -13.076723, -13.039384, -13.010556, -13.238036, \n -13.045113, -12.981088, -13.003889, -14.009461, -14.633162, -14.706434,\n -14.042056, -13.7074])\n', (10585, 10903), True, 'import numpy as np\n'), ((10971, 11188), 'numpy.array', 'np.array', (['[0.052, 0.0417, 0.0462, 0.0264, 0.0308, 0.0296, 0.0363, 0.0348, 0.0377, \n 0.036, 0.0329, 0.0258, 0.0296, 0.0245, 0.0275, 0.0309, 0.035, 0.0325, \n 0.0288, 0.0292, 0.0431, 0.0363, 0.0435, 0.0282, 0.0309]'], {}), '([0.052, 0.0417, 0.0462, 0.0264, 0.0308, 0.0296, 0.0363, 0.0348, \n 0.0377, 0.036, 0.0329, 0.0258, 0.0296, 0.0245, 0.0275, 0.0309, 0.035, \n 0.0325, 0.0288, 0.0292, 0.0431, 0.0363, 0.0435, 0.0282, 0.0309])\n', (10979, 11188), True, 'import numpy as np\n'), ((11252, 11451), 'numpy.array', 'np.array', (['[2454446.80208333, 2454446.80208333, 2454446.80208333, 2454446.80208333, \n 2454446.80208333, 2454446.80208333, 2454446.80208333, 2454446.80210505,\n 2454446.80210505, 2454446.80210505]'], {}), '([2454446.80208333, 2454446.80208333, 2454446.80208333, \n 2454446.80208333, 2454446.80208333, 2454446.80208333, 2454446.80208333,\n 2454446.80210505, 2454446.80210505, 2454446.80210505])\n', (11260, 11451), True, 'import numpy as np\n'), ((11504, 11572), 'numpy.testing.assert_allclose', 'nptest.assert_allclose', (['self.reader.lat[:25]', 'lat_should'], {'atol': '(1e-05)'}), '(self.reader.lat[:25], lat_should, atol=1e-05)\n', (11526, 11572), True, 'import numpy.testing as nptest\n'), ((11580, 11648), 'numpy.testing.assert_allclose', 'nptest.assert_allclose', (['self.reader.lon[:25]', 'lon_should'], {'atol': '(1e-05)'}), '(self.reader.lon[:25], lon_should, atol=1e-05)\n', (11602, 11648), True, 'import numpy.testing as nptest\n'), ((11656, 11733), 'numpy.testing.assert_allclose', 'nptest.assert_allclose', (["self.reader.data['sigf'][:25]", 'sig_should'], {'atol': '(1e-05)'}), "(self.reader.data['sigf'][:25], sig_should, atol=1e-05)\n", (11678, 11733), True, 'import numpy.testing as nptest\n'), ((11772, 11847), 'numpy.testing.assert_allclose', 'nptest.assert_allclose', (["self.reader.data['kpf'][:25]", 'kp_should'], {'atol': '(1e-05)'}), "(self.reader.data['kpf'][:25], kp_should, atol=1e-05)\n", (11794, 11847), True, 'import numpy.testing as nptest\n'), ((11886, 11962), 'numpy.testing.assert_allclose', 'nptest.assert_allclose', (["self.reader.data['jd'][75:85]", 'jd_should'], {'atol': '(1e-05)'}), "(self.reader.data['jd'][75:85], jd_should, atol=1e-05)\n", (11908, 11962), True, 'import numpy.testing as nptest\n'), ((12104, 12387), 'numpy.array', 'np.array', (['[64.45502, 64.42318, 64.39127, 64.35929, 64.32724, 64.29512, 64.262924, \n 64.23065, 64.19831, 64.16589, 64.1334, 64.10083, 64.06819, 64.03547, \n 64.00268, 63.969807, 63.936855, 63.903828, 63.870724, 63.837536, \n 63.804276, 63.77093, 63.737507, 63.704002, 63.67042]'], {}), '([64.45502, 64.42318, 64.39127, 64.35929, 64.32724, 64.29512, \n 64.262924, 64.23065, 64.19831, 64.16589, 64.1334, 64.10083, 64.06819, \n 64.03547, 64.00268, 63.969807, 63.936855, 63.903828, 63.870724, \n 63.837536, 63.804276, 63.77093, 63.737507, 63.704002, 63.67042])\n', (12112, 12387), True, 'import numpy as np\n'), ((12460, 12768), 'numpy.array', 'np.array', (['[103.29956, 103.32185, 103.34413, 103.36641, 103.38869, 103.41095, \n 103.43322, 103.45548, 103.47774, 103.49999, 103.52224, 103.54449, \n 103.566734, 103.588974, 103.61121, 103.63345, 103.655685, 103.67792, \n 103.70014, 103.722374, 103.7446, 103.76682, 103.78904, 103.811264, \n 103.83348]'], {}), '([103.29956, 103.32185, 103.34413, 103.36641, 103.38869, 103.41095,\n 103.43322, 103.45548, 103.47774, 103.49999, 103.52224, 103.54449, \n 103.566734, 103.588974, 103.61121, 103.63345, 103.655685, 103.67792, \n 103.70014, 103.722374, 103.7446, 103.76682, 103.78904, 103.811264, \n 103.83348])\n', (12468, 12768), True, 'import numpy as np\n'), ((12837, 13139), 'numpy.array', 'np.array', (['[-9.713457, -8.768949, -9.294478, -7.449275, -8.939872, -7.893198, -\n 8.570546, -8.934691, -7.851117, -7.782818, -8.33993, -7.539894, -\n 7.833797, -8.465893, -8.244121, -7.59996, -8.976448, -9.36595, -\n 10.800382, -8.289896, -9.127579, -9.410345, -7.238986, -8.335969, -7.897769\n ]'], {}), '([-9.713457, -8.768949, -9.294478, -7.449275, -8.939872, -7.893198,\n -8.570546, -8.934691, -7.851117, -7.782818, -8.33993, -7.539894, -\n 7.833797, -8.465893, -8.244121, -7.59996, -8.976448, -9.36595, -\n 10.800382, -8.289896, -9.127579, -9.410345, -7.238986, -8.335969, -\n 7.897769])\n', (12845, 13139), True, 'import numpy as np\n'), ((13207, 13406), 'numpy.array', 'np.array', (['[2458280.67917396, 2458280.67917396, 2458280.67918378, 2458280.67918378, \n 2458280.67918378, 2458280.67918378, 2458280.67918378, 2458280.67918378,\n 2458280.67918378, 2458280.67918378]'], {}), '([2458280.67917396, 2458280.67917396, 2458280.67918378, \n 2458280.67918378, 2458280.67918378, 2458280.67918378, 2458280.67918378,\n 2458280.67918378, 2458280.67918378, 2458280.67918378])\n', (13215, 13406), True, 'import numpy as np\n'), ((13459, 13535), 'numpy.testing.assert_allclose', 'nptest.assert_allclose', (["self.reader['img1'].lat[:25]", 'lat_should'], {'atol': '(1e-05)'}), "(self.reader['img1'].lat[:25], lat_should, atol=1e-05)\n", (13481, 13535), True, 'import numpy.testing as nptest\n'), ((13574, 13650), 'numpy.testing.assert_allclose', 'nptest.assert_allclose', (["self.reader['img1'].lon[:25]", 'lon_should'], {'atol': '(1e-05)'}), "(self.reader['img1'].lon[:25], lon_should, atol=1e-05)\n", (13596, 13650), True, 'import numpy.testing as nptest\n'), ((13689, 13777), 'numpy.testing.assert_allclose', 'nptest.assert_allclose', (["self.reader['img1'].data['sig'][:25]", 'sig_should'], {'atol': '(1e-05)'}), "(self.reader['img1'].data['sig'][:25], sig_should,\n atol=1e-05)\n", (13711, 13777), True, 'import numpy.testing as nptest\n'), ((13812, 13902), 'numpy.testing.assert_allclose', 'nptest.assert_allclose', (["self.reader['img1'].data['jd'][190:200]", 'jd_should'], {'atol': '(1e-05)'}), "(self.reader['img1'].data['jd'][190:200], jd_should,\n atol=1e-05)\n", (13834, 13902), True, 'import numpy.testing as nptest\n'), ((14181, 14231), 'ascat.level1.AscatL1Bufr', 'level1.AscatL1Bufr', (['self.data_path'], {'eo_portal': '(True)'}), '(self.data_path, eo_portal=True)\n', (14199, 14231), True, 'import ascat.level1 as level1\n'), ((14576, 14698), 'os.path.join', 'os.path.join', (['self.data_path', '"""M02-ASCA-ASCSZR1B0200-NA-9.1-20100609013900.000000000Z-20130824233100-1280350.bfr"""'], {}), "(self.data_path,\n 'M02-ASCA-ASCSZR1B0200-NA-9.1-20100609013900.000000000Z-20130824233100-1280350.bfr'\n )\n", (14588, 14698), False, 'import os\n'), ((14821, 14848), 'datetime.datetime', 'datetime', (['(2010)', '(6)', '(9)', '(1)', '(39)'], {}), '(2010, 6, 9, 1, 39)\n', (14829, 14848), False, 'from datetime import datetime\n'), ((15448, 15497), 'ascat.level1.AscatL1Eps', 'level1.AscatL1Eps', (['self.data_path'], {'eo_portal': '(True)'}), '(self.data_path, eo_portal=True)\n', (15465, 15497), True, 'import ascat.level1 as level1\n'), ((16103, 16210), 'os.path.join', 'os.path.join', (['self.data_path', '"""ASCA_SZR_1B_M02_20100609013900Z_20100609032058Z_R_O_20130824233100Z.nat"""'], {}), "(self.data_path,\n 'ASCA_SZR_1B_M02_20100609013900Z_20100609032058Z_R_O_20130824233100Z.nat')\n", (16115, 16210), False, 'import os\n'), ((16337, 16364), 'datetime.datetime', 'datetime', (['(2010)', '(6)', '(9)', '(1)', '(39)'], {}), '(2010, 6, 9, 1, 39)\n', (16345, 16364), False, 'from datetime import datetime\n'), ((16913, 16961), 'ascat.level1.AscatL1Nc', 'level1.AscatL1Nc', (['self.data_path'], {'eo_portal': '(True)'}), '(self.data_path, eo_portal=True)\n', (16929, 16961), True, 'import ascat.level1 as level1\n'), ((17302, 17441), 'os.path.join', 'os.path.join', (['self.data_path', '"""W_XX-EUMETSAT-Darmstadt,SURFACE+SATELLITE,METOPA+ASCAT_C_EUMP_20100609013900_18872_eps_o_125_l1.nc"""'], {}), "(self.data_path,\n 'W_XX-EUMETSAT-Darmstadt,SURFACE+SATELLITE,METOPA+ASCAT_C_EUMP_20100609013900_18872_eps_o_125_l1.nc'\n )\n", (17314, 17441), False, 'import os\n'), ((17562, 17589), 'datetime.datetime', 'datetime', (['(2010)', '(6)', '(9)', '(1)', '(39)'], {}), '(2010, 6, 9, 1, 39)\n', (17570, 17589), False, 'from datetime import datetime\n'), ((18182, 18232), 'ascat.level1.AscatL1Hdf5', 'level1.AscatL1Hdf5', (['self.data_path'], {'eo_portal': '(True)'}), '(self.data_path, eo_portal=True)\n', (18200, 18232), True, 'import ascat.level1 as level1\n'), ((18606, 18712), 'os.path.join', 'os.path.join', (['self.data_path', '"""ASCA_SZF_1B_M01_20180611041800Z_20180611055959Z_N_O_20180611050637Z.h5"""'], {}), "(self.data_path,\n 'ASCA_SZF_1B_M01_20180611041800Z_20180611055959Z_N_O_20180611050637Z.h5')\n", (18618, 18712), False, 'import os\n'), ((18838, 18866), 'datetime.datetime', 'datetime', (['(2018)', '(6)', '(11)', '(4)', '(18)'], {}), '(2018, 6, 11, 4, 18)\n', (18846, 18866), False, 'from datetime import datetime\n'), ((1968, 1993), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (1983, 1993), False, 'import os\n'), ((6251, 6345), 'numpy.testing.assert_allclose', 'nptest.assert_allclose', (['self.reader_eps.data[field]', 'self.reader_nc.data[field]'], {'atol': '(0.1)'}), '(self.reader_eps.data[field], self.reader_nc.data[\n field], atol=0.1)\n', (6273, 6345), True, 'import numpy.testing as nptest\n'), ((6593, 6702), 'numpy.testing.assert_allclose', 'nptest.assert_allclose', (['self.reader_eps_szf[szf_img].lat', 'self.reader_hdf5_szf[szf_img].lat'], {'atol': '(0.0001)'}), '(self.reader_eps_szf[szf_img].lat, self.\n reader_hdf5_szf[szf_img].lat, atol=0.0001)\n', (6615, 6702), True, 'import numpy.testing as nptest\n'), ((6779, 6888), 'numpy.testing.assert_allclose', 'nptest.assert_allclose', (['self.reader_eps_szf[szf_img].lon', 'self.reader_hdf5_szf[szf_img].lon'], {'atol': '(0.0001)'}), '(self.reader_eps_szf[szf_img].lon, self.\n reader_hdf5_szf[szf_img].lon, atol=0.0001)\n', (6801, 6888), True, 'import numpy.testing as nptest\n'), ((14047, 14072), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (14062, 14072), False, 'import os\n'), ((14409, 14436), 'datetime.datetime', 'datetime', (['(2010)', '(6)', '(9)', '(1)', '(39)'], {}), '(2010, 6, 9, 1, 39)\n', (14417, 14436), False, 'from datetime import datetime\n'), ((14997, 15017), 'datetime.datetime', 'datetime', (['(2010)', '(6)', '(8)'], {}), '(2010, 6, 8)\n', (15005, 15017), False, 'from datetime import datetime\n'), ((15075, 15096), 'datetime.datetime', 'datetime', (['(2010)', '(6)', '(10)'], {}), '(2010, 6, 10)\n', (15083, 15096), False, 'from datetime import datetime\n'), ((15124, 15151), 'datetime.datetime', 'datetime', (['(2010)', '(6)', '(9)', '(1)', '(39)'], {}), '(2010, 6, 9, 1, 39)\n', (15132, 15151), False, 'from datetime import datetime\n'), ((15312, 15337), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (15327, 15337), False, 'import os\n'), ((15673, 15700), 'datetime.datetime', 'datetime', (['(2010)', '(6)', '(9)', '(1)', '(39)'], {}), '(2010, 6, 9, 1, 39)\n', (15681, 15700), False, 'from datetime import datetime\n'), ((15870, 15898), 'datetime.datetime', 'datetime', (['(2018)', '(6)', '(11)', '(4)', '(18)'], {}), '(2018, 6, 11, 4, 18)\n', (15878, 15898), False, 'from datetime import datetime\n'), ((16525, 16545), 'datetime.datetime', 'datetime', (['(2010)', '(6)', '(8)'], {}), '(2010, 6, 8)\n', (16533, 16545), False, 'from datetime import datetime\n'), ((16547, 16568), 'datetime.datetime', 'datetime', (['(2010)', '(6)', '(10)'], {}), '(2010, 6, 10)\n', (16555, 16568), False, 'from datetime import datetime\n'), ((16596, 16623), 'datetime.datetime', 'datetime', (['(2010)', '(6)', '(9)', '(1)', '(39)'], {}), '(2010, 6, 9, 1, 39)\n', (16604, 16623), False, 'from datetime import datetime\n'), ((16783, 16808), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (16798, 16808), False, 'import os\n'), ((17135, 17162), 'datetime.datetime', 'datetime', (['(2010)', '(6)', '(9)', '(1)', '(39)'], {}), '(2010, 6, 9, 1, 39)\n', (17143, 17162), False, 'from datetime import datetime\n'), ((17736, 17756), 'datetime.datetime', 'datetime', (['(2010)', '(6)', '(8)'], {}), '(2010, 6, 8)\n', (17744, 17756), False, 'from datetime import datetime\n'), ((17812, 17833), 'datetime.datetime', 'datetime', (['(2010)', '(6)', '(10)'], {}), '(2010, 6, 10)\n', (17820, 17833), False, 'from datetime import datetime\n'), ((17861, 17888), 'datetime.datetime', 'datetime', (['(2010)', '(6)', '(9)', '(1)', '(39)'], {}), '(2010, 6, 9, 1, 39)\n', (17869, 17888), False, 'from datetime import datetime\n'), ((18050, 18075), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (18065, 18075), False, 'import os\n'), ((18373, 18401), 'datetime.datetime', 'datetime', (['(2018)', '(6)', '(11)', '(4)', '(18)'], {}), '(2018, 6, 11, 4, 18)\n', (18381, 18401), False, 'from datetime import datetime\n'), ((19013, 19034), 'datetime.datetime', 'datetime', (['(2018)', '(6)', '(10)'], {}), '(2018, 6, 10)\n', (19021, 19034), False, 'from datetime import datetime\n'), ((19090, 19111), 'datetime.datetime', 'datetime', (['(2018)', '(6)', '(12)'], {}), '(2018, 6, 12)\n', (19098, 19111), False, 'from datetime import datetime\n'), ((19139, 19167), 'datetime.datetime', 'datetime', (['(2018)', '(6)', '(11)', '(4)', '(18)'], {}), '(2018, 6, 11, 4, 18)\n', (19147, 19167), False, 'from datetime import datetime\n'), ((5961, 6057), 'numpy.testing.assert_allclose', 'nptest.assert_allclose', (['self.reader_bufr.data[field]', 'self.reader_eps.data[field]'], {'atol': '(0.1)'}), '(self.reader_bufr.data[field], self.reader_eps.data[\n field], atol=0.1)\n', (5983, 6057), True, 'import numpy.testing as nptest\n'), ((6108, 6203), 'numpy.testing.assert_allclose', 'nptest.assert_allclose', (['self.reader_nc.data[field]', 'self.reader_bufr.data[field]'], {'atol': '(0.1)'}), '(self.reader_nc.data[field], self.reader_bufr.data[\n field], atol=0.1)\n', (6130, 6203), True, 'import numpy.testing as nptest\n'), ((7335, 7457), 'numpy.testing.assert_allclose', 'nptest.assert_allclose', (['self.reader_eps_szf[szf_img].data[field]', 'self.reader_hdf5_szf[szf_img].data[field]'], {'atol': '(0.1)'}), '(self.reader_eps_szf[szf_img].data[field], self.\n reader_hdf5_szf[szf_img].data[field], atol=0.1)\n', (7357, 7457), True, 'import numpy.testing as nptest\n')] |
import torch
import torch.nn as nn
import numpy as np
import numpy.random as rand
from dset import idx2char
# We use cross entropy loss
loss_func = nn.CrossEntropyLoss(reduction='mean')
def compute_loss(rnn, xNy, h_list, device):
"""
compute_loss for a given RNN model using loss_func
Args:
RNN: model to be trained
xNy (tuple): the input and target pair of the form (input, target)
h_list (list): list of hidden states. Each hidden state is a torch.tensor
device(str): 'cpu' or 'cuda'
Returns:
torch.tensor: value of the loss
"""
x_t, y_t = xNy
x_t=x_t.to(device, non_blocking=True)
y_t=y_t.to(device, non_blocking=True)
loss = 0.
for i in range(x_t.shape[1]):
out, h_list = rnn(x_t[:, i, :], h_list)
loss += loss_func(out, y_t[:, i])
return loss
def print_function(max_len, rnn, char_size, h_size, depth, mode):
""" Generate text and print it using rnn.
Args:
max_len (int): maximum length of generated text
rnn: RNN model
char_size: number of characters in the vocabulary.
h_size: size of hidden layer.
mode (str): one of "RNN", "LSTM", "GRU"
"""
rnn.eval()
seed = torch.zeros((1, char_size))
seed[0, rand.randint(0, char_size)] = 1
if mode == "RNN" or mode == "GRU":
h = [torch.zeros((1, h_size)) for i in range(depth)]
elif mode == "LSTM":
h = ([torch.zeros((1, h_size)) for i in range(depth)], [torch.zeros((1, h_size)) for i in range(depth)])
generated = []
out_text = ''
with torch.no_grad():
for i in range(max_len):
out, h = rnn(seed, h)
p = torch.nn.functional.softmax(out, dim=1)
p = np.array(p)
max_idx = np.random.choice(range(char_size), p=p.ravel())
char = idx2char[max_idx.item()]
out_text += char
seed = torch.zeros((1, char_size))
seed[0, max_idx] = 1
print(out_text)
| [
"torch.nn.functional.softmax",
"torch.nn.CrossEntropyLoss",
"numpy.array",
"numpy.random.randint",
"torch.no_grad",
"torch.zeros"
] | [((148, 185), 'torch.nn.CrossEntropyLoss', 'nn.CrossEntropyLoss', ([], {'reduction': '"""mean"""'}), "(reduction='mean')\n", (167, 185), True, 'import torch.nn as nn\n'), ((1239, 1266), 'torch.zeros', 'torch.zeros', (['(1, char_size)'], {}), '((1, char_size))\n', (1250, 1266), False, 'import torch\n'), ((1595, 1610), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (1608, 1610), False, 'import torch\n'), ((1279, 1305), 'numpy.random.randint', 'rand.randint', (['(0)', 'char_size'], {}), '(0, char_size)\n', (1291, 1305), True, 'import numpy.random as rand\n'), ((1363, 1387), 'torch.zeros', 'torch.zeros', (['(1, h_size)'], {}), '((1, h_size))\n', (1374, 1387), False, 'import torch\n'), ((1695, 1734), 'torch.nn.functional.softmax', 'torch.nn.functional.softmax', (['out'], {'dim': '(1)'}), '(out, dim=1)\n', (1722, 1734), False, 'import torch\n'), ((1751, 1762), 'numpy.array', 'np.array', (['p'], {}), '(p)\n', (1759, 1762), True, 'import numpy as np\n'), ((1925, 1952), 'torch.zeros', 'torch.zeros', (['(1, char_size)'], {}), '((1, char_size))\n', (1936, 1952), False, 'import torch\n'), ((1450, 1474), 'torch.zeros', 'torch.zeros', (['(1, h_size)'], {}), '((1, h_size))\n', (1461, 1474), False, 'import torch\n'), ((1500, 1524), 'torch.zeros', 'torch.zeros', (['(1, h_size)'], {}), '((1, h_size))\n', (1511, 1524), False, 'import torch\n')] |
import numpy as np
class InputLayer():
def __init__(self, number_neurons):
self.number_neurons = number_neurons
self.stored_output = []
def calc_feed_forward(self, input):
self.input = input
self.output = input
self.stored_output.append(self.output)
return np.asarray(self.output)
def reset(self):
self.stored_output = []
| [
"numpy.asarray"
] | [((317, 340), 'numpy.asarray', 'np.asarray', (['self.output'], {}), '(self.output)\n', (327, 340), True, 'import numpy as np\n')] |
# Copyright (c) 2018 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# =============================================================================
"""CIFAR 10 dataset.
Author: <NAME> (<EMAIL>)
"""
from __future__ import print_function, division
import os
import numpy as np
import six
import sys
if sys.version.startswith("3"):
from urllib.request import urlretrieve
else:
from urllib import urlretrieve
from subprocess import call
from dataset import DataSet
SOURCE_URL = "https://www.cs.toronto.edu/~kriz/"
def maybe_download(filename, work_directory):
"""Download the data from Alex"s website, unless it"s already here."""
if not os.path.exists(work_directory):
os.makedirs(work_directory)
filepath = os.path.join(work_directory, filename)
if not os.path.exists(os.path.join(work_directory, 'cifar-10-batches-py')):
if not os.path.exists(filepath):
print("Downloading CIFAR-10 from {}".format(SOURCE_URL + filename))
filepath, _ = urlretrieve(SOURCE_URL + filename, filepath)
statinfo = os.stat(filepath)
print("Succesfully downloaded {} {} bytes".format(filename, statinfo.st_size))
print("Unzipping data")
call(["tar", "-xzvf", filepath, "-C", work_directory])
print("Done")
return filepath
def read_data_sets(data_folder, seed=0):
train_img = []
train_label = []
test_img = []
test_label = []
filename = 'cifar-10-python.tar.gz'
maybe_download(filename, data_folder)
train_file_list = [
"data_batch_1", "data_batch_2", "data_batch_3", "data_batch_4", "data_batch_5"
]
test_file_list = ["test_batch"]
for i in six.moves.xrange(len(train_file_list)):
tmp_dict = np.load(
os.path.join(data_folder, 'cifar-10-batches-py', train_file_list[i]), encoding='latin1')
train_img.append(tmp_dict["data"])
train_label.append(tmp_dict["labels"])
tmp_dict = np.load(
os.path.join(data_folder, 'cifar-10-batches-py', test_file_list[0]), encoding='latin1')
test_img.append(tmp_dict["data"])
test_label.append(tmp_dict["labels"])
train_img = np.concatenate(train_img)
train_label = np.concatenate(train_label)
test_img = np.concatenate(test_img)
test_label = np.concatenate(test_label)
train_img = np.reshape(train_img, [-1, 3, 32, 32])
test_img = np.reshape(test_img, [-1, 3, 32, 32])
# change format from [B, C, H, W] to [B, H, W, C] for feeding to Tensorflow
train_img = np.transpose(train_img, [0, 2, 3, 1])
test_img = np.transpose(test_img, [0, 2, 3, 1])
class DataSets(object):
pass
data_sets = DataSets()
data_sets.train = DataSet(train_img, train_label, seed=seed)
data_sets.test = DataSet(test_img, test_label, seed=seed)
return data_sets
| [
"os.path.exists",
"numpy.reshape",
"os.makedirs",
"dataset.DataSet",
"urllib.urlretrieve",
"os.path.join",
"subprocess.call",
"numpy.concatenate",
"os.stat",
"numpy.transpose",
"sys.version.startswith"
] | [((1319, 1346), 'sys.version.startswith', 'sys.version.startswith', (['"""3"""'], {}), "('3')\n", (1341, 1346), False, 'import sys\n'), ((1755, 1793), 'os.path.join', 'os.path.join', (['work_directory', 'filename'], {}), '(work_directory, filename)\n', (1767, 1793), False, 'import os\n'), ((3183, 3208), 'numpy.concatenate', 'np.concatenate', (['train_img'], {}), '(train_img)\n', (3197, 3208), True, 'import numpy as np\n'), ((3227, 3254), 'numpy.concatenate', 'np.concatenate', (['train_label'], {}), '(train_label)\n', (3241, 3254), True, 'import numpy as np\n'), ((3270, 3294), 'numpy.concatenate', 'np.concatenate', (['test_img'], {}), '(test_img)\n', (3284, 3294), True, 'import numpy as np\n'), ((3312, 3338), 'numpy.concatenate', 'np.concatenate', (['test_label'], {}), '(test_label)\n', (3326, 3338), True, 'import numpy as np\n'), ((3356, 3394), 'numpy.reshape', 'np.reshape', (['train_img', '[-1, 3, 32, 32]'], {}), '(train_img, [-1, 3, 32, 32])\n', (3366, 3394), True, 'import numpy as np\n'), ((3410, 3447), 'numpy.reshape', 'np.reshape', (['test_img', '[-1, 3, 32, 32]'], {}), '(test_img, [-1, 3, 32, 32])\n', (3420, 3447), True, 'import numpy as np\n'), ((3545, 3582), 'numpy.transpose', 'np.transpose', (['train_img', '[0, 2, 3, 1]'], {}), '(train_img, [0, 2, 3, 1])\n', (3557, 3582), True, 'import numpy as np\n'), ((3598, 3634), 'numpy.transpose', 'np.transpose', (['test_img', '[0, 2, 3, 1]'], {}), '(test_img, [0, 2, 3, 1])\n', (3610, 3634), True, 'import numpy as np\n'), ((3727, 3769), 'dataset.DataSet', 'DataSet', (['train_img', 'train_label'], {'seed': 'seed'}), '(train_img, train_label, seed=seed)\n', (3734, 3769), False, 'from dataset import DataSet\n'), ((3791, 3831), 'dataset.DataSet', 'DataSet', (['test_img', 'test_label'], {'seed': 'seed'}), '(test_img, test_label, seed=seed)\n', (3798, 3831), False, 'from dataset import DataSet\n'), ((1672, 1702), 'os.path.exists', 'os.path.exists', (['work_directory'], {}), '(work_directory)\n', (1686, 1702), False, 'import os\n'), ((1712, 1739), 'os.makedirs', 'os.makedirs', (['work_directory'], {}), '(work_directory)\n', (1723, 1739), False, 'import os\n'), ((2238, 2292), 'subprocess.call', 'call', (["['tar', '-xzvf', filepath, '-C', work_directory]"], {}), "(['tar', '-xzvf', filepath, '-C', work_directory])\n", (2242, 2292), False, 'from subprocess import call\n'), ((2998, 3065), 'os.path.join', 'os.path.join', (['data_folder', '"""cifar-10-batches-py"""', 'test_file_list[0]'], {}), "(data_folder, 'cifar-10-batches-py', test_file_list[0])\n", (3010, 3065), False, 'import os\n'), ((1820, 1871), 'os.path.join', 'os.path.join', (['work_directory', '"""cifar-10-batches-py"""'], {}), "(work_directory, 'cifar-10-batches-py')\n", (1832, 1871), False, 'import os\n'), ((1889, 1913), 'os.path.exists', 'os.path.exists', (['filepath'], {}), '(filepath)\n', (1903, 1913), False, 'import os\n'), ((2021, 2065), 'urllib.urlretrieve', 'urlretrieve', (['(SOURCE_URL + filename)', 'filepath'], {}), '(SOURCE_URL + filename, filepath)\n', (2032, 2065), False, 'from urllib import urlretrieve\n'), ((2089, 2106), 'os.stat', 'os.stat', (['filepath'], {}), '(filepath)\n', (2096, 2106), False, 'import os\n'), ((2786, 2854), 'os.path.join', 'os.path.join', (['data_folder', '"""cifar-10-batches-py"""', 'train_file_list[i]'], {}), "(data_folder, 'cifar-10-batches-py', train_file_list[i])\n", (2798, 2854), False, 'import os\n')] |
""" This module calculates turbulent viscosity at the cell faces.
Libraries/Modules:
numpy\n
"""
import numpy as np
# from Grid import Grid
# class BaldwinLomax():
# @profile
def turbulent_viscosity(model, ws, state):
""" Baldwin-lomax turbulence model: modtur = 2.
Calculates turbulent viscosity at the cell faces.
Averages to obtain cell center values fully vectorized routine. *
Calculates eddy viscosity, vorticity, total velocity, normal distance.
Also calculates outer and innner eddy viscosity.
Attributes:
rev: eddy viscocity
ylen: normal distance
vor: vorticity
vol: control volume
amuto: outer eddy viscosity
amuti: inner eddy viscosity
Notes:
Adapted from subroutine turb2.f
"""
[nx, ny] = ws.field_size()
# necessary fields
def mget(varName):
return ws.get_field(varName, model.className)
ie = mget('ie')
je = mget('je')
gamma = mget('gamma')
rm = mget('rm')
re = mget('re')
ncyc = mget('ncyc')
rev = mget('rev')
il = nx+1
jl = ny+1
dims = ws.get_dims()
itl = dims['itl']
itu = dims['itu']
w = state
x = mget('x')
p = mget('p')
xtran = mget('xtran')
vol = mget('vol')
tauw = np.ones(nx)
yscal = np.ones(nx)
vor = np.ones((nx,ny))
avorm = np.ones(nx)
ravg = np.ones(nx)
amut = np.ones((nx,ny))
amuto = np.ones(nx)
amuti = np.ones(nx)
yvor = np.ones(nx)
yvorm = np.ones(nx)
utot = np.ones((nx,ny))
utotm = np.ones(nx)
utmin = np.ones(nx)
fkleb = np.ones(nx)
jedge = np.ones(nx)
utmax = np.ones(nx)
amu = np.ones((nx,ny))
u = np.ones((nx,ny))
v = np.ones((nx,ny))
t = np.ones((nx,ny))
fcros = np.ones(nx)
rinv = np.ones((nx,ny))
vola = np.ones((nx,ny))
ylen = np.ones((nx,ny))
ylenm = np.ones(nx)
j2 = je
jlm = jl- 1
jstop = 3* (j2- 2)/5
itlp = itl+ 1
cwk1 = 1.0
ckleb = 0.3
ccp = 1.6
modbl = 3
restarr = 0
rey = re
sgam = np.sqrt(gamma)
sgrm = sgam*rm
sgrmi = 1.0/sgrm
rinv[:,:] = 1.0/w[:,:,0]
t[:,:] = p[:,:]* rinv[:,:]
u[:,:] = w[:,:,1]* rinv[:,:]
v[:,:] = w[:,:,2]* rinv[:,:]
amu[:,:] = t[:,:]
amut[:,:] = 0.0
'''
Determination of eddy viscosity
Turbulence model:
Wall boundary layer --- baldwin-lomax model
Wake region --- baldwin-lomax model (cwake= 1.0)
Calculates vorticity and total velocity
'''
vola[:,:] = 0.5* (vol[:,:]+ vol[:,:+1])
xxa = x[1:,1,1]-x[:il,1,1]
yxa = x[1:,1,2]-x[:il,1,2]
uy = u[1:,2]- u[1:,1]
vy = v[1:,2]- v[1:,1]
uavg = .5* (u[1:,1]+u[1:,2])
vavg = .5* (v[1:,1]+v[1:,2])
vor1 = (xxa*uy + yxa*vy)/vola[1:,1]
vor2 = 0.0
vor3 = 0.0
vort = vor1-vor2-vor3
vor[1:,1] = abs(vort)
utotal = uavg*uavg + vavg*vavg
utot[1:,1] = np.sqrt(utotal)
xxa = x[1:il,1:jlm,0]-x[0:il-1,1:jlm,0]
yxa = x[1:il,1:jlm,1]-x[0:il-1,1:jlm,1]
uy = u[1:il,2:jlm+1]- u[1:il,1:jlm]
vy = v[1:il,2:jlm+1]- v[1:il,1:jlm]
uavg = 0.5* (u[1:il,1:jlm]+ u[1:il,2:jlm+1])
vavg = 0.5* (v[1:il,1:jlm]+ v[1:il,2:jlm+1])
'''
thin-layer navier-stokes contribution to vorticity
'''
vor1 = (xxa*uy + yxa*vy)/vola[1:il,1:jlm]
'''
additional contributions to vorticity
'''
xyw = 0.5* (x[0:il-1,2:jlm+1,0]- x[0:il-1,0:jlm-1,0])
xye = 0.5* (x[1:il,2:jlm+1,0]- x[1:il,0:jlm-1,0])
yyw = 0.5* (x[0:il-1,2:jlm+1,1]- x[0:il-1,0:jlm-1,1])
yye = 0.5* (x[1:il,2:jlm+1,1]- x[1:il,0:jlm-1,1])
volawi = 2.0/(vola[1:il,1:jlm]+ vola[0:il-1,1:jlm])
volaei = 2.0/(vola[1:il,1:jlm]+ vola[2:il+1,1:jlm])
uxe = 0.5* (u[2:il+1,1:jlm]+u[2:il+1,2:jlm+1]) - uavg
vxe = 0.5* (v[2:il+1,1:jlm]+v[2:il+1,2:jlm+1]) - vavg
uxw = uavg - 0.5* (u[0:il-1,1:jlm]+u[0:il-1,2:jlm+1])
vxw = vavg - 0.5* (v[0:il-1,1:jlm]+v[0:il-1,2:jlm+1])
vor2 = 0.5* (xye* volaei* uxe+ xyw* volawi* uxw)
vor3 = 0.5* (yye* volaei* vxe+ yyw* volawi* vxw)
vort = vor1- vor2- vor3
vor[1:il,1:jlm] = abs(vort)
utotal = uavg* uavg+ vavg* vavg
utot[1:il,1:jlm] = np.sqrt(utotal)
'''
Determine transition index
'''
itr1 = 0
itr2 = 0
j = 1
for i in range(0,il):
if (x[i,j,1] <= xtran):
itr1 = i - 1
break
itr1p = itr1 + 1
for i in range(itr1p-1,il):
if (x[i,j,1] >= xtran):
itr2 = i
break
for i in range(1,il):
avor = vor[i,0:jlm]
utot1 = utot[i,0:jlm]
jmaxv = np.argmax(avor)
if (jmaxv == 0):
jmaxv = 1
jminut = np.argmin(utot1)
jmaxut = np.argmax(utot1)
avorm[i] = avor[jmaxv]
utmin[i] = utot1[jminut]
utmax[i] = max(utot1[jmaxut],1.e-3)
utotm[i] = utmax[i]
yscal[i] = 1000000.
if (modbl == 1):
tur1 = 1.0
tur2 = 0.
tur3 = 0.
elif (modbl == 2):
tur1 = 0.
tur2 = 1.0
tur3 = 0.
else:
tur1 = 0.
tur2 = 0.
tur3 = 1.0
xxa = x[itlp-1:itu,0,0]- x[itlp-1:itu-1,0,0]
yxa = x[itlp-1:itu,0,1]- x[itlp-1:itu-1,0,1]
volai = 1.0/vola[itlp-1:itu,0]
uy = 2.0* u[itlp-1:itu,1]
amub = .5* (amu[itlp-1:itu,0]+ amu[itlp-1:itu,1])
tauw[itlp-1:itu] = amub* (xxa* uy)* volai
avor1 = vor[itlp-1:itu,0]
avora = avor1
avorb = 0.5* (avor1+ avorm[itlp-1:itu])
avorc = avorm[itlp-1:itu]
avor2 = tur1*avora + tur2*avorb + tur3*avorc
yscal[itlp-1:itu] = np.sqrt(rey* sgrmi* amub* avor2* w[itlp-1:itu,1,0])/(26.*amub)
'''
Compute normal distance ylen[i,j] and function 'yvor'
(yvor = y* vorticity)
'''
ylen[1:il,1] = 0.0
xc2 = .50* (x[1:il,1:jlm,0]+ x[0:il-1,1:jlm,0]-x[1:il,0:jlm-1,0]- x[0:il-1,0:jlm-1,0])
yc2 = .50* (x[1:il,1:jlm,1]+ x[0:il-1,1:jlm,1]-x[1:il,0:jlm-1,1]- x[0:il-1,0:jlm-1,1])
scalf = np.sqrt(np.square(xc2) + np.square(yc2))
ylen[1:il,1:jlm] = ylen[1:il,0:jlm-1]+ scalf
for i in range(1,il):
ylen1 = 0.5* ylen[i,1]
for j in range(0,int(np.floor(jstop))):
y1 = yscal[i]* ylen[i,j]
damp = 1.0- np.exp(-y1)
yvor[j] = ylen[i,j]* vor[i,j]* damp
jmaxyv = np.argmax(yvor)
jmaxyv = max(jmaxyv,2)
jedge[i] = jmaxyv
yvorm[i] = max(yvor[jmaxyv],1.e-6)
ylenm[i] = max(ylen[i,jmaxyv],ylen1)
if (jedge[i] < int(np.floor(jstop))):
ylenm1 = ylenm[i]
if (ncyc>=10 or restarr==1.0):
jmyv = int(jedge[i])
dyvm = yvor[jmyv]-yvor[jmyv-1]
dyvp = yvor[jmyv]-yvor[jmyv+1]
if (yvor[jmyv-1] < yvor[jmyv+1]):
ylenm[i] = ylen[i,jmyv]+ 0.5*(ylen[i,jmyv+1]- ylen[i,jmyv])*(1- dyvp/dyvm)
else:
if dyvp == 0.0:
dyvp = 0.00001
ylenm[i] = ylen[i,jmyv]- 0.5*(ylen[i,jmyv]- ylen[i,jmyv-1])*(1- dyvm/dyvp)
else:
ylenm[i] = ylenm1
'''
Compute outer eddy viscosity
'''
for i in range(1,il):
udiff = abs(utmax[i]- utmin[i])
udiff1 = cwk1* udiff
for j in range(1,int(np.floor(jstop))):
ravg[j] = 0.5* (w[i,j,0]+ w[i,j+1,0])
coeff = 0.0168* ccp
fwake1 = coeff* yvorm[i]* ylenm[i]
coeff2 = coeff* cwk1* cwk1
fwake2 = coeff2* ylenm[i]* udiff* udiff/yvorm[i]
fwake = min(fwake1,fwake2)
fkleb0 = ckleb* ylen[i,j]/ylenm[i]
fkleb1 = min(fkleb0,1.e5)
fkleb[j] = 1.0/(1.0+ 5.5* fkleb1**6)
amuto[j] = rey* sgrmi* ravg[j]* fwake* fkleb[j]
amuto[j] = abs(amuto[j])
amuto[1] = amuto[2]
'''
Compute inner eddy viscosity
'''
j=int(np.floor(jstop))
y1 = yscal[i]* ylen[i,1:j]
damp = 1.0- np.exp(-y1)
tscali = 0.4* ylen[i,1:j]* damp
amuti1 = tscali* tscali* vor[i,1:j]
amuti[1:j] = rey* sgrmi* ravg[1:j]* amuti1
amuti[1:j] = abs(amuti[1:j])
amuti[1] = 0.0
if (i<=itl or i>itu):
amuti[1] = amuti[2]
'''
Load viscosity coeffs. into array, use inner value until
match point is reached
'''
ivect = 1
if (ivect == 0):
icross = 0
amut[i,0] = amuti[0]
for j in range(1,int(np.floor(jstop))):
if (amuti[j]<=amuto[j] and icross==0):
amut[i,j] = amuti[j]
else:
icross = 1
amut[i,j] = amuto[j]
else:
amut[i,0] = amuti[0]
ystop = int(np.floor(jstop))
for j in range(0,int(np.floor(jstop))):
amudif = amuti[j]- amuto[j]
if (amudif >= 0):
fcros[j] = j
else:
fcros[j] = 1000
jcros = np.argmin(fcros)
if (jcros == 1):
jcros = 2
jcrosm = jcros- 1
amut[i,0:jcrosm] = amuti[0:jcrosm]
j = int(np.floor(jstop))
amut[i,jcros-1:j] = amuto[jcros-1:j]
'''
Compute turbulent viscosity at cell center
'''
j=int(np.floor(jstop))
amutc = 0.5* (amut[i,1:j]+ amut[i,0:j-1])
amu[i,1:j] = amutc
amut[i,1:j] = amu[i,1:j]
if (i>itr1 and i<=itr2):
amut[i,1:j] = 0.
'''
Copy amut to rev
'''
scale = 1.
rev[0:ie,0:je] = scale*amut[0:ie,0:je]
return
| [
"numpy.sqrt",
"numpy.ones",
"numpy.floor",
"numpy.argmax",
"numpy.square",
"numpy.exp",
"numpy.argmin"
] | [((1340, 1351), 'numpy.ones', 'np.ones', (['nx'], {}), '(nx)\n', (1347, 1351), True, 'import numpy as np\n'), ((1364, 1375), 'numpy.ones', 'np.ones', (['nx'], {}), '(nx)\n', (1371, 1375), True, 'import numpy as np\n'), ((1386, 1403), 'numpy.ones', 'np.ones', (['(nx, ny)'], {}), '((nx, ny))\n', (1393, 1403), True, 'import numpy as np\n'), ((1415, 1426), 'numpy.ones', 'np.ones', (['nx'], {}), '(nx)\n', (1422, 1426), True, 'import numpy as np\n'), ((1438, 1449), 'numpy.ones', 'np.ones', (['nx'], {}), '(nx)\n', (1445, 1449), True, 'import numpy as np\n'), ((1461, 1478), 'numpy.ones', 'np.ones', (['(nx, ny)'], {}), '((nx, ny))\n', (1468, 1478), True, 'import numpy as np\n'), ((1490, 1501), 'numpy.ones', 'np.ones', (['nx'], {}), '(nx)\n', (1497, 1501), True, 'import numpy as np\n'), ((1514, 1525), 'numpy.ones', 'np.ones', (['nx'], {}), '(nx)\n', (1521, 1525), True, 'import numpy as np\n'), ((1537, 1548), 'numpy.ones', 'np.ones', (['nx'], {}), '(nx)\n', (1544, 1548), True, 'import numpy as np\n'), ((1561, 1572), 'numpy.ones', 'np.ones', (['nx'], {}), '(nx)\n', (1568, 1572), True, 'import numpy as np\n'), ((1584, 1601), 'numpy.ones', 'np.ones', (['(nx, ny)'], {}), '((nx, ny))\n', (1591, 1601), True, 'import numpy as np\n'), ((1613, 1624), 'numpy.ones', 'np.ones', (['nx'], {}), '(nx)\n', (1620, 1624), True, 'import numpy as np\n'), ((1637, 1648), 'numpy.ones', 'np.ones', (['nx'], {}), '(nx)\n', (1644, 1648), True, 'import numpy as np\n'), ((1661, 1672), 'numpy.ones', 'np.ones', (['nx'], {}), '(nx)\n', (1668, 1672), True, 'import numpy as np\n'), ((1685, 1696), 'numpy.ones', 'np.ones', (['nx'], {}), '(nx)\n', (1692, 1696), True, 'import numpy as np\n'), ((1709, 1720), 'numpy.ones', 'np.ones', (['nx'], {}), '(nx)\n', (1716, 1720), True, 'import numpy as np\n'), ((1731, 1748), 'numpy.ones', 'np.ones', (['(nx, ny)'], {}), '((nx, ny))\n', (1738, 1748), True, 'import numpy as np\n'), ((1756, 1773), 'numpy.ones', 'np.ones', (['(nx, ny)'], {}), '((nx, ny))\n', (1763, 1773), True, 'import numpy as np\n'), ((1781, 1798), 'numpy.ones', 'np.ones', (['(nx, ny)'], {}), '((nx, ny))\n', (1788, 1798), True, 'import numpy as np\n'), ((1806, 1823), 'numpy.ones', 'np.ones', (['(nx, ny)'], {}), '((nx, ny))\n', (1813, 1823), True, 'import numpy as np\n'), ((1835, 1846), 'numpy.ones', 'np.ones', (['nx'], {}), '(nx)\n', (1842, 1846), True, 'import numpy as np\n'), ((1858, 1875), 'numpy.ones', 'np.ones', (['(nx, ny)'], {}), '((nx, ny))\n', (1865, 1875), True, 'import numpy as np\n'), ((1886, 1903), 'numpy.ones', 'np.ones', (['(nx, ny)'], {}), '((nx, ny))\n', (1893, 1903), True, 'import numpy as np\n'), ((1914, 1931), 'numpy.ones', 'np.ones', (['(nx, ny)'], {}), '((nx, ny))\n', (1921, 1931), True, 'import numpy as np\n'), ((1943, 1954), 'numpy.ones', 'np.ones', (['nx'], {}), '(nx)\n', (1950, 1954), True, 'import numpy as np\n'), ((2183, 2197), 'numpy.sqrt', 'np.sqrt', (['gamma'], {}), '(gamma)\n', (2190, 2197), True, 'import numpy as np\n'), ((3107, 3122), 'numpy.sqrt', 'np.sqrt', (['utotal'], {}), '(utotal)\n', (3114, 3122), True, 'import numpy as np\n'), ((4476, 4491), 'numpy.sqrt', 'np.sqrt', (['utotal'], {}), '(utotal)\n', (4483, 4491), True, 'import numpy as np\n'), ((4944, 4959), 'numpy.argmax', 'np.argmax', (['avor'], {}), '(avor)\n', (4953, 4959), True, 'import numpy as np\n'), ((5031, 5047), 'numpy.argmin', 'np.argmin', (['utot1'], {}), '(utot1)\n', (5040, 5047), True, 'import numpy as np\n'), ((5068, 5084), 'numpy.argmax', 'np.argmax', (['utot1'], {}), '(utot1)\n', (5077, 5084), True, 'import numpy as np\n'), ((6012, 6071), 'numpy.sqrt', 'np.sqrt', (['(rey * sgrmi * amub * avor2 * w[itlp - 1:itu, 1, 0])'], {}), '(rey * sgrmi * amub * avor2 * w[itlp - 1:itu, 1, 0])\n', (6019, 6071), True, 'import numpy as np\n'), ((6762, 6777), 'numpy.argmax', 'np.argmax', (['yvor'], {}), '(yvor)\n', (6771, 6777), True, 'import numpy as np\n'), ((6414, 6428), 'numpy.square', 'np.square', (['xc2'], {}), '(xc2)\n', (6423, 6428), True, 'import numpy as np\n'), ((6431, 6445), 'numpy.square', 'np.square', (['yc2'], {}), '(yc2)\n', (6440, 6445), True, 'import numpy as np\n'), ((8378, 8393), 'numpy.floor', 'np.floor', (['jstop'], {}), '(jstop)\n', (8386, 8393), True, 'import numpy as np\n'), ((8462, 8473), 'numpy.exp', 'np.exp', (['(-y1)'], {}), '(-y1)\n', (8468, 8473), True, 'import numpy as np\n'), ((9560, 9576), 'numpy.argmin', 'np.argmin', (['fcros'], {}), '(fcros)\n', (9569, 9576), True, 'import numpy as np\n'), ((9886, 9901), 'numpy.floor', 'np.floor', (['jstop'], {}), '(jstop)\n', (9894, 9901), True, 'import numpy as np\n'), ((6587, 6602), 'numpy.floor', 'np.floor', (['jstop'], {}), '(jstop)\n', (6595, 6602), True, 'import numpy as np\n'), ((6679, 6690), 'numpy.exp', 'np.exp', (['(-y1)'], {}), '(-y1)\n', (6685, 6690), True, 'import numpy as np\n'), ((6958, 6973), 'numpy.floor', 'np.floor', (['jstop'], {}), '(jstop)\n', (6966, 6973), True, 'import numpy as np\n'), ((7726, 7741), 'numpy.floor', 'np.floor', (['jstop'], {}), '(jstop)\n', (7734, 7741), True, 'import numpy as np\n'), ((9293, 9308), 'numpy.floor', 'np.floor', (['jstop'], {}), '(jstop)\n', (9301, 9308), True, 'import numpy as np\n'), ((9731, 9746), 'numpy.floor', 'np.floor', (['jstop'], {}), '(jstop)\n', (9739, 9746), True, 'import numpy as np\n'), ((9003, 9018), 'numpy.floor', 'np.floor', (['jstop'], {}), '(jstop)\n', (9011, 9018), True, 'import numpy as np\n'), ((9343, 9358), 'numpy.floor', 'np.floor', (['jstop'], {}), '(jstop)\n', (9351, 9358), True, 'import numpy as np\n')] |
import time
import cv2
import argparse
import numpy as np
import serial
# khoi tao bo dem
#open camera
cap = cv2.VideoCapture(0)
start = time.time()
#image = cv2.imread('199.jpg',1)
# Ham tra ve output layer
def get_output_layers(net):
layer_names = net.getLayerNames()
output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]
return output_layers
# Ham ve cac hinh chu nhat va ten class
def draw_prediction(img, class_id, confidence, x, y, x_plus_w, y_plus_h):
label = str(classes[class_id])
color = (0,0,0)
cv2.rectangle(img, (x, y), (x_plus_w, y_plus_h), color, 2)
cv2.putText(img, label, (x - 10, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)
# Doc ten cac class
classes = None
with open("objects.names", 'r') as f:
classes = [line.strip() for line in f.readlines()]
COLORS = np.random.uniform(0, 255, size=(len(classes), 3))
print("load modelll")
net = cv2.dnn.readNet("yolov3.weights","yolov3.cfg")
while (True):
# Doc frame
ret, image = cap.read()
end = time.time()
timer = end - start
# Loc cac object trong khung hinh
class_ids = []
confidences = []
boxes = []
conf_threshold = 0.1
nms_threshold = 0.1
if timer >= 1.0 :
# Resize
Width = image.shape[1]
Height = image.shape[0]
scale = 0.00392
blob = cv2.dnn.blobFromImage(image, scale, (416, 416), (0, 0, 0), True, crop=False)
net.setInput(blob)
outs = net.forward(get_output_layers(net))
# Th?c hi?n xác d?nh b?ng HOG và SVM
for out in outs:
for detection in out:
scores = detection[5:]
class_id = np.argmax(scores)
confidence = scores[class_id]
if confidence > conf_threshold:
center_x = int(detection[0] * Width)
center_y = int(detection[1] * Height)
w = int(detection[2] * Width)
h = int(detection[3] * Height)
x = center_x - w / 2
y = center_y - h / 2
class_ids.append(class_id)
confidences.append(float(confidence))
boxes.append([x, y, w, h])
indices = cv2.dnn.NMSBoxes(boxes, confidences, conf_threshold, nms_threshold)
# Ve cac khung chu nhat quanh doi tuong
for i in indices:
i = i[0]
box = boxes[i]
x = box[0]
y = box[1]
w = box[2]
h = box[3]
draw_prediction(image, class_ids[i], confidences[i], round(x), round(y), round(x + w), round(y + h))
cv2.imshow("object detection", image)
print("YOLO Execution time: ", timer)
if cv2.waitKey(1)== 32:
break
cap.stop()
cv2.destroyAllWindows()
| [
"cv2.rectangle",
"cv2.dnn.blobFromImage",
"numpy.argmax",
"cv2.putText",
"cv2.imshow",
"cv2.waitKey",
"cv2.destroyAllWindows",
"cv2.VideoCapture",
"cv2.dnn.NMSBoxes",
"time.time",
"cv2.dnn.readNet"
] | [((112, 131), 'cv2.VideoCapture', 'cv2.VideoCapture', (['(0)'], {}), '(0)\n', (128, 131), False, 'import cv2\n'), ((140, 151), 'time.time', 'time.time', ([], {}), '()\n', (149, 151), False, 'import time\n'), ((947, 994), 'cv2.dnn.readNet', 'cv2.dnn.readNet', (['"""yolov3.weights"""', '"""yolov3.cfg"""'], {}), "('yolov3.weights', 'yolov3.cfg')\n", (962, 994), False, 'import cv2\n'), ((2997, 3020), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (3018, 3020), False, 'import cv2\n'), ((567, 625), 'cv2.rectangle', 'cv2.rectangle', (['img', '(x, y)', '(x_plus_w, y_plus_h)', 'color', '(2)'], {}), '(img, (x, y), (x_plus_w, y_plus_h), color, 2)\n', (580, 625), False, 'import cv2\n'), ((631, 717), 'cv2.putText', 'cv2.putText', (['img', 'label', '(x - 10, y - 10)', 'cv2.FONT_HERSHEY_SIMPLEX', '(0.5)', 'color', '(2)'], {}), '(img, label, (x - 10, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5,\n color, 2)\n', (642, 717), False, 'import cv2\n'), ((1067, 1078), 'time.time', 'time.time', ([], {}), '()\n', (1076, 1078), False, 'import time\n'), ((2862, 2899), 'cv2.imshow', 'cv2.imshow', (['"""object detection"""', 'image'], {}), "('object detection', image)\n", (2872, 2899), False, 'import cv2\n'), ((1387, 1463), 'cv2.dnn.blobFromImage', 'cv2.dnn.blobFromImage', (['image', 'scale', '(416, 416)', '(0, 0, 0)', '(True)'], {'crop': '(False)'}), '(image, scale, (416, 416), (0, 0, 0), True, crop=False)\n', (1408, 1463), False, 'import cv2\n'), ((2389, 2456), 'cv2.dnn.NMSBoxes', 'cv2.dnn.NMSBoxes', (['boxes', 'confidences', 'conf_threshold', 'nms_threshold'], {}), '(boxes, confidences, conf_threshold, nms_threshold)\n', (2405, 2456), False, 'import cv2\n'), ((2949, 2963), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (2960, 2963), False, 'import cv2\n'), ((1743, 1760), 'numpy.argmax', 'np.argmax', (['scores'], {}), '(scores)\n', (1752, 1760), True, 'import numpy as np\n')] |
# -*- coding: utf-8 -*-
import numpy as np
from skimage.util import img_as_float
from skimage.segmentation import slic
from skimage.io import imread
import os
from salientdetect.detector import calc_saliency_score
def _load_dist_mat():
npy_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "color_dist.npy")
return np.load(npy_path)
DIST_MAT = _load_dist_mat()
def saliency_score(path):
img = imread(path)
return saliency_score_from_ndarry(img)
def saliency_score_from_ndarry(img):
segment_labels = slic(img_as_float(img), n_segments=20, compactness=20, sigma=2.0)
return calc_saliency_score(img, segment_labels, DIST_MAT)
| [
"skimage.util.img_as_float",
"salientdetect.detector.calc_saliency_score",
"skimage.io.imread",
"os.path.abspath",
"numpy.load"
] | [((339, 356), 'numpy.load', 'np.load', (['npy_path'], {}), '(npy_path)\n', (346, 356), True, 'import numpy as np\n'), ((424, 436), 'skimage.io.imread', 'imread', (['path'], {}), '(path)\n', (430, 436), False, 'from skimage.io import imread\n'), ((617, 667), 'salientdetect.detector.calc_saliency_score', 'calc_saliency_score', (['img', 'segment_labels', 'DIST_MAT'], {}), '(img, segment_labels, DIST_MAT)\n', (636, 667), False, 'from salientdetect.detector import calc_saliency_score\n'), ((545, 562), 'skimage.util.img_as_float', 'img_as_float', (['img'], {}), '(img)\n', (557, 562), False, 'from skimage.util import img_as_float\n'), ((282, 307), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (297, 307), False, 'import os\n')] |
import numpy as np
from .lanczos import lanczos_resample_three, lanczos_resample_one
def invert_affine_transform_wcs(u, v, wcs):
"""Invert a galsim.AffineTransform WCS.
The AffineTransform WCS forward model is
[u, v] = Jac * ([x, y] - origin) + world_origin
where the `*` is a matrix multiplication and `[u, v]` is a column
vector, etc.
Parameters
----------
u : np.ndarray
The first world coordinate value.
v : np.ndarray
The second world coordinate value.
wcs : galsim.AffineTransform
The AffineTransform WCS object to invert.
Returns
-------
x : np.ndarray
The first image coordinate value.
y : np.ndarray
The second image coordinate value.
"""
invmat = np.linalg.inv(
np.array([[wcs.dudx, wcs.dudy], [wcs.dvdx, wcs.dvdy]]))
du = u - wcs.u0
dv = v - wcs.v0
x = invmat[0, 0] * du + invmat[0, 1] * dv + wcs.x0
y = invmat[1, 0] * du + invmat[1, 1] * dv + wcs.y0
return x, y
def coadd_image_noise_interpfrac(
se_images, se_noises, se_interp_fracs, se_wcs_objs,
coadd_wgts, coadd_scale, coadd_dim):
"""Coadd a set of SE images, noise fields, and interpolation fractions.
Parameters
----------
se_images : list of np.ndarray
The list of SE images to coadd.
se_noises : list of np.ndarray
The list of SE noise images to coadd.
se_interp_fracs : list of np.ndarray
The list of SE interpolated fraction images to coadd.
se_wcs_objs : list of galsim.BaseWCS or children
The WCS objects for each of the SE images.
coadd_wgts : 1d array-like object of floats
The relative coaddng weights for each of the SE images.
coadd_scale : float
The pixel scale of desired coadded image.
coadd_dim : int
The number of pixels desired for the final coadd image..
Returns
-------
img : np.ndarray, shape (coadd_dim, coadd_dim)
The coadd image.
nse : np.ndarray, shape (coadd_dim, coadd_dim)
The coadd noise image.
intp : np.ndarray, shape (coadd_dim, coadd_dim)
The interpolated flux fraction in each coadd pixel.
"""
# coadd pixel coords
y, x = np.mgrid[0:coadd_dim, 0:coadd_dim]
u = x.ravel() * coadd_scale
v = y.ravel() * coadd_scale
coadd_image = np.zeros((coadd_dim, coadd_dim), dtype=np.float64)
coadd_noise = np.zeros((coadd_dim, coadd_dim), dtype=np.float64)
coadd_intp = np.zeros((coadd_dim, coadd_dim), dtype=np.float32)
wgts = coadd_wgts / np.sum(coadd_wgts)
for se_im, se_nse, se_intp, se_wcs, wgt in zip(
se_images, se_noises, se_interp_fracs, se_wcs_objs, wgts):
se_x, se_y = invert_affine_transform_wcs(u, v, se_wcs)
im, nse, intp, _ = lanczos_resample_three(
se_im / se_wcs.pixelArea(),
se_nse / se_wcs.pixelArea(),
se_intp,
se_y,
se_x)
coadd_image += (im.reshape((coadd_dim, coadd_dim)) * wgt)
coadd_noise += (nse.reshape((coadd_dim, coadd_dim)) * wgt)
coadd_intp += (intp.reshape((coadd_dim, coadd_dim)) * wgt)
coadd_image *= (coadd_scale**2)
coadd_noise *= (coadd_scale**2)
return coadd_image, coadd_noise, coadd_intp
def coadd_psfs(
se_psfs, se_wcs_objs, coadd_wgts,
coadd_scale, coadd_dim, coadd_offset, se_offsets):
"""Coadd the PSFs.
Parameters
----------
se_psfs : list of np.ndarray
The list of SE PSF images to coadd.
se_wcs_objs : list of galsim.BaseWCS or children
The WCS objects for each of the SE PSFs.
coadd_wgts : 1d array-like object of floats
The relative coaddng weights for each of the SE PSFs.
coadd_scale : float
The pixel scale of desired coadded PSF image.
coadd_dim : int
The number of pixels desired for the final coadd PSF.
coadd_offset : float
The offset in pixels of the start of the coadd PSF image stamp.
se_offsets : list of tuples of floats
The offset in the SE image coords of the start of the SE PSF
image.
Returns
-------
psf : np.ndarray
The coadded PSF image.
"""
# coadd pixel coords
y, x = np.mgrid[0:coadd_dim, 0:coadd_dim]
u = (coadd_offset + x.ravel()) * coadd_scale
v = (coadd_offset + y.ravel()) * coadd_scale
coadd_image = np.zeros((coadd_dim, coadd_dim), dtype=np.float64)
wgts = coadd_wgts / np.sum(coadd_wgts)
for se_psf, se_wcs, wgt, se_offset in zip(
se_psfs, se_wcs_objs, wgts, se_offsets):
se_x, se_y = invert_affine_transform_wcs(u, v, se_wcs)
se_x -= se_offset[0]
se_y -= se_offset[1]
im, _ = lanczos_resample_one(se_psf / se_wcs.pixelArea(), se_y, se_x)
coadd_image += (im.reshape((coadd_dim, coadd_dim)) * wgt)
coadd_image *= (coadd_scale**2)
return coadd_image
| [
"numpy.array",
"numpy.zeros",
"numpy.sum"
] | [((2358, 2408), 'numpy.zeros', 'np.zeros', (['(coadd_dim, coadd_dim)'], {'dtype': 'np.float64'}), '((coadd_dim, coadd_dim), dtype=np.float64)\n', (2366, 2408), True, 'import numpy as np\n'), ((2427, 2477), 'numpy.zeros', 'np.zeros', (['(coadd_dim, coadd_dim)'], {'dtype': 'np.float64'}), '((coadd_dim, coadd_dim), dtype=np.float64)\n', (2435, 2477), True, 'import numpy as np\n'), ((2495, 2545), 'numpy.zeros', 'np.zeros', (['(coadd_dim, coadd_dim)'], {'dtype': 'np.float32'}), '((coadd_dim, coadd_dim), dtype=np.float32)\n', (2503, 2545), True, 'import numpy as np\n'), ((4409, 4459), 'numpy.zeros', 'np.zeros', (['(coadd_dim, coadd_dim)'], {'dtype': 'np.float64'}), '((coadd_dim, coadd_dim), dtype=np.float64)\n', (4417, 4459), True, 'import numpy as np\n'), ((796, 850), 'numpy.array', 'np.array', (['[[wcs.dudx, wcs.dudy], [wcs.dvdx, wcs.dvdy]]'], {}), '([[wcs.dudx, wcs.dudy], [wcs.dvdx, wcs.dvdy]])\n', (804, 850), True, 'import numpy as np\n'), ((2571, 2589), 'numpy.sum', 'np.sum', (['coadd_wgts'], {}), '(coadd_wgts)\n', (2577, 2589), True, 'import numpy as np\n'), ((4485, 4503), 'numpy.sum', 'np.sum', (['coadd_wgts'], {}), '(coadd_wgts)\n', (4491, 4503), True, 'import numpy as np\n')] |
import unittest
from mock import Mock
from records_mover.records.schema.field.numpy import details_from_numpy_dtype
import numpy as np
class TestNumpy(unittest.TestCase):
def test_details_from_numpy_dtype(self):
tests = {
np.dtype(str): 'string',
np.dtype(int): 'integer',
np.dtype(np.datetime64): 'datetime',
}
for dtype, expected_field_type in tests.items():
mock_unique = Mock(name='unique')
actual_field_type, actual_constraints = details_from_numpy_dtype(dtype=dtype,
unique=mock_unique)
self.assertEqual(actual_field_type, expected_field_type)
| [
"mock.Mock",
"numpy.dtype",
"records_mover.records.schema.field.numpy.details_from_numpy_dtype"
] | [((248, 261), 'numpy.dtype', 'np.dtype', (['str'], {}), '(str)\n', (256, 261), True, 'import numpy as np\n'), ((285, 298), 'numpy.dtype', 'np.dtype', (['int'], {}), '(int)\n', (293, 298), True, 'import numpy as np\n'), ((323, 346), 'numpy.dtype', 'np.dtype', (['np.datetime64'], {}), '(np.datetime64)\n', (331, 346), True, 'import numpy as np\n'), ((453, 472), 'mock.Mock', 'Mock', ([], {'name': '"""unique"""'}), "(name='unique')\n", (457, 472), False, 'from mock import Mock\n'), ((525, 582), 'records_mover.records.schema.field.numpy.details_from_numpy_dtype', 'details_from_numpy_dtype', ([], {'dtype': 'dtype', 'unique': 'mock_unique'}), '(dtype=dtype, unique=mock_unique)\n', (549, 582), False, 'from records_mover.records.schema.field.numpy import details_from_numpy_dtype\n')] |
from typing import Union
import numpy as np
from gmhazard_calc import gm_data
from .SiteInfo import SiteInfo
from qcore.geo import closest_location
def get_site_from_coords(
ensemble: Union[str, gm_data.Ensemble],
lat: float,
lon: float,
user_vs30: float = None,
):
"""Returns a SiteInfo for the
snapped location of the specified coordinates
Parameters
----------
ensemble: Ensemble
lat: float
Latitude
lon: float
Longitude
user_vs30: float
A user specified vs30, which potentially differs from the one used
Returns
-------
SiteInfo
Corresponding to the snapped location
float
Distance of the snapped location from the specified location
"""
if isinstance(ensemble, str):
ensemble = gm_data.Ensemble(ensemble)
# Get the closest station
i, d = closest_location(
np.vstack((ensemble.stations.lon.values, ensemble.stations.lat.values)).T,
lon,
lat,
)
return (
get_site_from_name(
ensemble, ensemble.stations.index.values[i], user_vs30=user_vs30
),
d,
)
def get_site_from_name(
ensemble: Union[str, gm_data.Ensemble],
station_name: str,
user_vs30: float = None,
):
"""Returns a SiteInfo for the specified station
Parameters
----------
ensemble: Ensemble
station_name: str
user_vs30: float, optional
A user specified vs30, which potentially differs from the one used
Returns
-------
SiteInfo
"""
if isinstance(ensemble, str):
ensemble = gm_data.Ensemble(ensemble)
# Check the specified station is in the ensemble
if station_name not in ensemble.stations.index.values:
raise ValueError(
f"The station name {station_name} is not a valid "
f"station for ensemble {ensemble.name}."
)
# Get the db vs30 value for the specified station_name
db_vs30 = (
ensemble.vs30_df.loc[station_name, "vs30"]
if ensemble.vs30_df is not None
else None
)
# Get the Z values for the specified station_name
z1p0 = (
ensemble.z_df.loc[station_name, "Z1.0"]
if ensemble.z_df is not None and station_name in ensemble.z_df.index
else None
)
z2p5 = (
ensemble.z_df.loc[station_name, "Z2.5"]
if ensemble.z_df is not None and station_name in ensemble.z_df.index
else None
)
mask = ensemble.stations.index.values == station_name
lat = ensemble.stations.lat.values[mask][0]
lon = ensemble.stations.lon.values[mask][0]
return SiteInfo(
station_name, lat, lon, db_vs30, user_vs30=user_vs30, z1p0=z1p0, z2p5=z2p5
)
| [
"gmhazard_calc.gm_data.Ensemble",
"numpy.vstack"
] | [((809, 835), 'gmhazard_calc.gm_data.Ensemble', 'gm_data.Ensemble', (['ensemble'], {}), '(ensemble)\n', (825, 835), False, 'from gmhazard_calc import gm_data\n'), ((1616, 1642), 'gmhazard_calc.gm_data.Ensemble', 'gm_data.Ensemble', (['ensemble'], {}), '(ensemble)\n', (1632, 1642), False, 'from gmhazard_calc import gm_data\n'), ((904, 975), 'numpy.vstack', 'np.vstack', (['(ensemble.stations.lon.values, ensemble.stations.lat.values)'], {}), '((ensemble.stations.lon.values, ensemble.stations.lat.values))\n', (913, 975), True, 'import numpy as np\n')] |
# -*- coding: utf-8 -*-
#!/usr/bin/env python
#######################################################################
##### #####
##### <NAME> #####
##### <EMAIL> #####
##### 09/27/2018 #####
##### LABIO - PUCRS #####
##### Real-time ,Color tracking and matchesTheshold #####
##### #####
#######################################################################
# import the necessary packages
from picamera.array import PiRGBArray
from picamera import PiCamera
from contextlib import contextmanager
from tkinter import *
import time
import os
import pygame
import sys
import itertools as it
import numpy as np
import cv2 as cv
import cv2
import matplotlib.pyplot as plt
# R G B
WHITE = (255, 255, 255)
BLACK = ( 0, 0, 0)
BRIGHTRED = (255, 0, 0)
RED = (255, 0, 0)
BRIGHTGREEN = ( 0, 255, 0)
GREEN = ( 0, 155, 0)
BRIGHTBLUE = ( 0, 0, 255)
BLUE = ( 0, 0, 155)
BRIGHTYELLOW = (255, 255, 0)
YELLOW = (155, 155, 0)
DARKGRAY = ( 40, 40, 40)
# define range of red color in HSV
#lower_red = np.array([150, 30, 30])
#upper_red = np.array([200, 255, 255])
#lower_red = np.array([151, 136, 91]) #calib 25092018
#upper_red = np.array([179, 255, 255]) #calib 25092018
lower_red = np.array([172, 61, 57]) #calib 26092018
upper_red = np.array([179, 255, 255]) #calib 26092018
# define range of blue color in HSV
#lower_blue = np.array([112,173,60]) #calib 24092018
#upper_blue = np.array([128,255,214]) #calib 24092018
lower_blue = np.array([111,131,54]) #calib 26092018
upper_blue = np.array([140,255,255]) #calib 26092018
#lower_blue = np.array([115,150,80])
#upper_blue = np.array([125,255,255])
# define range of yellow color in HSV
lower_yellow = np.array([10,100,100])
upper_yellow = np.array([40,255,255])
#lower_yellow = np.array([17,150,194]) #calib 25092018
#upper_yellow = np.array([28,255,255]) #calib 25092018
# define range of gray color in HSV
lower_gray = np.array([106, 47, 66])
upper_gray = np.array([114, 78, 255])
#lower_gray = np.array([98, 90, 30]) #calib 26092018
#upper_gray = np.array([108, 220, 255]) #calib 26092018
#lower_gray = np.array([120, 15, 40])
#upper_gray = np.array([255, 90, 128])
PY3 = sys.version_info[0] == 3
if PY3:
xrange = range
################### interface ###################
'''
class Application:
def __init__(self, master=None):
pygame.mixer.init()
pygame.mixer.music.load("ini_software.mp3")
pygame.mixer.music.play()
self.widget1 = Frame(master)
self.widget1.pack(side=RIGHT)
self.msg = Label(self.widget1, text="Iniciar Software ?")
self.msg["font"] = ("Verdana", "12", "italic", "bold")
self.msg.pack ()
self.sair = Button(self.widget1)
self.sair["text"] = "Sim"
self.sair["font"] = ("Verdana", "10")
self.sair["width"] = 15
self.sair["command"] = self.widget1.quit
self.sair.pack (side=RIGHT)
self.msg.pack ()
self.sair = Button(self.widget1)
self.sair["text"] = "Nao"
self.sair["font"] = ("Verdana", "10")
self.sair["width"] = 15
self.sair["command"] = self.widget1.quit
self.sair.pack (side=RIGHT)
root = Tk()
Application(root)
root.mainloop()
# audio payback test
pygame.mixer.init()
pygame.mixer.music.load("welcome_demolidor.mp3")
pygame.mixer.music.play()
'''
class Application:
def __init__(self, master=None):
self.fontePadrao = ("Arial", "10")
self.primeiroContainer = Frame(master)
self.primeiroContainer["pady"] = 10
self.primeiroContainer.pack()
self.segundoContainer = Frame(master)
self.segundoContainer["padx"] = 20
self.segundoContainer.pack()
self.terceiroContainer = Frame(master)
self.terceiroContainer["padx"] = 20
self.terceiroContainer.pack()
self.quartoContainer = Frame(master)
self.quartoContainer["pady"] = 20
self.quartoContainer.pack()
self.titulo = Label(self.primeiroContainer, text="Dados do usuário")
self.titulo["font"] = ("Arial", "10", "bold")
self.titulo.pack()
self.nomeLabel = Label(self.segundoContainer,text="Nome", font=self.fontePadrao)
self.nomeLabel.pack(side=LEFT)
self.nome = Entry(self.segundoContainer)
self.nome["width"] = 30
self.nome["font"] = self.fontePadrao
self.nome.pack(side=LEFT)
self.senhaLabel = Label(self.terceiroContainer, text="Senha", font=self.fontePadrao)
self.senhaLabel.pack(side=LEFT)
self.senha = Entry(self.terceiroContainer)
self.senha["width"] = 30
self.senha["font"] = self.fontePadrao
self.senha["show"] = "*"
self.senha.pack(side=LEFT)
self.autenticar = Button(self.quartoContainer)
self.autenticar["text"] = "Autenticar"
self.autenticar["font"] = ("Calibri", "8")
self.autenticar["width"] = 12
self.autenticar["command"] = self.verificaSenha
self.autenticar.pack()
self.mensagem = Label(self.quartoContainer, text="", font=self.fontePadrao)
self.mensagem.pack()
#Método verificar senha
def verificaSenha(self):
usuario = self.nome.get()
senha = self.senha.get()
if usuario == "labio" and senha == "<PASSWORD>":
self.mensagem["text"] = "Autenticado"
else:
self.mensagem["text"] = "Erro na autenticação"
root = Tk()
Application(root)
root.mainloop()
################### end interface ###################
# initialize the camera and grab a reference to the raw camera capture
camera = PiCamera()
camera.resolution = (640, 480)
camera.framerate = 32
rawCapture = PiRGBArray(camera, size=(640, 480))
sift = cv2.xfeatures2d.SIFT_create()
surf = cv2.xfeatures2d.SURF_create()
##### teste 26092018 ###########
cv2.ocl.setUseOpenCL(False)
CV_LOAD_IMAGE_COLOR = 1
subsamplingRatio = 0.5
matchesTheshold = 0.5
orb = cv2.ORB_create()
bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)
##### teste 26092018 ###########
img = cv2.imread('/home/pi/image.jpg',1)
#img = cv2.imread('/home/pi/image_editada.jpg',1)
orb = cv2.ORB_create()
#detector = cv2.SIFT()
#extrator = cv2.DescriptorExtrator_create("SIFT")
#detector = cv2.FeatureDetector_create("SIFT")
# allow the camera to warmup
time.sleep(0.1)
#r,h,c,w = 120,85,45,60
r,h,c,w = 250,90,500,125
rr,hr,cr,wr = 60,90,500,125
ry,hy,cy,wy = 120,120,45,200
rg,hg,cg,wg = 120,80,120,80
track_window = (c,r,w,h)
track_window_red = (cr,rr,wr,hr)
track_window_yellow = (cy,ry,wy,hy)
track_window_gray = (cg,rg,wg,hg)
# capture frames from the camera
for frame in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True):
# grab the raw NumPy array representing the image, then initialize the timestamp
# and occupied/unoccupied text
image = frame.array
ret = image
ret_red = image
ret_yellow = image
ret_gray = image
kp1, des1 = orb.detectAndCompute(img, None)
kp2, des2 = orb.detectAndCompute(image, None)
bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)
matches = bf.match(des1, des2)
matches = sorted(matches, key = lambda x:x.distance)
# apply ratio test
good = []
'''for m,n in matches:
if m.distance < 0.75*n.distance:
good.append([m])
'''
img3 = cv2.drawMatches(img, kp1, image, kp2, matches[:15], None, flags=2)
# ROI image
roi = image[r:r+h, c:c+w]
roi_red = image[rr:rr+hr, cr:cr+wr]
roi_yellow = image[ry:ry+hy, cy:cy+wy]
roi_gray = image[rg:rg+hg, cg:cg+wg]
# Convert BGR to HSV
hsv_blue = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
hsv_red = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
hsv_yellow = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
hsv_gray = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
# Threshold the HSV image
mask_blue = cv2.inRange(hsv_blue, lower_blue, upper_blue,) # Threshold the HSV image to get only blue colors
mask_red = cv2.inRange(hsv_red, lower_red, upper_red,) # Threshold the HSV image to get only red colors
mask_yellow = cv2.inRange(hsv_yellow, lower_yellow, upper_yellow,) # Threshold the HSV image to get only red colors
mask_gray = cv2.inRange(hsv_gray, lower_gray, upper_gray,) # Threshold the HSV image to get only red colors
# Bitwise-AND mask and original image
res_blue = cv2.bitwise_and(image,image, mask= mask_blue)
res_red = cv2.bitwise_and(image,image, mask= mask_red)
res_yellow = cv2.bitwise_and(image,image, mask= mask_yellow)
res_gray = cv2.bitwise_and(image,image, mask= mask_gray)
# Convert BGR to HSV
hsv_roi = cv2.cvtColor(res_blue, cv2.COLOR_BGR2HSV)
hsv_roi_red = cv2.cvtColor(res_red, cv2.COLOR_BGR2HSV) ### teste
hsv_roi_yellow = cv2.cvtColor(res_yellow, cv2.COLOR_BGR2HSV) ### teste
hsv_roi_gray = cv2.cvtColor(res_gray, cv2.COLOR_BGR2HSV) ### teste
####################### Blue ####################
roi_hist = cv2.calcHist([hsv_roi],[0],mask_blue,[180],[0,180])
cv2.normalize(roi_hist,roi_hist,0,255,cv2.NORM_MINMAX)
####################### Blue ####################
####################### RED #####################
roi_hist_red = cv2.calcHist([hsv_roi_red],[0],mask_red,[180],[0,255])
cv2.normalize(roi_hist_red,roi_hist_red,0,255,cv2.NORM_MINMAX)
####################### RED #####################
####################### YELLOW ##################
roi_hist_yellow = cv2.calcHist([hsv_roi_yellow],[0],mask_yellow,[180],[0,180])
cv2.normalize(roi_hist_yellow,roi_hist_yellow,0,255,cv2.NORM_MINMAX)
####################### YELLOW ##################
####################### GRAY ####################
roi_hist_gray = cv2.calcHist([hsv_roi_gray],[0],mask_gray,[180],[0,180])
cv2.normalize(roi_hist_gray,roi_hist_gray,0,180,cv2.NORM_MINMAX)
####################### GRAY ####################
# Setup the termination criteria, either 10 iteration or move by atleast 1 pt
term_crit = ( cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 1)
dst = cv2.calcBackProject([hsv_blue],[0],roi_hist,[0,180],100)
#dst_red = cv2.calcBackProject([hsv_red],[0],roi_hist,[0,255],5)
dst_red = cv2.calcBackProject([hsv_red],[0],roi_hist_red,[0,255],100)
dst_yellow = cv2.calcBackProject([hsv_yellow],[0],roi_hist_yellow,[0,255],5)#########
dst_gray = cv2.calcBackProject([hsv_gray],[0],roi_hist_gray,[0,255],5)#########
te = cv2.findContours(mask_blue.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
'''
cv2.drawContours(ret, te, (255,0,0),3)
for i in range(len(te)):
xx,yy,ww,hh=cv2.boundingRect(conts[i])
cv2.rectangle(ret, (xx,yy), (xx+ww,yy+hh), (0,0,255),2)
'''
# Draw it on images
x,y,w,h = track_window
xr,yr,wr,hr = track_window_red
xy,yy,wy,hy = track_window_yellow
xg,yg,wg,hg = track_window_gray
font = cv2.FONT_HERSHEY_SIMPLEX
#apply meanshift to get the new location
ret, track_window = cv2.meanShift(dst, track_window, term_crit)
ret, track_window_red = cv2.meanShift(dst_red, track_window_red, term_crit)#########
ret, track_window_yellow = cv2.meanShift(dst_yellow, track_window_yellow, term_crit)#########
ret, track_window_gray = cv2.meanShift(dst_gray, track_window_gray, term_crit)#########
#circles = cv.HoughCircles(image, cv.HOUGH_GRADIENT, 1, 10, np.array([]), 100, 30, 1, 30)
img2 = cv2.rectangle(image, (x,y), (x+w,y+h), 255,2) # largura da linha e cor
img2 = cv2.rectangle(res_blue, (x,y), (x+w,y+h), (255,0,0), 2) # largura da linha e cor
img2 = cv2.putText(res_blue, 'Nitrogen', (x,y), font, 0.9, (255,0), 2)
img5 = cv2.rectangle(image, (x,y), (x+w,y+h), 255,2) # largura da linha e cor
img5 = cv2.rectangle(res_red, (xr,yr), (xr+wr,yr+hr), (0,0,255),2) # largura da linha e cor
img5 = cv2.putText(res_red, 'Oxygen', (xr,yr), font, 0.9, (0,0,255), 2)
img6 = cv2.rectangle(image, (x,y), (x+w,y+h), 255,2) # largura da linha e cor
img6 = cv2.rectangle(res_yellow, (xy,yy), (xy+wy,yy+hy), (40,255,255),2) # largura da linha e cor
img6 = cv2.putText(res_yellow, 'Phosphorus', (xy,yy), font, 0.9, (40,255,255), 2)
img7 = cv2.rectangle(image, (x,y), (x+w,y+h), 255,2) # largura da linha e cor
img7 = cv2.rectangle(res_gray, (xg,yg), (xg+wg,yg+hg), DARKGRAY, 2) # largura da linha e cor
img7 = cv2.putText(res_gray, 'Carbon', (xg,yg), font, 0.9, DARKGRAY, 2)
#########################################################################################
img4 = cv2.rectangle(image, (x,y), (x+w,y+h), 255,2) # testando impressao da mask
img4 = cv2.putText(image, 'Nitrogen', (x,y), font, 0.9, (255,0), 2)
img4 = cv2.rectangle(image, (xr,yr), (xr+wr,yr+hr), (0,0,255),2) # largura da linha e cor
img4 = cv2.putText(image, 'Oxygen', (xr,yr), font, 0.9, (0,0,255), 2)
img4 = cv2.rectangle(image, (xy,yy), (xy+wy,yy+hy), (40,255,255),2) # largura da linha e cor
img4 = cv2.putText(image, 'Phosphorus', (xy,yy), font, 0.9, (40,255,255), 2)
img4 = cv2.rectangle(image, (xg,yg), (xg+wg,yg+hg), WHITE, 2) # largura da linha e cor
img4 = cv2.putText(image, 'Carbon', (xg,yg), font, 0.9, WHITE, 2)
#########################################################################################
# show the frame
cv2.imshow('Real image', img4)
cv2.imshow('GRAY',res_gray)
cv2.imshow('RED',res_red)
cv2.imshow('BLUE',res_blue)
cv2.imshow('YELLOW',res_yellow)
cv2.imshow('matches', img3)
#cv2.imshow('res_red',res_red)
key = cv2.waitKey(1) & 0xFF
# clear the stream in preparation for the next frame
rawCapture.truncate(0)
# if the `q` key was pressed, break from the loop
if key == ord("q"):
break
| [
"cv2.rectangle",
"cv2.BFMatcher",
"cv2.normalize",
"time.sleep",
"cv2.imshow",
"numpy.array",
"cv2.xfeatures2d.SIFT_create",
"cv2.ocl.setUseOpenCL",
"cv2.calcHist",
"cv2.calcBackProject",
"cv2.xfeatures2d.SURF_create",
"cv2.ORB_create",
"picamera.array.PiRGBArray",
"cv2.waitKey",
"cv2.me... | [((1590, 1613), 'numpy.array', 'np.array', (['[172, 61, 57]'], {}), '([172, 61, 57])\n', (1598, 1613), True, 'import numpy as np\n'), ((1648, 1673), 'numpy.array', 'np.array', (['[179, 255, 255]'], {}), '([179, 255, 255])\n', (1656, 1673), True, 'import numpy as np\n'), ((1858, 1882), 'numpy.array', 'np.array', (['[111, 131, 54]'], {}), '([111, 131, 54])\n', (1866, 1882), True, 'import numpy as np\n'), ((1915, 1940), 'numpy.array', 'np.array', (['[140, 255, 255]'], {}), '([140, 255, 255])\n', (1923, 1940), True, 'import numpy as np\n'), ((2091, 2115), 'numpy.array', 'np.array', (['[10, 100, 100]'], {}), '([10, 100, 100])\n', (2099, 2115), True, 'import numpy as np\n'), ((2129, 2153), 'numpy.array', 'np.array', (['[40, 255, 255]'], {}), '([40, 255, 255])\n', (2137, 2153), True, 'import numpy as np\n'), ((2318, 2341), 'numpy.array', 'np.array', (['[106, 47, 66]'], {}), '([106, 47, 66])\n', (2326, 2341), True, 'import numpy as np\n'), ((2355, 2379), 'numpy.array', 'np.array', (['[114, 78, 255]'], {}), '([114, 78, 255])\n', (2363, 2379), True, 'import numpy as np\n'), ((6108, 6118), 'picamera.PiCamera', 'PiCamera', ([], {}), '()\n', (6116, 6118), False, 'from picamera import PiCamera\n'), ((6185, 6220), 'picamera.array.PiRGBArray', 'PiRGBArray', (['camera'], {'size': '(640, 480)'}), '(camera, size=(640, 480))\n', (6195, 6220), False, 'from picamera.array import PiRGBArray\n'), ((6229, 6258), 'cv2.xfeatures2d.SIFT_create', 'cv2.xfeatures2d.SIFT_create', ([], {}), '()\n', (6256, 6258), False, 'import cv2\n'), ((6266, 6295), 'cv2.xfeatures2d.SURF_create', 'cv2.xfeatures2d.SURF_create', ([], {}), '()\n', (6293, 6295), False, 'import cv2\n'), ((6331, 6358), 'cv2.ocl.setUseOpenCL', 'cv2.ocl.setUseOpenCL', (['(False)'], {}), '(False)\n', (6351, 6358), False, 'import cv2\n'), ((6435, 6451), 'cv2.ORB_create', 'cv2.ORB_create', ([], {}), '()\n', (6449, 6451), False, 'import cv2\n'), ((6457, 6505), 'cv2.BFMatcher', 'cv2.BFMatcher', (['cv2.NORM_HAMMING'], {'crossCheck': '(True)'}), '(cv2.NORM_HAMMING, crossCheck=True)\n', (6470, 6505), False, 'import cv2\n'), ((6547, 6582), 'cv2.imread', 'cv2.imread', (['"""/home/pi/image.jpg"""', '(1)'], {}), "('/home/pi/image.jpg', 1)\n", (6557, 6582), False, 'import cv2\n'), ((6638, 6654), 'cv2.ORB_create', 'cv2.ORB_create', ([], {}), '()\n', (6652, 6654), False, 'import cv2\n'), ((6805, 6820), 'time.sleep', 'time.sleep', (['(0.1)'], {}), '(0.1)\n', (6815, 6820), False, 'import time\n'), ((7510, 7558), 'cv2.BFMatcher', 'cv2.BFMatcher', (['cv2.NORM_HAMMING'], {'crossCheck': '(True)'}), '(cv2.NORM_HAMMING, crossCheck=True)\n', (7523, 7558), False, 'import cv2\n'), ((7803, 7869), 'cv2.drawMatches', 'cv2.drawMatches', (['img', 'kp1', 'image', 'kp2', 'matches[:15]', 'None'], {'flags': '(2)'}), '(img, kp1, image, kp2, matches[:15], None, flags=2)\n', (7818, 7869), False, 'import cv2\n'), ((8068, 8106), 'cv2.cvtColor', 'cv2.cvtColor', (['image', 'cv2.COLOR_BGR2HSV'], {}), '(image, cv2.COLOR_BGR2HSV)\n', (8080, 8106), False, 'import cv2\n'), ((8118, 8156), 'cv2.cvtColor', 'cv2.cvtColor', (['image', 'cv2.COLOR_BGR2HSV'], {}), '(image, cv2.COLOR_BGR2HSV)\n', (8130, 8156), False, 'import cv2\n'), ((8171, 8209), 'cv2.cvtColor', 'cv2.cvtColor', (['image', 'cv2.COLOR_BGR2HSV'], {}), '(image, cv2.COLOR_BGR2HSV)\n', (8183, 8209), False, 'import cv2\n'), ((8222, 8260), 'cv2.cvtColor', 'cv2.cvtColor', (['image', 'cv2.COLOR_BGR2HSV'], {}), '(image, cv2.COLOR_BGR2HSV)\n', (8234, 8260), False, 'import cv2\n'), ((8302, 8347), 'cv2.inRange', 'cv2.inRange', (['hsv_blue', 'lower_blue', 'upper_blue'], {}), '(hsv_blue, lower_blue, upper_blue)\n', (8313, 8347), False, 'import cv2\n'), ((8411, 8453), 'cv2.inRange', 'cv2.inRange', (['hsv_red', 'lower_red', 'upper_red'], {}), '(hsv_red, lower_red, upper_red)\n', (8422, 8453), False, 'import cv2\n'), ((8519, 8570), 'cv2.inRange', 'cv2.inRange', (['hsv_yellow', 'lower_yellow', 'upper_yellow'], {}), '(hsv_yellow, lower_yellow, upper_yellow)\n', (8530, 8570), False, 'import cv2\n'), ((8634, 8679), 'cv2.inRange', 'cv2.inRange', (['hsv_gray', 'lower_gray', 'upper_gray'], {}), '(hsv_gray, lower_gray, upper_gray)\n', (8645, 8679), False, 'import cv2\n'), ((8782, 8827), 'cv2.bitwise_and', 'cv2.bitwise_and', (['image', 'image'], {'mask': 'mask_blue'}), '(image, image, mask=mask_blue)\n', (8797, 8827), False, 'import cv2\n'), ((8839, 8883), 'cv2.bitwise_and', 'cv2.bitwise_and', (['image', 'image'], {'mask': 'mask_red'}), '(image, image, mask=mask_red)\n', (8854, 8883), False, 'import cv2\n'), ((8898, 8945), 'cv2.bitwise_and', 'cv2.bitwise_and', (['image', 'image'], {'mask': 'mask_yellow'}), '(image, image, mask=mask_yellow)\n', (8913, 8945), False, 'import cv2\n'), ((8958, 9003), 'cv2.bitwise_and', 'cv2.bitwise_and', (['image', 'image'], {'mask': 'mask_gray'}), '(image, image, mask=mask_gray)\n', (8973, 9003), False, 'import cv2\n'), ((9038, 9079), 'cv2.cvtColor', 'cv2.cvtColor', (['res_blue', 'cv2.COLOR_BGR2HSV'], {}), '(res_blue, cv2.COLOR_BGR2HSV)\n', (9050, 9079), False, 'import cv2\n'), ((9096, 9136), 'cv2.cvtColor', 'cv2.cvtColor', (['res_red', 'cv2.COLOR_BGR2HSV'], {}), '(res_red, cv2.COLOR_BGR2HSV)\n', (9108, 9136), False, 'import cv2\n'), ((9165, 9208), 'cv2.cvtColor', 'cv2.cvtColor', (['res_yellow', 'cv2.COLOR_BGR2HSV'], {}), '(res_yellow, cv2.COLOR_BGR2HSV)\n', (9177, 9208), False, 'import cv2\n'), ((9235, 9276), 'cv2.cvtColor', 'cv2.cvtColor', (['res_gray', 'cv2.COLOR_BGR2HSV'], {}), '(res_gray, cv2.COLOR_BGR2HSV)\n', (9247, 9276), False, 'import cv2\n'), ((9351, 9407), 'cv2.calcHist', 'cv2.calcHist', (['[hsv_roi]', '[0]', 'mask_blue', '[180]', '[0, 180]'], {}), '([hsv_roi], [0], mask_blue, [180], [0, 180])\n', (9363, 9407), False, 'import cv2\n'), ((9404, 9462), 'cv2.normalize', 'cv2.normalize', (['roi_hist', 'roi_hist', '(0)', '(255)', 'cv2.NORM_MINMAX'], {}), '(roi_hist, roi_hist, 0, 255, cv2.NORM_MINMAX)\n', (9417, 9462), False, 'import cv2\n'), ((9586, 9645), 'cv2.calcHist', 'cv2.calcHist', (['[hsv_roi_red]', '[0]', 'mask_red', '[180]', '[0, 255]'], {}), '([hsv_roi_red], [0], mask_red, [180], [0, 255])\n', (9598, 9645), False, 'import cv2\n'), ((9642, 9708), 'cv2.normalize', 'cv2.normalize', (['roi_hist_red', 'roi_hist_red', '(0)', '(255)', 'cv2.NORM_MINMAX'], {}), '(roi_hist_red, roi_hist_red, 0, 255, cv2.NORM_MINMAX)\n', (9655, 9708), False, 'import cv2\n'), ((9827, 9892), 'cv2.calcHist', 'cv2.calcHist', (['[hsv_roi_yellow]', '[0]', 'mask_yellow', '[180]', '[0, 180]'], {}), '([hsv_roi_yellow], [0], mask_yellow, [180], [0, 180])\n', (9839, 9892), False, 'import cv2\n'), ((9889, 9961), 'cv2.normalize', 'cv2.normalize', (['roi_hist_yellow', 'roi_hist_yellow', '(0)', '(255)', 'cv2.NORM_MINMAX'], {}), '(roi_hist_yellow, roi_hist_yellow, 0, 255, cv2.NORM_MINMAX)\n', (9902, 9961), False, 'import cv2\n'), ((10085, 10146), 'cv2.calcHist', 'cv2.calcHist', (['[hsv_roi_gray]', '[0]', 'mask_gray', '[180]', '[0, 180]'], {}), '([hsv_roi_gray], [0], mask_gray, [180], [0, 180])\n', (10097, 10146), False, 'import cv2\n'), ((10143, 10211), 'cv2.normalize', 'cv2.normalize', (['roi_hist_gray', 'roi_hist_gray', '(0)', '(180)', 'cv2.NORM_MINMAX'], {}), '(roi_hist_gray, roi_hist_gray, 0, 180, cv2.NORM_MINMAX)\n', (10156, 10211), False, 'import cv2\n'), ((10426, 10487), 'cv2.calcBackProject', 'cv2.calcBackProject', (['[hsv_blue]', '[0]', 'roi_hist', '[0, 180]', '(100)'], {}), '([hsv_blue], [0], roi_hist, [0, 180], 100)\n', (10445, 10487), False, 'import cv2\n'), ((10560, 10624), 'cv2.calcBackProject', 'cv2.calcBackProject', (['[hsv_red]', '[0]', 'roi_hist_red', '[0, 255]', '(100)'], {}), '([hsv_red], [0], roi_hist_red, [0, 255], 100)\n', (10579, 10624), False, 'import cv2\n'), ((10634, 10702), 'cv2.calcBackProject', 'cv2.calcBackProject', (['[hsv_yellow]', '[0]', 'roi_hist_yellow', '[0, 255]', '(5)'], {}), '([hsv_yellow], [0], roi_hist_yellow, [0, 255], 5)\n', (10653, 10702), False, 'import cv2\n'), ((10719, 10783), 'cv2.calcBackProject', 'cv2.calcBackProject', (['[hsv_gray]', '[0]', 'roi_hist_gray', '[0, 255]', '(5)'], {}), '([hsv_gray], [0], roi_hist_gray, [0, 255], 5)\n', (10738, 10783), False, 'import cv2\n'), ((11306, 11349), 'cv2.meanShift', 'cv2.meanShift', (['dst', 'track_window', 'term_crit'], {}), '(dst, track_window, term_crit)\n', (11319, 11349), False, 'import cv2\n'), ((11375, 11426), 'cv2.meanShift', 'cv2.meanShift', (['dst_red', 'track_window_red', 'term_crit'], {}), '(dst_red, track_window_red, term_crit)\n', (11388, 11426), False, 'import cv2\n'), ((11464, 11521), 'cv2.meanShift', 'cv2.meanShift', (['dst_yellow', 'track_window_yellow', 'term_crit'], {}), '(dst_yellow, track_window_yellow, term_crit)\n', (11477, 11521), False, 'import cv2\n'), ((11557, 11610), 'cv2.meanShift', 'cv2.meanShift', (['dst_gray', 'track_window_gray', 'term_crit'], {}), '(dst_gray, track_window_gray, term_crit)\n', (11570, 11610), False, 'import cv2\n'), ((11722, 11774), 'cv2.rectangle', 'cv2.rectangle', (['image', '(x, y)', '(x + w, y + h)', '(255)', '(2)'], {}), '(image, (x, y), (x + w, y + h), 255, 2)\n', (11735, 11774), False, 'import cv2\n'), ((11801, 11864), 'cv2.rectangle', 'cv2.rectangle', (['res_blue', '(x, y)', '(x + w, y + h)', '(255, 0, 0)', '(2)'], {}), '(res_blue, (x, y), (x + w, y + h), (255, 0, 0), 2)\n', (11814, 11864), False, 'import cv2\n'), ((11890, 11955), 'cv2.putText', 'cv2.putText', (['res_blue', '"""Nitrogen"""', '(x, y)', 'font', '(0.9)', '(255, 0)', '(2)'], {}), "(res_blue, 'Nitrogen', (x, y), font, 0.9, (255, 0), 2)\n", (11901, 11955), False, 'import cv2\n'), ((11963, 12015), 'cv2.rectangle', 'cv2.rectangle', (['image', '(x, y)', '(x + w, y + h)', '(255)', '(2)'], {}), '(image, (x, y), (x + w, y + h), 255, 2)\n', (11976, 12015), False, 'import cv2\n'), ((12042, 12110), 'cv2.rectangle', 'cv2.rectangle', (['res_red', '(xr, yr)', '(xr + wr, yr + hr)', '(0, 0, 255)', '(2)'], {}), '(res_red, (xr, yr), (xr + wr, yr + hr), (0, 0, 255), 2)\n', (12055, 12110), False, 'import cv2\n'), ((12135, 12202), 'cv2.putText', 'cv2.putText', (['res_red', '"""Oxygen"""', '(xr, yr)', 'font', '(0.9)', '(0, 0, 255)', '(2)'], {}), "(res_red, 'Oxygen', (xr, yr), font, 0.9, (0, 0, 255), 2)\n", (12146, 12202), False, 'import cv2\n'), ((12209, 12261), 'cv2.rectangle', 'cv2.rectangle', (['image', '(x, y)', '(x + w, y + h)', '(255)', '(2)'], {}), '(image, (x, y), (x + w, y + h), 255, 2)\n', (12222, 12261), False, 'import cv2\n'), ((12288, 12362), 'cv2.rectangle', 'cv2.rectangle', (['res_yellow', '(xy, yy)', '(xy + wy, yy + hy)', '(40, 255, 255)', '(2)'], {}), '(res_yellow, (xy, yy), (xy + wy, yy + hy), (40, 255, 255), 2)\n', (12301, 12362), False, 'import cv2\n'), ((12387, 12464), 'cv2.putText', 'cv2.putText', (['res_yellow', '"""Phosphorus"""', '(xy, yy)', 'font', '(0.9)', '(40, 255, 255)', '(2)'], {}), "(res_yellow, 'Phosphorus', (xy, yy), font, 0.9, (40, 255, 255), 2)\n", (12398, 12464), False, 'import cv2\n'), ((12471, 12523), 'cv2.rectangle', 'cv2.rectangle', (['image', '(x, y)', '(x + w, y + h)', '(255)', '(2)'], {}), '(image, (x, y), (x + w, y + h), 255, 2)\n', (12484, 12523), False, 'import cv2\n'), ((12550, 12616), 'cv2.rectangle', 'cv2.rectangle', (['res_gray', '(xg, yg)', '(xg + wg, yg + hg)', 'DARKGRAY', '(2)'], {}), '(res_gray, (xg, yg), (xg + wg, yg + hg), DARKGRAY, 2)\n', (12563, 12616), False, 'import cv2\n'), ((12644, 12709), 'cv2.putText', 'cv2.putText', (['res_gray', '"""Carbon"""', '(xg, yg)', 'font', '(0.9)', 'DARKGRAY', '(2)'], {}), "(res_gray, 'Carbon', (xg, yg), font, 0.9, DARKGRAY, 2)\n", (12655, 12709), False, 'import cv2\n'), ((12817, 12869), 'cv2.rectangle', 'cv2.rectangle', (['image', '(x, y)', '(x + w, y + h)', '(255)', '(2)'], {}), '(image, (x, y), (x + w, y + h), 255, 2)\n', (12830, 12869), False, 'import cv2\n'), ((12900, 12962), 'cv2.putText', 'cv2.putText', (['image', '"""Nitrogen"""', '(x, y)', 'font', '(0.9)', '(255, 0)', '(2)'], {}), "(image, 'Nitrogen', (x, y), font, 0.9, (255, 0), 2)\n", (12911, 12962), False, 'import cv2\n'), ((12971, 13037), 'cv2.rectangle', 'cv2.rectangle', (['image', '(xr, yr)', '(xr + wr, yr + hr)', '(0, 0, 255)', '(2)'], {}), '(image, (xr, yr), (xr + wr, yr + hr), (0, 0, 255), 2)\n', (12984, 13037), False, 'import cv2\n'), ((13062, 13127), 'cv2.putText', 'cv2.putText', (['image', '"""Oxygen"""', '(xr, yr)', 'font', '(0.9)', '(0, 0, 255)', '(2)'], {}), "(image, 'Oxygen', (xr, yr), font, 0.9, (0, 0, 255), 2)\n", (13073, 13127), False, 'import cv2\n'), ((13135, 13204), 'cv2.rectangle', 'cv2.rectangle', (['image', '(xy, yy)', '(xy + wy, yy + hy)', '(40, 255, 255)', '(2)'], {}), '(image, (xy, yy), (xy + wy, yy + hy), (40, 255, 255), 2)\n', (13148, 13204), False, 'import cv2\n'), ((13229, 13301), 'cv2.putText', 'cv2.putText', (['image', '"""Phosphorus"""', '(xy, yy)', 'font', '(0.9)', '(40, 255, 255)', '(2)'], {}), "(image, 'Phosphorus', (xy, yy), font, 0.9, (40, 255, 255), 2)\n", (13240, 13301), False, 'import cv2\n'), ((13308, 13368), 'cv2.rectangle', 'cv2.rectangle', (['image', '(xg, yg)', '(xg + wg, yg + hg)', 'WHITE', '(2)'], {}), '(image, (xg, yg), (xg + wg, yg + hg), WHITE, 2)\n', (13321, 13368), False, 'import cv2\n'), ((13396, 13455), 'cv2.putText', 'cv2.putText', (['image', '"""Carbon"""', '(xg, yg)', 'font', '(0.9)', 'WHITE', '(2)'], {}), "(image, 'Carbon', (xg, yg), font, 0.9, WHITE, 2)\n", (13407, 13455), False, 'import cv2\n'), ((13574, 13604), 'cv2.imshow', 'cv2.imshow', (['"""Real image"""', 'img4'], {}), "('Real image', img4)\n", (13584, 13604), False, 'import cv2\n'), ((13606, 13634), 'cv2.imshow', 'cv2.imshow', (['"""GRAY"""', 'res_gray'], {}), "('GRAY', res_gray)\n", (13616, 13634), False, 'import cv2\n'), ((13636, 13662), 'cv2.imshow', 'cv2.imshow', (['"""RED"""', 'res_red'], {}), "('RED', res_red)\n", (13646, 13662), False, 'import cv2\n'), ((13663, 13691), 'cv2.imshow', 'cv2.imshow', (['"""BLUE"""', 'res_blue'], {}), "('BLUE', res_blue)\n", (13673, 13691), False, 'import cv2\n'), ((13692, 13724), 'cv2.imshow', 'cv2.imshow', (['"""YELLOW"""', 'res_yellow'], {}), "('YELLOW', res_yellow)\n", (13702, 13724), False, 'import cv2\n'), ((13726, 13753), 'cv2.imshow', 'cv2.imshow', (['"""matches"""', 'img3'], {}), "('matches', img3)\n", (13736, 13753), False, 'import cv2\n'), ((13794, 13808), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (13805, 13808), False, 'import cv2\n')] |
# -*- coding: utf-8 -*-
"""
Created on Tue May 22 14:24:45 2018
@author: yume
"""
import numpy as np
import matplotlib.pyplot as plt
import hidden_markov_models
def gaussian_paras(x):
mean = x.mean()
var = x.var()
std = x.std()
return (mean, var, std)
if __name__ == '__main__':
sampler = hidden_markov_models.GaussianHMM()
z, x = sampler(10000, complete_data=True)
sampler.visualize(x)
print("Distribution: ", sampler.get_name())
print("Parameters: ", sampler.get_params())
# パラメタ推定処理
K = len(np.unique(z)) # 3
N = len(z)
p_initial_state = [0.4, 0.3, 0.3]
print("K:", K)
print("p_initial_state:", p_initial_state)
a = np.linspace(0, K-1, K)
b = np.linspace(0, K-1, K)
a, b = np.meshgrid(a, b)
a = a.reshape(-1, 1)
b = b.reshape(-1, 1)
pre_and_now_zs_grid = np.hstack((a, b))
prev_z = z[:-1]
count_list = []
for zs in pre_and_now_zs_grid:
count = 0
for i in np.arange(1, N):
if all(zs == np.array([z[i], prev_z[i-1]])):
count += 1
count_list.append(count)
count_list = np.array(count_list).reshape(K, K)
transition_matrix = []
for k in range(K):
for i in range(K):
transition_matrix.append(count_list[k, i]/count_list[k].sum())
transition_matrix = np.array(transition_matrix).reshape(K, K)
xs = []
for k in range(K):
x_zi = x[z == k]
xs.append(x_zi)
mean_lst = []
var_lst = []
std_lst = []
for k in range(K):
mean, var, std = gaussian_paras(np.array(xs[k], dtype=np.float64))
mean_lst.append(mean)
var_lst.append(var)
std_lst.append(std)
means = np.array(mean_lst)
stds = np.array(std_lst)
# 以下、モデル生成処理
z_1 = np.random.choice(K, 1, p=p_initial_state)
x_1 = np.random.normal(means[z_1], stds[z_1], 1)
z_new = [z_1]
x_new = [x_1]
for i in np.arange(1, N):
z_new.append(np.random.choice(K, 1,
p=transition_matrix[int(z_new[-1])]))
x_new.append(np.random.normal(
means[int(z_new[-1])], stds[int(z_new[-1])], 1))
x_new = np.array(x_new)
print("transition_matrix:", transition_matrix)
print("mean:", mean_lst)
print("std:", std_lst)
sampler.visualize(x_new)
| [
"numpy.random.normal",
"hidden_markov_models.GaussianHMM",
"numpy.unique",
"numpy.hstack",
"numpy.random.choice",
"numpy.array",
"numpy.linspace",
"numpy.meshgrid",
"numpy.arange"
] | [((315, 349), 'hidden_markov_models.GaussianHMM', 'hidden_markov_models.GaussianHMM', ([], {}), '()\n', (347, 349), False, 'import hidden_markov_models\n'), ((694, 718), 'numpy.linspace', 'np.linspace', (['(0)', '(K - 1)', 'K'], {}), '(0, K - 1, K)\n', (705, 718), True, 'import numpy as np\n'), ((725, 749), 'numpy.linspace', 'np.linspace', (['(0)', '(K - 1)', 'K'], {}), '(0, K - 1, K)\n', (736, 749), True, 'import numpy as np\n'), ((759, 776), 'numpy.meshgrid', 'np.meshgrid', (['a', 'b'], {}), '(a, b)\n', (770, 776), True, 'import numpy as np\n'), ((853, 870), 'numpy.hstack', 'np.hstack', (['(a, b)'], {}), '((a, b))\n', (862, 870), True, 'import numpy as np\n'), ((1722, 1740), 'numpy.array', 'np.array', (['mean_lst'], {}), '(mean_lst)\n', (1730, 1740), True, 'import numpy as np\n'), ((1752, 1769), 'numpy.array', 'np.array', (['std_lst'], {}), '(std_lst)\n', (1760, 1769), True, 'import numpy as np\n'), ((1795, 1836), 'numpy.random.choice', 'np.random.choice', (['K', '(1)'], {'p': 'p_initial_state'}), '(K, 1, p=p_initial_state)\n', (1811, 1836), True, 'import numpy as np\n'), ((1847, 1889), 'numpy.random.normal', 'np.random.normal', (['means[z_1]', 'stds[z_1]', '(1)'], {}), '(means[z_1], stds[z_1], 1)\n', (1863, 1889), True, 'import numpy as np\n'), ((1939, 1954), 'numpy.arange', 'np.arange', (['(1)', 'N'], {}), '(1, N)\n', (1948, 1954), True, 'import numpy as np\n'), ((2193, 2208), 'numpy.array', 'np.array', (['x_new'], {}), '(x_new)\n', (2201, 2208), True, 'import numpy as np\n'), ((546, 558), 'numpy.unique', 'np.unique', (['z'], {}), '(z)\n', (555, 558), True, 'import numpy as np\n'), ((982, 997), 'numpy.arange', 'np.arange', (['(1)', 'N'], {}), '(1, N)\n', (991, 997), True, 'import numpy as np\n'), ((1134, 1154), 'numpy.array', 'np.array', (['count_list'], {}), '(count_list)\n', (1142, 1154), True, 'import numpy as np\n'), ((1345, 1372), 'numpy.array', 'np.array', (['transition_matrix'], {}), '(transition_matrix)\n', (1353, 1372), True, 'import numpy as np\n'), ((1589, 1622), 'numpy.array', 'np.array', (['xs[k]'], {'dtype': 'np.float64'}), '(xs[k], dtype=np.float64)\n', (1597, 1622), True, 'import numpy as np\n'), ((1024, 1055), 'numpy.array', 'np.array', (['[z[i], prev_z[i - 1]]'], {}), '([z[i], prev_z[i - 1]])\n', (1032, 1055), True, 'import numpy as np\n')] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: <NAME>
"""
from scipy.stats import multivariate_normal, norm
import numpy as np
#### Generalized Black Scholes Formula
def GBlackScholes(CallPutFlag, S, X, T, r, b, v):
d_1 = (np.log(S/X) + (b + v**2/2) * T) / (v * T**(1/2))
d_2 = d_1 - v * T**(1/2)
if CallPutFlag == 'c':
return S * np.e**((b-r)*T) * norm.cdf(d_1) - X * np.e**(-r*T) * norm.cdf(d_2)
else:
return X * np.e**(-r*T) * norm.cdf(-d_2) - S * np.e**((b-r)*T) * norm.cdf(-d_1)
#### Bjerksund Stensland 1993 American Option Algorithm
# Help Function
def phi(S, T, gamma, h, i, r, b, v):
L = (-r + gamma * b + gamma * (gamma - 1) * v**2/2 ) * T
d = -(np.log(S/h) + (b + (gamma - 1/2) * v**2) * T ) / (v * T**(1/2))
K = 2 * b / v ** 2 + (2 * gamma - 1)
return np.e**L * S**gamma * (norm.cdf(d) - (i/S)**K * norm.cdf(d - (2 * np.log(i/S)/(v * T**(1/2)) )))
def BSAmerican_fast(CallPutFlag, S, X, T, r, b, v):
if T == np.inf: # If perpetual
if CallPutFlag != 'c':
gam = 1/2 - b/v**2 - ((b/v**2 - 1/2)**2 + 2*r/v**2 )**(1/2)
return X/(1-gam) * ((gam-1)/gam * S/X)**gam
else:
gam = 1/2 - b/v**2 + ((b/v**2 - 1/2)**2 + 2*r/v**2 )**(1/2)
return X/(gam - 1) * ((gam-1)/gam * S/X)**gam
else: # if normal
if CallPutFlag != 'c':
r = r - b
b = -b
S, X = X, S
if b >= r:
return GBlackScholes('c', S, X, T, r, b, v)
else:
Beta = (1/2 - b/v**2) + ((b/v**2 - 1/2)**2 + 2 * r/v**2)**(1/2)
BInfinity = Beta/(Beta - 1) * X
B0 = max(X, r/(r-b) * X)
ht = -(b * T + 2 * v * T**(1/2)) * B0 / (BInfinity - B0)
i = B0 + (BInfinity - B0) * (1 - np.e**(ht))
alfa = (i - X) * i**(-Beta)
if S >= i:
return S - X
else:
return (alfa * S ** Beta - alfa * phi(S, T, Beta, i, i, r, b, v)
+ phi(S, T, 1, i, i, r, b, v) - phi(S, T, 1, X, i, r, b, v)
- X * phi(S, T, 0, i, i, r, b, v) + X * phi(S, T, 0, X, i, r, b, v))
class Vanilla:
"""
Vanilla Option Pricing Class
Used to price European and American Options on Stocks, Futures/Forwards and Currency
and calculate corresponding numerical Greeks
Generalized Black Scholes 1973, Merton 1973, Black 1976, Asay 1982 and
Garman and Kohlhagen 1983, Bjerksund Stensland 1993
Initialize with
TypeFlag - 'American' or 'European' string
CallPutFlag - 'c' string for call, 'p' string for put
price - price of underlying
strike - strike price
time_to_maturity - time to maturity given in years
(set to np.inf for perpetual american options)
riskfree_rate - annualized expected risk free interest rate until maturity in percent
cost_of_carry - cost of holding the underlying given as annualized rate
- stock: cost_of_carry = riskfree_rate - continous dividend yield
- future/forward: cost_of_carry = 0
- margined Future: cost_of_carry = 0, riskfree_rate = 0
- currency: cost_of_carry = risk free rate of underlying currency
volatility - annualized volatility of underlying returns
"""
def __init__(self,
TypeFlag, CallPutFlag,
price, strike,
time_to_maturity,
riskfree_rate, cost_of_carry,
volatility):
self.F = CallPutFlag
self.S = price
self.X = strike
self.T = time_to_maturity
self.r = riskfree_rate
self.b = cost_of_carry
self.v = volatility
if TypeFlag == 'American':
self.func = BSAmerican_fast
elif TypeFlag == 'European':
self.func = GBlackScholes
else:
print('bad defined TypeFlag')
if CallPutFlag not in ['c','p']:
print('bad defined CallPutFlag')
def price(self):
""" Get optionprice"""
return self.func(self.F, self.S, self.X, self.T, self.r, self.b, self.v)
def Delta(self, diff = 0.001):
""" Get delta = Doptionprice / Dprice"""
return (self.func(self.F, self.S + diff, self.X, self.T, self.r, self.b, self.v)
- self.func(self.F, self.S - diff, self.X, self.T, self.r, self.b, self.v))/(diff * 2)
def Vanna(self, diff = 0.001):
""" Get vanna = Ddelta / Dvolatility """
return (self.func(self.F, self.S + diff, self.X, self.T, self.r, self.b, self.v + diff)
- self.func(self.F, self.S + diff, self.X, self.T, self.r, self.b, self.v - diff)
- self.func(self.F, self.S - diff, self.X, self.T, self.r, self.b, self.v + diff)
+ self.func(self.F, self.S - diff, self.X, self.T, self.r, self.b, self.v - diff))/(4 * diff **2)
def DvannaDvol(self, diff = 0.001):
""" Get Dvanna / Dvolatility"""
return (self.func(self.F, self.S + diff, self.X, self.T, self.r, self.b, self.v + diff)
- 2 * self.func(self.F, self.S + diff, self.X, self.T, self.r, self.b, self.v)
+ self.func(self.F, self.S + diff, self.X, self.T, self.r, self.b, self.v - diff)
- self.func(self.F, self.S - diff, self.X, self.T, self.r, self.b, self.v + diff)
+ 2 * self.func(self.F, self.S - diff, self.X, self.T, self.r, self.b, self.v)
- self.func(self.F, self.S - diff, self.X, self.T, self.r, self.b, self.v - diff))/(2 * diff**3)
def Charm(self, diff = 0.001):
""" Get charm = Ddelta / Dtime"""
return (self.func(self.F, self.S + diff, self.X, self.T + diff, self.r, self.b, self.v)
- self.func(self.F, self.S + diff, self.X, self.T - diff, self.r, self.b, self.v)
- self.func(self.F, self.S - diff, self.X, self.T + diff, self.r, self.b, self.v)
+ self.func(self.F, self.S - diff, self.X, self.T - diff, self.r, self.b, self.v))/(-4 * diff **2)
def Lambda(self, diff = 0.001):
""" Get lambda = omega = elasticity = delta * price / optionprice"""
return self.Delta(diff = diff) * self.S / self.price()
def Elasticity(self, diff = 0.001):
""" Get lambda = omega = elasticity = delta * price / optionprice"""
return self.Lambda(diff = diff)
def Omega(self, diff = 0.001):
""" Get lambda = omega = elasticity = delta * price / optionprice"""
return self.Lambda(diff = diff)
def Gamma(self, diff = 0.001):
""" Get gamma = convexity = Ddelta / Dprice"""
return (self.func(self.F, self.S + diff, self.X, self.T, self.r, self.b, self.v)
+ self.func(self.F, self.S - diff, self.X, self.T, self.r, self.b, self.v)
- 2 * self.func(self.F, self.S, self.X, self.T, self.r, self.b, self.v))/(diff **2)
def Convexity(self, diff = 0.001):
""" Get gamma = convexity = Ddelta / Dprice"""
return self.Gamma(diff = diff)
def GammaP(self, diff = 0.001):
""" Get gamma percent = gammaP = gamma * price / 100"""
return self.S * self.Gamma(diff = diff) / 100
def Zomma(self, diff = 0.001):
""" Get zomma = Dgamma / Dvol"""
return (self.func(self.F, self.S + diff, self.X, self.T, self.r, self.b, self.v + diff)
- 2 * self.func(self.F, self.S, self.X, self.T, self.r, self.b, self.v + diff)
+ self.func(self.F, self.S - diff, self.X, self.T, self.r, self.b, self.v + diff)
- self.func(self.F, self.S + diff, self.X, self.T, self.r, self.b, self.v - diff)
+ 2 * self.func(self.F, self.S, self.X, self.T, self.r, self.b, self.v - diff)
- self.func(self.F, self.S - diff, self.X, self.T, self.r, self.b, self.v - diff))/(2 * diff**3)
def ZommaP(self, diff = 0.001):
""" Gat zommaP = DgammaP / Dvol"""
return self.S * self.Zomma(diff = diff) / 100
def Speed(self, diff = 0.001):
""" Get speed = Dgamma / Dprice"""
return (self.func(self.F, self.S + 2 * diff, self.X, self.T, self.r, self.b, self.v)
- 3 * self.func(self.F, self.S + diff, self.X, self.T, self.r, self.b, self.v)
+ 3 * self.func(self.F, self.S, self.X, self.T, self.r, self.b, self.v)
- self.func(self.F, self.S - diff, self.X, self.T, self.r, self.b, self.v))/(diff ** 3)
def SpeedP(self):
""" Get speed percent = speedP = DgammaP / Dprice"""
return self.S * self.Speed(diff = diff) / 100
def Colour(self, diff = 0.001):
""" Get colour = gamma_bleed = Dgamma / Dtime """
return (self.func(self.F, self.S + diff, self.X, self.T + diff, self.r, self.b, self.v)
- 2 * self.func(self.F, self.S, self.X, self.T + diff, self.r, self.b, self.v)
+ self.func(self.F, self.S - diff, self.X, self.T + diff, self.r, self.b, self.v)
- self.func(self.F, self.S + diff, self.X, self.T - diff, self.r, self.b, self.v)
+ 2 * self.func(self.F, self.S, self.X, self.T - diff, self.r, self.b, self.v)
- self.func(self.F, self.S - diff, self.X, self.T - diff, self.r, self.b, self.v))/(-2 * diff**3)
def ColourP(self, diff = 0.001):
""" Get colourP = gamma_percant_bleed = DgammaP / Dtime """
return self.S * self.Colour(diff = diff) / 100
def Vega(self, diff = 0.001):
""" Get vega = Doptionprice / Dvolatility """
return (self.func(self.F, self.S, self.X, self.T, self.r, self.b, self.v + diff)
- self.func(self.F, self.S, self.X, self.T, self.r, self.b, self.v - diff))/(diff * 2)
def VegaP(self):
""" Get vegaP = volatility / 10 * Doptionprice / Dvolatility """
return self.v * self.Vega() / 10
def VegaBleed(self, diff = 0.001):
""" Get vega bleed = Dvega / Dtime """
return (self.func(self.F, self.S, self.X, self.T + diff, self.r, self.b, self.v + diff)
- self.func(self.F, self.S, self.X, self.T - diff, self.r, self.b, self.v + diff)
- self.func(self.F, self.S, self.X, self.T + diff, self.r, self.b, self.v - diff)
+ self.func(self.F, self.S, self.X, self.T - diff, self.r, self.b, self.v - diff))/(4 * diff ** 2)
def Vomma(self, diff = 0.001):
""" Get vomma = volga = Dvega / Dvolatility """
return (self.func(self.F, self.S, self.X, self.T, self.r, self.b, self.v + diff)
+ self.func(self.F, self.S, self.X, self.T, self.r, self.b, self.v - diff)
- 2 * self.func(self.F, self.S, self.X, self.T, self.r, self.b, self.v))/(diff **2)
def VommaP(self):
""" Get vommaP = volatility / 10 * Dvega / Dvolatility """
return self.v * self.Vomma() / 10
def Ultima(self, diff = 0.001):
""" Get ultima = Dvomma / Dvolatility """
return (self.func(self.F, self.S, self.X, self.T, self.r, self.b, self.v + 2 * diff)
- 3 * self.func(self.F, self.S, self.X, self.T, self.r, self.b, self.v + diff)
+ 3 * self.func(self.F, self.S, self.X, self.T, self.r, self.b, self.v)
- self.func(self.F, self.S, self.X, self.T, self.r, self.b, self.v - diff))/(diff ** 3)
def Theta(self, diff = 0.001):
""" Get theta = expected bleed """
return (self.func(self.F, self.S, self.X, self.T, self.r, self.b, self.v)
- self.func(self.F, self.S, self.X, self.T - diff, self.r, self.b, self.v))/-diff
def Rho(self, diff = 0.001, future = False):
""" Get rho = Doptionprice / Driskfree_rate, set future=True for Forward/Future as underlying """
return (self.func(self.F, self.S, self.X, self.T, self.r + diff, self.b + diff * (future != False), self.v)
- self.func(self.F, self.S, self.X, self.T, self.r - diff, self.b - diff * (future != False), self.v))/(diff * 2)
def Phi(self, diff = 0.001):
""" Get phi = rho2 = Doptionprice / D(riskfree_rate - cost_of_carry) = Doptionprice / Ddividend_yield """
return (self.func(self.F, self.S, self.X, self.T, self.r, self.b + diff, self.v)
- self.func(self.F, self.S, self.X, self.T, self.r, self.b - diff, self.v))/(diff * -2)
def StrikeDelta(self, diff = 0.001):
""" Get strike delta = discounted probability = Doptionprice / Dstrike """
return (self.func(self.F, self.S, self.X + diff, self.T, self.r, self.b, self.v)
- self.func(self.F, self.S, self.X - diff, self.T, self.r, self.b, self.v))/(diff * 2)
def StrikeGamma(self, diff = 0.001):
""" Get strike gamma = RiskNeutralDensity = Dstrike_delta / Dstrike """
return (self.func(self.F, self.S, self.X + diff, self.T, self.r, self.b, self.v)
+ self.func(self.F, self.S, self.X - diff, self.T, self.r, self.b, self.v)
- 2 * self.func(self.F, self.S, self.X, self.T, self.r, self.b, self.v))/(diff **2)
### Only for European Options
# def Zeta(self): ######
# """ Get zeta = in the money probability """
# return norm.cdf(self.F * self.d_2)
#
# def DzetaDvol(self): ######
# """ Get Dzeta/Dvolatility """
# return - self.F * norm.pdf(self.d_2) * self.d_1 / self.v
#
# def ZetaBleed(self): ######
# """ Get - Dzeta/Dtime """
# A = self.b / (self.v * self.T**(1/2)) - self.d_1 / (2 * self.T)
# return norm.pdf(self.d_2) * A * self.F
@np.vectorize
def implied_V(TypeFlag, CallPutFlag, S, X, T, r, b, P, eps):
"Calculates implied volatility"
v = np.sqrt(np.abs(np.log(S/X) + r*T) * 2 / T)
Opt = Vanilla(TypeFlag, CallPutFlag, S, X, T, r, b, v)
impP = Opt.price()
while abs(P - impP) > eps:
v = v - (impP - P)/Opt.Vega()
Opt = Vanilla(TypeFlag, CallPutFlag, S, X, T, r, b, v)
impP = Opt.price()
return v
| [
"scipy.stats.norm.cdf",
"numpy.log"
] | [((243, 256), 'numpy.log', 'np.log', (['(S / X)'], {}), '(S / X)\n', (249, 256), True, 'import numpy as np\n'), ((853, 864), 'scipy.stats.norm.cdf', 'norm.cdf', (['d'], {}), '(d)\n', (861, 864), False, 'from scipy.stats import multivariate_normal, norm\n'), ((385, 398), 'scipy.stats.norm.cdf', 'norm.cdf', (['d_1'], {}), '(d_1)\n', (393, 398), False, 'from scipy.stats import multivariate_normal, norm\n'), ((420, 433), 'scipy.stats.norm.cdf', 'norm.cdf', (['d_2'], {}), '(d_2)\n', (428, 433), False, 'from scipy.stats import multivariate_normal, norm\n'), ((478, 492), 'scipy.stats.norm.cdf', 'norm.cdf', (['(-d_2)'], {}), '(-d_2)\n', (486, 492), False, 'from scipy.stats import multivariate_normal, norm\n'), ((517, 531), 'scipy.stats.norm.cdf', 'norm.cdf', (['(-d_1)'], {}), '(-d_1)\n', (525, 531), False, 'from scipy.stats import multivariate_normal, norm\n'), ((715, 728), 'numpy.log', 'np.log', (['(S / h)'], {}), '(S / h)\n', (721, 728), True, 'import numpy as np\n'), ((14096, 14109), 'numpy.log', 'np.log', (['(S / X)'], {}), '(S / X)\n', (14102, 14109), True, 'import numpy as np\n'), ((896, 909), 'numpy.log', 'np.log', (['(i / S)'], {}), '(i / S)\n', (902, 909), True, 'import numpy as np\n')] |
import tensorflow as tf
import os
import numpy as np
import pandas as pd
from skimage import io
from skimage.transform import resize
from skimage.filters import gaussian
# from deepflash import unet, preproc, utils
from df_resources import unet, preproc, utils, pixelshift37
from skimage.measure import label, regionprops, approximate_polygon
from skimage.draw import polygon, polygon_perimeter
from shapely.geometry import MultiPoint, Polygon
import math
import matplotlib.pyplot as plt
def pixel_shift_3d(np_img, dichroic_dictionary, json_file):
# INPUT:
# np_img: numpy image. shape = 3D
# dichroic_dictionary: dictionary where key=channel number, value=name of dichroic_dictionary
# json_file: path to the .json file containing the shift values for each dichroic generated by the shift callibration script
# OUTPUT:
# return: numpy image of shape (n_channels, height, width). height and width may be different than origional image
number_of_channels = np_img.shape[0]
shifted_list = []
# instantiate PixelShifter class object from pixelshift37
shift_obj = pixelshift37.PixelShifter(jsonfilepath=json_file)
# perform shift on each channel
for ch in range(np_img.shape[0]):
ch_img = np_img[ch,:,:]
ch_dichroic = dichroic_dictionary[ch]
for key in shift_obj.shiftdict.keys():
if key.split('_')[-1].lower() in ch_dichroic.lower():
ch_img = shift_obj.shape_images(ch_img)
shiftval = shift_obj.shiftdict[key]
img = shift_obj.align_with_shift_matrix(ch_img,shiftval)
shifted_list.append(img)
# create numpy array where .shape = 3 from list of lists 'shifted_list'
shifted_img = np.dstack(shifted_list)
# rearranges shape of numpy array to look more like origional image
shifted_img = np.moveaxis(shifted_img, -1, 0)
print("shifted img shape: ", shifted_img.shape)
return(shifted_img)
def correct_shift_upsampling(img):
if np.issubdtype(img.dtype, np.dtype('uint16')):
over_values = img > 4095
img[over_values] = 4095
return(img)
elif np.issubdtype(img.dtype, np.dtype('uint8')):
over_values = img > 255
img[over_values] = 255
return(img)
def convert_16_to_8(np_img):
# INPUT:
# np_img: numpy image. shape = 2D or 3D
# OUTPUT:
# return: 8 bit version of origional np_img
info = np.iinfo(np_img.dtype)
if np.issubdtype(np_img.dtype, np.dtype('uint16')):
data = np_img.astype(np.int16)/4095
# print('ORIGIONAL IMG: ', np.max(np_img))
# print('CONVERSION: ', np.max(data), " INFO: ", info)
data = 255 * data
img8 = data.astype(np.uint8)
return(img8)
elif np.issubdtype(np_img.dtype, np.dtype('uint8')):
return(np_img)
def check_input(df, img_directory='./images'):
#CHECK IMAGE SHAPE TO CHANNELS GIVEN
fs = df.file_name.tolist()
cs = df.ch_order.tolist()
shs = [io.imread(os.path.join(img_directory, f)).shape for f in fs]
# for i in range(len(fs)):
print(fs, cs, shs)
def polygons_from_labels(labeled_arr, gene_name):
df = pd.DataFrame(columns=['cell_n', 'gene_name', 'row_pixels', 'col_pixels'])
region_props=regionprops(labeled_arr)
for n, prop in enumerate(region_props):
p = approximate_polygon(region_props[n].coords, tolerance=2)
# OR
# p = region_props[0].coords
r = p[:,0]
c = p[:,1]
# r, c = polygon_perimeter(r,c)
# new_img[r,c] = 200
# load_dict = {'cell_n':n, 'row_pixels':r.tolist(), 'col_pixels':c.tolist()}
# df = df.append(load_dict, ignore_index=True)
pp=[(x,y) for x,y in zip(r.tolist(), c.tolist())]
cent=(sum([p[0] for p in pp])/len(pp),sum([p[1] for p in pp])/len(pp))
pp.sort(key=lambda p: math.atan2(p[1]-cent[1],p[0]-cent[0]))
# print(pp)
shapely_poly = Polygon(pp)
rr, cc = shapely_poly.exterior.coords.xy
rr = np.asarray(rr, dtype=np.int16)
cc = np.asarray(cc, dtype=np.int16)
# print(rr, cc)
load_dict = {'cell_n':n, 'gene_name':gene_name, 'row_pixels':rr.tolist(), 'col_pixels':cc.tolist()}
df = df.append(load_dict, ignore_index=True)
return(df)
def overlap(arr1,arr2,threshold=0.5):
"""
Values:
0 = background for arr1
2 = background for arr2
1 = signal for both arr1 and arr2
"""
arr1r = (arr1>threshold)*1
arr2r = (arr2>threshold)*1
arr2r[arr2r==0] = 2
over = np.sum(arr1r==arr2r)
arr1r_area = np.sum(arr1r==1)
arr2r_area = np.sum(arr2r==1)
arr1r_percent = over/arr1r_area
arr2r_percent = over/arr2r_area
return(over, arr1r_area, arr1r_percent, arr2r_area, arr2r_percent)
def process_images(df,
dichroic={0:'dmqb', 1:'dm4', 2:'dm4', 3:'dmqb', 4:'dmqb'},
jsonfilepath='./df_resources/shiftset.json',
input_directory='./images',
output_directory='./processed',
model_path='./df_resources/full_model.h5',
minx=2040,
miny=2040,
GAUSS=0.1,
TILE_SHAPE=(540,540),
PADDING=(184,184),
SEED=0,
EL_SIZE=[600, 600], #micrometers
BATCH_NORM=True,
LAMBDA=50, #50
V_BAL=0.1, #0.1
SIGMA_BAL=10, #10
SIGMA_SEP=6 #6
):
print(df)
fs = df.file_name.tolist()
full_fs = [os.path.join(input_directory, f) for f in fs]
for i in range(len(fs)):
out_path=os.path.join(output_directory, fs[i].split('.')[0])
if not os.path.exists(out_path):
os.makedirs(out_path)
img=io.imread(full_fs[i])
### SLOW: uncomment before use!!!!!!
# img = pixel_shift_3d(img, dichroic_dictionary=dichroic, json_file=jsonfilepath)
# img = correct_shift_upsampling(img)
img = convert_16_to_8(img)
save_tif_path=os.path.join(out_path, fs[i])
io.imsave(save_tif_path, img)
if len(img.shape) == 3:
image_list = [img[i] for i in range(img.shape[0])]
else:
image_list = [img]
for n in range(len(image_list)):
if image_list[n].shape != (miny, minx):
reshaped_img = resize(image_list[n], (miny, minx), anti_aliasing=True)
if GAUSS is not None:
reshaped_img = gaussian(reshaped_img, sigma=GAUSS)
image_list[n] = reshaped_img
image_list = [np.expand_dims(img, axis=2) for img in image_list]
img_sizes = [i.shape for i in image_list]
X_test = np.empty(((0,) + image_list[0].shape))
X_test = np.append(X_test, np.array(image_list), axis=0)
data_test = [{'rawdata': img, 'element_size_um': EL_SIZE} for img in X_test]
test_generator = preproc.TileGenerator(data = data_test,
instancelabels=None,
tile_shape=TILE_SHAPE,
padding=PADDING,
n_classes=2,
border_weight_sigma_px=SIGMA_SEP,
border_weight_factor=LAMBDA,
foreground_background_ratio=V_BAL)
model = unet.Unet2D(snapshot=model_path,
n_channels=1,
n_classes=2,
n_levels=4,
batch_norm = BATCH_NORM,
upsample=False,
relu_alpha=0.1,
n_features=64, name='U-Net')
prediction = model.predict(test_generator)
print()
# print(img.shape)
return(prediction)
| [
"numpy.iinfo",
"skimage.measure.approximate_polygon",
"df_resources.unet.Unet2D",
"numpy.array",
"shapely.geometry.Polygon",
"numpy.moveaxis",
"os.path.exists",
"numpy.asarray",
"numpy.empty",
"pandas.DataFrame",
"numpy.dtype",
"skimage.measure.regionprops",
"skimage.io.imread",
"df_resour... | [((1104, 1153), 'df_resources.pixelshift37.PixelShifter', 'pixelshift37.PixelShifter', ([], {'jsonfilepath': 'json_file'}), '(jsonfilepath=json_file)\n', (1129, 1153), False, 'from df_resources import unet, preproc, utils, pixelshift37\n'), ((1725, 1748), 'numpy.dstack', 'np.dstack', (['shifted_list'], {}), '(shifted_list)\n', (1734, 1748), True, 'import numpy as np\n'), ((1840, 1871), 'numpy.moveaxis', 'np.moveaxis', (['shifted_img', '(-1)', '(0)'], {}), '(shifted_img, -1, 0)\n', (1851, 1871), True, 'import numpy as np\n'), ((2419, 2441), 'numpy.iinfo', 'np.iinfo', (['np_img.dtype'], {}), '(np_img.dtype)\n', (2427, 2441), True, 'import numpy as np\n'), ((3168, 3241), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': "['cell_n', 'gene_name', 'row_pixels', 'col_pixels']"}), "(columns=['cell_n', 'gene_name', 'row_pixels', 'col_pixels'])\n", (3180, 3241), True, 'import pandas as pd\n'), ((3259, 3283), 'skimage.measure.regionprops', 'regionprops', (['labeled_arr'], {}), '(labeled_arr)\n', (3270, 3283), False, 'from skimage.measure import label, regionprops, approximate_polygon\n'), ((4556, 4578), 'numpy.sum', 'np.sum', (['(arr1r == arr2r)'], {}), '(arr1r == arr2r)\n', (4562, 4578), True, 'import numpy as np\n'), ((4594, 4612), 'numpy.sum', 'np.sum', (['(arr1r == 1)'], {}), '(arr1r == 1)\n', (4600, 4612), True, 'import numpy as np\n'), ((4628, 4646), 'numpy.sum', 'np.sum', (['(arr2r == 1)'], {}), '(arr2r == 1)\n', (4634, 4646), True, 'import numpy as np\n'), ((2021, 2039), 'numpy.dtype', 'np.dtype', (['"""uint16"""'], {}), "('uint16')\n", (2029, 2039), True, 'import numpy as np\n'), ((2477, 2495), 'numpy.dtype', 'np.dtype', (['"""uint16"""'], {}), "('uint16')\n", (2485, 2495), True, 'import numpy as np\n'), ((3341, 3397), 'skimage.measure.approximate_polygon', 'approximate_polygon', (['region_props[n].coords'], {'tolerance': '(2)'}), '(region_props[n].coords, tolerance=2)\n', (3360, 3397), False, 'from skimage.measure import label, regionprops, approximate_polygon\n'), ((3947, 3958), 'shapely.geometry.Polygon', 'Polygon', (['pp'], {}), '(pp)\n', (3954, 3958), False, 'from shapely.geometry import MultiPoint, Polygon\n'), ((4021, 4051), 'numpy.asarray', 'np.asarray', (['rr'], {'dtype': 'np.int16'}), '(rr, dtype=np.int16)\n', (4031, 4051), True, 'import numpy as np\n'), ((4065, 4095), 'numpy.asarray', 'np.asarray', (['cc'], {'dtype': 'np.int16'}), '(cc, dtype=np.int16)\n', (4075, 4095), True, 'import numpy as np\n'), ((5574, 5606), 'os.path.join', 'os.path.join', (['input_directory', 'f'], {}), '(input_directory, f)\n', (5586, 5606), False, 'import os\n'), ((5811, 5832), 'skimage.io.imread', 'io.imread', (['full_fs[i]'], {}), '(full_fs[i])\n', (5820, 5832), False, 'from skimage import io\n'), ((6072, 6101), 'os.path.join', 'os.path.join', (['out_path', 'fs[i]'], {}), '(out_path, fs[i])\n', (6084, 6101), False, 'import os\n'), ((6110, 6139), 'skimage.io.imsave', 'io.imsave', (['save_tif_path', 'img'], {}), '(save_tif_path, img)\n', (6119, 6139), False, 'from skimage import io\n'), ((6747, 6783), 'numpy.empty', 'np.empty', (['((0,) + image_list[0].shape)'], {}), '((0,) + image_list[0].shape)\n', (6755, 6783), True, 'import numpy as np\n'), ((6963, 7182), 'df_resources.preproc.TileGenerator', 'preproc.TileGenerator', ([], {'data': 'data_test', 'instancelabels': 'None', 'tile_shape': 'TILE_SHAPE', 'padding': 'PADDING', 'n_classes': '(2)', 'border_weight_sigma_px': 'SIGMA_SEP', 'border_weight_factor': 'LAMBDA', 'foreground_background_ratio': 'V_BAL'}), '(data=data_test, instancelabels=None, tile_shape=\n TILE_SHAPE, padding=PADDING, n_classes=2, border_weight_sigma_px=\n SIGMA_SEP, border_weight_factor=LAMBDA, foreground_background_ratio=V_BAL)\n', (6984, 7182), False, 'from df_resources import unet, preproc, utils, pixelshift37\n'), ((7465, 7628), 'df_resources.unet.Unet2D', 'unet.Unet2D', ([], {'snapshot': 'model_path', 'n_channels': '(1)', 'n_classes': '(2)', 'n_levels': '(4)', 'batch_norm': 'BATCH_NORM', 'upsample': '(False)', 'relu_alpha': '(0.1)', 'n_features': '(64)', 'name': '"""U-Net"""'}), "(snapshot=model_path, n_channels=1, n_classes=2, n_levels=4,\n batch_norm=BATCH_NORM, upsample=False, relu_alpha=0.1, n_features=64,\n name='U-Net')\n", (7476, 7628), False, 'from df_resources import unet, preproc, utils, pixelshift37\n'), ((2161, 2178), 'numpy.dtype', 'np.dtype', (['"""uint8"""'], {}), "('uint8')\n", (2169, 2178), True, 'import numpy as np\n'), ((2777, 2794), 'numpy.dtype', 'np.dtype', (['"""uint8"""'], {}), "('uint8')\n", (2785, 2794), True, 'import numpy as np\n'), ((5734, 5758), 'os.path.exists', 'os.path.exists', (['out_path'], {}), '(out_path)\n', (5748, 5758), False, 'import os\n'), ((5772, 5793), 'os.makedirs', 'os.makedirs', (['out_path'], {}), '(out_path)\n', (5783, 5793), False, 'import os\n'), ((6628, 6655), 'numpy.expand_dims', 'np.expand_dims', (['img'], {'axis': '(2)'}), '(img, axis=2)\n', (6642, 6655), True, 'import numpy as np\n'), ((6821, 6841), 'numpy.array', 'np.array', (['image_list'], {}), '(image_list)\n', (6829, 6841), True, 'import numpy as np\n'), ((2993, 3023), 'os.path.join', 'os.path.join', (['img_directory', 'f'], {}), '(img_directory, f)\n', (3005, 3023), False, 'import os\n'), ((6406, 6461), 'skimage.transform.resize', 'resize', (['image_list[n]', '(miny, minx)'], {'anti_aliasing': '(True)'}), '(image_list[n], (miny, minx), anti_aliasing=True)\n', (6412, 6461), False, 'from skimage.transform import resize\n'), ((6527, 6562), 'skimage.filters.gaussian', 'gaussian', (['reshaped_img'], {'sigma': 'GAUSS'}), '(reshaped_img, sigma=GAUSS)\n', (6535, 6562), False, 'from skimage.filters import gaussian\n'), ((3865, 3907), 'math.atan2', 'math.atan2', (['(p[1] - cent[1])', '(p[0] - cent[0])'], {}), '(p[1] - cent[1], p[0] - cent[0])\n', (3875, 3907), False, 'import math\n')] |
"""
Copyright (C) Cortic Technology Corp. - All Rights Reserved
Written by <NAME> <<EMAIL>>, 2021
"""
import cv2
import numpy as np
FINGER_COLOR = [
(128, 128, 128),
(80, 190, 168),
(234, 187, 105),
(175, 119, 212),
(81, 110, 221),
]
JOINT_COLOR = [(0, 0, 0), (125, 255, 79), (255, 102, 0), (181, 70, 255), (13, 63, 255)]
class circularlist(object):
def __init__(self, size, data = []):
"""Initialization"""
self.index = 0
self.size = size
self._data = list(data)[-size:]
def append(self, value):
"""Append an element"""
if len(self._data) == self.size:
self._data[self.index] = value
else:
self._data.append(value)
self.index = (self.index + 1) % self.size
def __getitem__(self, key):
"""Get element by index, relative to the current index"""
if len(self._data) == self.size:
return(self._data[(key + self.index) % self.size])
else:
return(self._data[key])
def __repr__(self):
"""Return string representation"""
return self._data.__repr__() + ' (' + str(len(self._data))+' items)'
def calc_average(self):
num_data = len(self._data)
sum = 0
if num_data == 0:
return 0
for val in self._data:
sum = sum + val
return(float(sum)/num_data)
def draw_object_imgs(image, object_img, x1, y1, x2, y2, alpha):
if x1 >= 0 and y1 >= 0 and x2 < image.shape[1] and y2 < image.shape[0]:
object_alpha = object_img[:, :, 3] / 255.0
combined_alpha = object_alpha * alpha
y2 = y2 + (object_img.shape[0] - (y2 - y1))
image[y1:y2, x1:x2, 0] = (1.0 - combined_alpha) * image[
y1:y2, x1:x2, 0
] + combined_alpha * object_img[:, :, 0]
image[y1:y2, x1:x2, 1] = (1.0 - combined_alpha) * image[
y1:y2, x1:x2, 1
] + combined_alpha * object_img[:, :, 1]
image[y1:y2, x1:x2, 2] = (1.0 - combined_alpha) * image[
y1:y2, x1:x2, 2
] + combined_alpha * object_img[:, :, 2]
def frame_norm(frame, bbox):
norm_vals = np.full(len(bbox), frame.shape[0])
norm_vals[::2] = frame.shape[1]
return (np.clip(np.array(bbox), 0, 1) * norm_vals).astype(int)
def draw_hand_landmarks(img, hands, zoom_mode, single_handed):
list_connections = [
[0, 1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16],
[17, 18, 19, 20],
]
for hand in hands:
lm_xy = []
for landmark in hand.landmarks:
lm_xy.append([int(landmark[0]), int(landmark[1])])
palm_line = [np.array([lm_xy[point] for point in [0, 5, 9, 13, 17, 0]])]
cv2.polylines(img, palm_line, False, (255, 255, 255), 2, cv2.LINE_AA)
for i in range(len(list_connections)):
finger = list_connections[i]
line = [np.array([lm_xy[point] for point in finger])]
cv2.polylines(img, line, False, FINGER_COLOR[i], 2, cv2.LINE_AA)
for point in finger:
pt = lm_xy[point]
cv2.circle(img, (pt[0], pt[1]), 3, JOINT_COLOR[i], -1)
if single_handed:
if zoom_mode:
cv2.line(img, (lm_xy[4][0], lm_xy[4][1]), (lm_xy[8][0], lm_xy[8][1]), (0, 255, 0), 2, cv2.LINE_AA)
return img
def draw_zoom_scale(frame, translation_z, max_scale, screen_height):
scale = (translation_z + max_scale) / (max_scale - (-max_scale))
bar_height = int(scale * (screen_height // 3 + 2))
cv2.rectangle(frame, (40, screen_height - 40), (60, screen_height - 40 - screen_height // 3), (255, 255, 255), 1, 1)
cv2.rectangle(frame, (40 + 2, screen_height - 40 - 1), (60 - 2, screen_height - 40 - 1 - bar_height), (80, 190, 168), -1, 1) | [
"cv2.rectangle",
"cv2.polylines",
"cv2.line",
"numpy.array",
"cv2.circle"
] | [((3574, 3695), 'cv2.rectangle', 'cv2.rectangle', (['frame', '(40, screen_height - 40)', '(60, screen_height - 40 - screen_height // 3)', '(255, 255, 255)', '(1)', '(1)'], {}), '(frame, (40, screen_height - 40), (60, screen_height - 40 - \n screen_height // 3), (255, 255, 255), 1, 1)\n', (3587, 3695), False, 'import cv2\n'), ((3695, 3824), 'cv2.rectangle', 'cv2.rectangle', (['frame', '(40 + 2, screen_height - 40 - 1)', '(60 - 2, screen_height - 40 - 1 - bar_height)', '(80, 190, 168)', '(-1)', '(1)'], {}), '(frame, (40 + 2, screen_height - 40 - 1), (60 - 2, \n screen_height - 40 - 1 - bar_height), (80, 190, 168), -1, 1)\n', (3708, 3824), False, 'import cv2\n'), ((2754, 2823), 'cv2.polylines', 'cv2.polylines', (['img', 'palm_line', '(False)', '(255, 255, 255)', '(2)', 'cv2.LINE_AA'], {}), '(img, palm_line, False, (255, 255, 255), 2, cv2.LINE_AA)\n', (2767, 2823), False, 'import cv2\n'), ((2686, 2744), 'numpy.array', 'np.array', (['[lm_xy[point] for point in [0, 5, 9, 13, 17, 0]]'], {}), '([lm_xy[point] for point in [0, 5, 9, 13, 17, 0]])\n', (2694, 2744), True, 'import numpy as np\n'), ((2990, 3054), 'cv2.polylines', 'cv2.polylines', (['img', 'line', '(False)', 'FINGER_COLOR[i]', '(2)', 'cv2.LINE_AA'], {}), '(img, line, False, FINGER_COLOR[i], 2, cv2.LINE_AA)\n', (3003, 3054), False, 'import cv2\n'), ((2932, 2976), 'numpy.array', 'np.array', (['[lm_xy[point] for point in finger]'], {}), '([lm_xy[point] for point in finger])\n', (2940, 2976), True, 'import numpy as np\n'), ((3138, 3192), 'cv2.circle', 'cv2.circle', (['img', '(pt[0], pt[1])', '(3)', 'JOINT_COLOR[i]', '(-1)'], {}), '(img, (pt[0], pt[1]), 3, JOINT_COLOR[i], -1)\n', (3148, 3192), False, 'import cv2\n'), ((3261, 3364), 'cv2.line', 'cv2.line', (['img', '(lm_xy[4][0], lm_xy[4][1])', '(lm_xy[8][0], lm_xy[8][1])', '(0, 255, 0)', '(2)', 'cv2.LINE_AA'], {}), '(img, (lm_xy[4][0], lm_xy[4][1]), (lm_xy[8][0], lm_xy[8][1]), (0, \n 255, 0), 2, cv2.LINE_AA)\n', (3269, 3364), False, 'import cv2\n'), ((2254, 2268), 'numpy.array', 'np.array', (['bbox'], {}), '(bbox)\n', (2262, 2268), True, 'import numpy as np\n')] |
import time,calendar,os,json,sys,datetime
from requests import get
from subprocess import Popen,PIPE
from math import sqrt,log,exp
from scipy.optimize import minimize
import numpy as np
np.set_printoptions(precision=3,linewidth=120)
def datetoday(x):
t=time.strptime(x+'UTC','%Y-%m-%d%Z')
return calendar.timegm(t)//86400
def daytodate(r):
t=time.gmtime(r*86400)
return time.strftime('%Y-%m-%d',t)
def get_data(req):
url='https://api.coronavirus.data.gov.uk/v1/data?'
response = get(url+req, timeout=10)
if not response.ok:
raise RuntimeError(f'Request failed: { response.text }')
date=time.strftime('%Y-%m-%d',time.strptime(response.headers['Last-Modified'],'%a, %d %b %Y %H:%M:%S %Z'))# Not currently used
data=response.json()['data']
# Convert from list form to dictionary keyed by age
day=datetoday(data[0]['date'])
n=1
while n<len(data) and datetoday(data[n]['date'])==day-n: n+=1# Find maximal contiguous date range
data1=[]
for i in range(n-1,-1,-1):
d=data[i]
e={'date':d['date']}
for x in d:
if x!='date':
for y in d[x]:
if 'value' in y: val=y['value']
else: val=y['deaths']
e[y['age']]=e.get(y['age'],0)+val
data1.append(e)
return data1
req='filters=areaType=nation;areaName=england&structure={"date":"date","blah":"newDeaths28DaysByDeathDateAgeDemographics"}'; mortdata=get_data(req)
req='filters=areaType=nation;areaName=england&structure={"date":"date","blah":"cumAdmissionsByAge"}'; hospdata=get_data(req)
req='filters=areaType=nation;areaName=england&structure={"date":"date","male":"maleCases"}'; malecases=get_data(req)
req='filters=areaType=nation;areaName=england&structure={"date":"date","female":"femaleCases"}'; femalecases=get_data(req)
casedata=[]
for (m,f) in zip(malecases,femalecases):
d={'date': m['date']}
assert m['date']==f['date']
for s in [m,f]:
for x in s:
if x!='date': d[x]=d.get(x,0)+s[x]
casedata.append(d)
updatedate=casedata[-1]['date']
now=datetime.datetime.utcnow().strftime('%Y-%m-%d')
# Save case data because we might want to artificially implement cases-by-publication-date-and-age. (newCasesByPublishDateAgeDemographics not working)
fn=os.path.join('apidata',updatedate)
if len(sys.argv)==1 and os.path.isfile(fn): sys.exit(1)# Exit signalling no update needs to be done
os.makedirs('apidata', exist_ok=True)
with open(fn,'w') as fp:
json.dump(casedata,fp,indent=2)
def getdiff(data):
n=len(data)
newdata=[]
for i in range(1,n):
l={'date':data[i]['date']}
for age in data[i]:
if age!='date': l[age]=data[i][age]-data[i-1].get(age,0)
newdata.append(l)
return newdata
newhosp=getdiff(hospdata)
newcases=getdiff(casedata)
newmcases=getdiff(malecases)
newfcases=getdiff(femalecases)
newcases=newcases[:-1]# Last entry seems particularly unreliable, I think because it using specimen date and there are biases with recent entries
newmcases=newmcases[:-1]
newfcases=newfcases[:-1]
# Convert (eg) string ages '15_19', '15_to_19', '60+' to (15,20), (15,20), (60,150) respectively
def parseage(x):
if x[-1]=='+': return (int(x[:-1]),150)
x=x.replace('_to_','_')# cater for 65_to_69 and 65_69 formats
aa=[int(y) for y in x.split("_")]
return (aa[0],aa[1]+1)
# Convert (eg) (15,20) to "15 - 19"
def unparse(r):
(a,b)=r
if b==150: return "%d+"%a
return "%d - %d"%(a,b)
# Convert dictionary from using '15_19' (etc) format to (15,20) format
# At the same time remove age brackets such as '60+' and '00_59' that strictly contain other age brackets, so avoiding overcounting
# Return list of ages
def convertages(dd):
ages0=[(x,parseage(x)) for x in dd[-1] if x!='date']
ages1={}
for (x,(a,b)) in ages0:
for (y,(c,d)) in ages0:
if c>=a and d<=b and (c>a or d<b): break
else: ages1[x]=(a,b)
ee=[]
for d in dd:
e={}
e['date']=d['date']
for x in ages1:
e[ages1[x]]=d.get(x,0)
ee.append(e)
ages2=sorted(ages1.values())
return (ee,ages2)
#date=max(hosp[-1]['date'],cases[-1]['date'])
#mindate=daytodate(datetoday(updatedate)-90)
mindate='2020-12-30'#daytodate(datetoday(updatedate)-90)
hosp,hospages=convertages(newhosp)
cases,caseages=convertages(newcases)
deaths,deathages=convertages(mortdata)
fcases,_=convertages(newfcases)
mcases,_=convertages(newmcases)
# For fancysmooth - not currently used
smoothness=1e6
def LL(rr,xx,lx):
L=0
n=len(rr)
er=np.exp(rr)
for i in range(7):
x=xx[i::7].sum()
ew=x/(er[i::7].sum())
L+=x*log(ew)
# xx.lx is only a constant, but subtracting makes LL more meaningful and keeps it in a better range of values
L+=(xx*(rr-lx)).sum()
dd=-rr[:-2]+2*rr[1:-1]-rr[2:]
t=(dd*dd).sum()
#s=(rr*rr).sum();L-=n*log(t/s)
L-=smoothness/2*t
# Seems that scaling down objective function to control precision works significantly better than reducing tolerance in SLSQP (option ftol)
return -L/n/300
# Not currently used
def fancysmooth1(data):
deb=0
ages=[x for x in data[0].keys() if x!='date']
xx=np.array([sum(d[age] for age in ages) for d in data])
lx=np.log(xx)
n=len(xx)
# Convenient to optimise in the 'gauge' rr.sum()=0 because it doesn't involve xx (minimize can't handle auxiliary variables?) but transform to other gauge afterwards
# (Actually, probably don't need this constraint)
constr={'type':'eq', 'fun':lambda rr: rr.sum()}
# bounds=[(-30,30) for d in range(n)]
res=minimize(LL,np.zeros(n),args=(xx,lx),method="SLSQP",constraints=[constr],options={"maxiter":10000})
if not res.success: raise RuntimeError(res.message)
if deb: print(res.nit,"iterations")
rr=res.x
if deb: print(LL(rr,xx,lx));print()
# Regauge to put underlying Poisson parameter on the same footing as original data
rr+=log(xx.sum()/np.exp(rr).sum())
er=np.exp(rr)
if deb:
ww=[log(xx[i::7].sum()/er[i::7].sum()) for i in range(7)]
vv=[ww[d%7] for d in range(n)]
ev=np.exp(vv)
print((-np.exp(vv+rr).sum()))
print((xx*(vv+rr-lx)).sum())
dd=-rr[:-2]+2*rr[1:-1]-rr[2:]
t=(dd*dd).sum()
s=(rr*rr).sum()
print(-smoothness/2*t,n*log(t/s))
aa=[xx[i::7].sum()/len(xx[i::7]) for i in range(7)]
bb=[aa[d%7] for d in range(n)]
yy=xx/bb
yy*=xx.sum()/yy.sum()
with open('temp','w') as fp:
for i in range(n):
print("%12g %12g %12g %12g %12g"%(xx[i],er[i],ev[i],er[i]*ev[i],yy[i]),file=fp)
return
def simplesmooth1(data):
n=len(data)
ages=[x for x in data[0].keys() if x!='date']
xx=np.array([sum(d[age] for age in ages) for d in data])
ww=[xx[i::7].sum()/len(xx[i::7]) for i in range(7)]
vv=np.array([ww[d%7] for d in range(n)])
vv*=(xx/vv).sum()/xx.sum()
smoothed=[]
for d in range(n):
di={'date': data[d]['date']}
for age in ages:
di[age]=data[d][age]/vv[d]
smoothed.append(di)
return smoothed
def simplesmooth2(data):
ages=[x for x in data[0].keys() if x!='date']
n=len(data)
smoothed=[]
for i in range(n):
d={'date': data[i]['date']}
j0=max(i-3,0)
j1=min(i+4,n)
for age in ages:
d[age]=sum(data[j][age] for j in range(j0,j1))/(j1-j0)
smoothed.append(d)
return smoothed
def smooth(data):
#return data
#return simplesmooth1(data)
#return simplesmooth2(data)
return simplesmooth2(simplesmooth1(data))
hosp=smooth(hosp)
cases=smooth(cases)
deaths=smooth(deaths)
mcases=smooth(mcases)
fcases=smooth(fcases)
def makegraph(title='A graph', data=[], mindate='0000-00-00', ylabel='', outfn='temp.png', extra=[]):
po=Popen("gnuplot",shell=True,stdin=PIPE);p=po.stdin
# Use this to cater for earlier versions of Python whose Popen()s don't have the 'encoding' keyword
def write(*s): p.write((' '.join(map(str,s))+'\n').encode('utf-8'))
write('set terminal pngcairo font "sans,13" size 1920,1280')
write('set bmargin 5;set lmargin 15;set rmargin 15;set tmargin 5')
write('set output "%s"'%outfn)
write('set for [i=9:16] linetype i dashtype (20,7)')
write('set key right')
write('set title "%s"'%title)
write('set ylabel "'+ylabel+'"')
write('set xdata time')
write('set format x "%Y-%m-%d"')
write('set timefmt "%Y-%m-%d"')
write('set tics scale 2,0.5')
write('set xtics "2020-01-06", 604800')#%startdate)# Date labels on Mondays
write('set xtics rotate by 45 right offset 0.5,0')
write('set grid xtics ytics lc rgb "#dddddd" lt 1')
write('set xtics nomirror')
for x in extra: write(x)
s='plot '
first=True
for dat in data:
if not first: s+=', '
first=False
s+='"-" using 1:2 with lines '+dat.get('extra','')+' lw 3 title "%s"'%(dat['title'])
write(s)
for dat in data:
for (date,val) in dat['values']:
if date>=mindate: write(date,val)
write("e")
p.close();po.wait()
print("Written graph to %s"%outfn)
if 0:
days=(range(330,340),[-1])
ll=[]
for (ages,numthings,desc) in [(caseages,cases,"cases"), (deathages,deaths,"deaths")]:
aa={}
dd={}
for end in [0,1]:
for cut in [x[0] for x in ages]+[150]:
dd[(end,cut)]=sum(numthings[day][age] for day in days[end] for age in ages if age[0]<cut)/len(days[end])
n=len(ages)
for c0 in range(n-2):
cut0=ages[c0][0]
for c1 in range(c0+1,n-1):
cut1=ages[c1][0]
for c2 in range(c1,n):
cut2=ages[c2][0]
rr=[]
for end in [0,1]:
rr.append(dd[(end,cut1)]-dd[(end,cut0)])
rr.append(dd[(end,150)] -dd[(end,cut2)])
if min(rr)>=10:
aa[cut0,cut1,cut2]=rr[1]/rr[0]/(rr[3]/rr[2])
ll.append(aa)
l=[]
for x in ll[0]:
if x in ll[1]:
l.append((sqrt(ll[0][x]*ll[1][x]),*x))
l.sort(reverse=True)
for (r,cut0,cut1,cut2) in l:
if cut2<=70: print("%2d %2d %2d %7.3f"%(cut0,cut1,cut2,r))
if r<0.9*l[0][0]: break
title='Hospital admissions and confirmed cases/deaths ratios for Covid-19 in England, adjusted to be 1 on 1st January 2021\\nLast few values subject to change. Source: https://coronavirus.data.gov.uk/ at '+now
data=[]
for (desc, dat, ages, cutoff0, cutoff1, cutoff2) in [
("Hospital admissions", hosp, hospages, 0, 18, 65),
("Confirmed cases", cases, caseages, 0, 50, 55),
("Deaths", deaths, deathages, 0, 50, 55)]:
lowages=[age for age in ages if age[0]>=cutoff0 and age[1]<=cutoff1]
highages=[age for age in ages if age[0]>=cutoff2]
for d in dat:
if d["date"]=="2021-01-01": break
f=sum(d[a] for a in highages)/sum(d[a] for a in lowages)
if desc=="Deaths": maxdate="2021-03-29"
else: maxdate="9999-99-99"
data.append({
'title': desc+": %.2g * (aged %s) / (aged %s)"%(1/f,unparse((highages[0][0],highages[-1][1])),unparse((lowages[0][0],lowages[-1][1]))),
'values': [(d['date'],sum(d[a] for a in highages)/sum(d[a] for a in lowages)/f) for d in dat if d['date']>=mindate and d['date']<=maxdate]
})
makegraph(title=title, data=data, mindate=mindate, ylabel='Adjusted Ratio', outfn='admissionandcaseageratios2.png')
#################################
# Old graphs (14 Jan - 5 March) #
#################################
title='Hospital admissions and confirmed cases/deaths ratios for Covid-19 in England. Last few values subject to change.\\nSource: https://coronavirus.data.gov.uk/ at '+now
cutoff0=65;cutoff1=150;cutoff2=80
data=[]
data.append({
'title': 'Hospital admissions: (aged 85+) / (aged 18-64 or 85+)',
'values': [(d['date'],(d[(85,150)])/(d[(18,65)]+d[(85,150)])*100) for d in hosp if d['date']>=mindate]
})
lowages=[age for age in caseages if age[0]>=cutoff0 and age[1]<=cutoff1]
highages=[age for age in caseages if age[0]>=cutoff2]
data.append({
'title': 'Confirmed cases: (aged %s) / (aged %s)'%(unparse((cutoff2,150)),unparse((cutoff0,cutoff1))),
'values': [(d['date'],sum(d[a] for a in highages)/sum(d[a] for a in lowages)*100) for d in cases if d['date']>=mindate]
})
lowages=[age for age in deathages if age[0]>=cutoff0 and age[1]<=cutoff1]
highages=[age for age in deathages if age[0]>=cutoff2]
data.append({
'title': 'Deaths: (aged %s) / (aged %s) - 25%%'%(unparse((cutoff2,150)),unparse((cutoff0,cutoff1))),
'values': [(d['date'],sum(d[a] for a in highages)/sum(d[a] for a in lowages)*100-25) for d in deaths if d['date']>=mindate],
#'extra': 'axis x1y2'
})
makegraph(title=title, data=data, mindate=mindate, ylabel='Percentage', outfn='admissionandcaseageratios.png')
########################
data=[]
lowages=[age for age in caseages if age[0]>=16 and age[1]<=65]
data.append({
'title': 'Confirmed cases: #(female aged 16-65) / #(male aged 16-65)',
'values': [(f['date'],sum(f[a] for a in lowages)/sum(m[a] for a in lowages)) for (f,m) in zip(fcases,mcases) if f['date']>=mindate]
})
makegraph(title=title, data=data, mindate=mindate, ylabel='Ratio', outfn='femalemalecaseratio.png')
########################
data=[]
for age in [(18,65), (65,85), (85,150)]:
data.append({
'title': unparse(age),
'values': [(d['date'],d[age]) for d in hosp]
})
title='Hospital admissions for Covid-19 in England by age group. Last few values subject to change.\\nSource: https://coronavirus.data.gov.uk/ at '+now
makegraph(title=title, data=data, mindate=mindate, ylabel='Number of age group admitted', outfn='hospitaladmissionsbyage-abs.png')
########################
# Todo when can be bothered: normalise this by number in each age group
data=[]
for ageband in range(0,90,10):
if ageband<80: lim=ageband+10
else: lim=150
data.append({
'title': unparse((ageband,lim)),
'values': [(d['date'],sum(d[age] for age in caseages if age[0]>=ageband and age[1]<=lim)) for d in cases]
})
title='Confirmed cases per day for Covid-19 in England by age group. Last few values subject to change.\\nSource: https://coronavirus.data.gov.uk/ at '+now
makegraph(title=title, data=data, mindate=mindate, ylabel='Number of cases per day', outfn='confirmedcasesbyage-abs.png')#, extra=['set logscale y'])
if 0:
# Looking at hospitalisations per case
ave=14
delay=10
for t in range(-ave,-250,-ave):
print(cases[t]['date']+":",end='')
for age in hospages:
print(" %s:"%str(age),end='')
nh=nc=0
for i in range(ave):
nh+=hosp[t+i][age]
c=cases[t+i-delay]
for a in c:
if a=='date': continue
if a[0]>=age[0] and a[1]<=age[1]: nc+=c[a]
print("%5.1f"%(nh/nc*100),end='')
print()
print()
for t in range(-ave,-250,-ave):
nh=nc=0
for i in range(ave):
nh+=sum(hosp[t+i][x] for x in hospages)
nc+=sum(cases[t+i-delay][x] for x in caseages)
print("%s: %5.1f"%(cases[t]['date'],nh/nc*100))
| [
"time.strptime",
"os.makedirs",
"datetime.datetime.utcnow",
"subprocess.Popen",
"time.strftime",
"os.path.join",
"numpy.log",
"requests.get",
"math.log",
"os.path.isfile",
"numpy.exp",
"calendar.timegm",
"numpy.zeros",
"math.sqrt",
"sys.exit",
"time.gmtime",
"json.dump",
"numpy.set... | [((186, 233), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'precision': '(3)', 'linewidth': '(120)'}), '(precision=3, linewidth=120)\n', (205, 233), True, 'import numpy as np\n'), ((2252, 2287), 'os.path.join', 'os.path.join', (['"""apidata"""', 'updatedate'], {}), "('apidata', updatedate)\n", (2264, 2287), False, 'import time, calendar, os, json, sys, datetime\n'), ((2387, 2424), 'os.makedirs', 'os.makedirs', (['"""apidata"""'], {'exist_ok': '(True)'}), "('apidata', exist_ok=True)\n", (2398, 2424), False, 'import time, calendar, os, json, sys, datetime\n'), ((256, 294), 'time.strptime', 'time.strptime', (["(x + 'UTC')", '"""%Y-%m-%d%Z"""'], {}), "(x + 'UTC', '%Y-%m-%d%Z')\n", (269, 294), False, 'import time, calendar, os, json, sys, datetime\n'), ((350, 372), 'time.gmtime', 'time.gmtime', (['(r * 86400)'], {}), '(r * 86400)\n', (361, 372), False, 'import time, calendar, os, json, sys, datetime\n'), ((380, 408), 'time.strftime', 'time.strftime', (['"""%Y-%m-%d"""', 't'], {}), "('%Y-%m-%d', t)\n", (393, 408), False, 'import time, calendar, os, json, sys, datetime\n'), ((494, 520), 'requests.get', 'get', (['(url + req)'], {'timeout': '(10)'}), '(url + req, timeout=10)\n', (497, 520), False, 'from requests import get\n'), ((2311, 2329), 'os.path.isfile', 'os.path.isfile', (['fn'], {}), '(fn)\n', (2325, 2329), False, 'import time, calendar, os, json, sys, datetime\n'), ((2331, 2342), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (2339, 2342), False, 'import time, calendar, os, json, sys, datetime\n'), ((2452, 2485), 'json.dump', 'json.dump', (['casedata', 'fp'], {'indent': '(2)'}), '(casedata, fp, indent=2)\n', (2461, 2485), False, 'import time, calendar, os, json, sys, datetime\n'), ((4470, 4480), 'numpy.exp', 'np.exp', (['rr'], {}), '(rr)\n', (4476, 4480), True, 'import numpy as np\n'), ((5131, 5141), 'numpy.log', 'np.log', (['xx'], {}), '(xx)\n', (5137, 5141), True, 'import numpy as np\n'), ((5843, 5853), 'numpy.exp', 'np.exp', (['rr'], {}), '(rr)\n', (5849, 5853), True, 'import numpy as np\n'), ((7546, 7586), 'subprocess.Popen', 'Popen', (['"""gnuplot"""'], {'shell': '(True)', 'stdin': 'PIPE'}), "('gnuplot', shell=True, stdin=PIPE)\n", (7551, 7586), False, 'from subprocess import Popen, PIPE\n'), ((301, 319), 'calendar.timegm', 'calendar.timegm', (['t'], {}), '(t)\n', (316, 319), False, 'import time, calendar, os, json, sys, datetime\n'), ((634, 710), 'time.strptime', 'time.strptime', (["response.headers['Last-Modified']", '"""%a, %d %b %Y %H:%M:%S %Z"""'], {}), "(response.headers['Last-Modified'], '%a, %d %b %Y %H:%M:%S %Z')\n", (647, 710), False, 'import time, calendar, os, json, sys, datetime\n'), ((2049, 2075), 'datetime.datetime.utcnow', 'datetime.datetime.utcnow', ([], {}), '()\n', (2073, 2075), False, 'import time, calendar, os, json, sys, datetime\n'), ((5483, 5494), 'numpy.zeros', 'np.zeros', (['n'], {}), '(n)\n', (5491, 5494), True, 'import numpy as np\n'), ((5968, 5978), 'numpy.exp', 'np.exp', (['vv'], {}), '(vv)\n', (5974, 5978), True, 'import numpy as np\n'), ((4558, 4565), 'math.log', 'log', (['ew'], {}), '(ew)\n', (4561, 4565), False, 'from math import sqrt, log, exp\n'), ((6148, 6158), 'math.log', 'log', (['(t / s)'], {}), '(t / s)\n', (6151, 6158), False, 'from math import sqrt, log, exp\n'), ((5817, 5827), 'numpy.exp', 'np.exp', (['rr'], {}), '(rr)\n', (5823, 5827), True, 'import numpy as np\n'), ((9633, 9658), 'math.sqrt', 'sqrt', (['(ll[0][x] * ll[1][x])'], {}), '(ll[0][x] * ll[1][x])\n', (9637, 9658), False, 'from math import sqrt, log, exp\n'), ((5991, 6006), 'numpy.exp', 'np.exp', (['(vv + rr)'], {}), '(vv + rr)\n', (5997, 6006), True, 'import numpy as np\n')] |
#!/usr/bin/env python
import argparse
import random
import numpy as np
import numpy.linalg as nplg
if __name__ == "__main__":
# FLAGS
# --------------------------------------------------------------------------
parser = argparse.ArgumentParser(
description='Picks imagemagick modulation within range that is reasonably ' +
'far from the modulations already done -- to ensure variety of materials.')
parser.add_argument(
'--past_modulations', action='store', type=str, required=True,
help='File with past modulations of the form: hsv 100 200 150')
parser.add_argument(
'--modulation_ranges', action='store', type=str, required=True,
help='File with 3 lines: hue MIN MAX; sat MIN MAX; val MIN MAX')
parser.add_argument(
'--n', action='store', type=str, default=7,
help='Number of attempts to pick furthest modulation.')
args = parser.parse_args()
with open(args.past_modulations) as f:
past_vals = [np.array([int(c) for c in v[1:]], dtype=np.float32)
for v in [x.strip().split() for x in f.readlines()]
if len(v) > 0]
with open(args.modulation_ranges) as f:
ranges = dict([(v[0], (int(v[1]), int(v[2])))
for v in [x.strip().split() for x in f.readlines()]
if len(v) > 0])
if 'val' not in ranges and 'value' in ranges:
ranges['val'] = ranges['value']
if 'hue' not in ranges or 'sat' not in ranges or 'val' not in ranges:
raise RuntimeError('Did not find hue/val/sat in %s' % args.modulation_ranges)
largest_dist = -1
furthest_val = None
for i in range(args.n):
val = np.array(
[random.randint(ranges['hue'][0], ranges['hue'][1]),
random.randint(ranges['sat'][0], ranges['sat'][1]),
random.randint(ranges['val'][0], ranges['val'][1])],
dtype=np.float32)
if len(past_vals) == 0:
furthest_val = val
break
best_dist = -1
for pval in past_vals:
dist = nplg.norm(val - pval)
if best_dist < 0 or dist < best_dist:
smallest_dist = dist
if largest_dist < 0 or best_dist > largest_dist:
furthest_val = val
largest_dist = best_dist
print('%d %d %d' % (int(furthest_val[0]), int(furthest_val[1]), int(furthest_val[2])))
| [
"random.randint",
"argparse.ArgumentParser",
"numpy.linalg.norm"
] | [((235, 421), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': "('Picks imagemagick modulation within range that is reasonably ' +\n 'far from the modulations already done -- to ensure variety of materials.')"}), "(description=\n 'Picks imagemagick modulation within range that is reasonably ' +\n 'far from the modulations already done -- to ensure variety of materials.')\n", (258, 421), False, 'import argparse\n'), ((2112, 2133), 'numpy.linalg.norm', 'nplg.norm', (['(val - pval)'], {}), '(val - pval)\n', (2121, 2133), True, 'import numpy.linalg as nplg\n'), ((1744, 1794), 'random.randint', 'random.randint', (["ranges['hue'][0]", "ranges['hue'][1]"], {}), "(ranges['hue'][0], ranges['hue'][1])\n", (1758, 1794), False, 'import random\n'), ((1809, 1859), 'random.randint', 'random.randint', (["ranges['sat'][0]", "ranges['sat'][1]"], {}), "(ranges['sat'][0], ranges['sat'][1])\n", (1823, 1859), False, 'import random\n'), ((1874, 1924), 'random.randint', 'random.randint', (["ranges['val'][0]", "ranges['val'][1]"], {}), "(ranges['val'][0], ranges['val'][1])\n", (1888, 1924), False, 'import random\n')] |
from skued import nfft, nfftfreq
import unittest
import numpy as np
np.random.seed(23)
class Testnfftfreq(unittest.TestCase):
def test_shape_even(self):
""" Test that the nfftfreq function returns expected shape """
freqs = nfftfreq(16)
self.assertTupleEqual(freqs.shape, (16,))
def test_shape_odd(self):
""" Test that the nfftfreq function returns expected shape """
freqs = nfftfreq(13)
self.assertTupleEqual(freqs.shape, (13,))
class Testnfft(unittest.TestCase):
def test_against_fft(self):
""" Test against goold ol' FFT on evenly spaced data """
x = np.linspace(0, 10, num=128)
y = np.sin(2 * np.pi * x)
k = np.fft.fftfreq(y.size)
knfft = nfftfreq(len(x), df=1)
dft = np.fft.fft(y)
from_nfft = nfft(x, y, M=len(x))
if __name__ == "__main__":
unittest.main()
| [
"numpy.sin",
"numpy.fft.fftfreq",
"numpy.fft.fft",
"numpy.linspace",
"numpy.random.seed",
"unittest.main",
"skued.nfftfreq"
] | [((70, 88), 'numpy.random.seed', 'np.random.seed', (['(23)'], {}), '(23)\n', (84, 88), True, 'import numpy as np\n'), ((879, 894), 'unittest.main', 'unittest.main', ([], {}), '()\n', (892, 894), False, 'import unittest\n'), ((248, 260), 'skued.nfftfreq', 'nfftfreq', (['(16)'], {}), '(16)\n', (256, 260), False, 'from skued import nfft, nfftfreq\n'), ((429, 441), 'skued.nfftfreq', 'nfftfreq', (['(13)'], {}), '(13)\n', (437, 441), False, 'from skued import nfft, nfftfreq\n'), ((639, 666), 'numpy.linspace', 'np.linspace', (['(0)', '(10)'], {'num': '(128)'}), '(0, 10, num=128)\n', (650, 666), True, 'import numpy as np\n'), ((679, 700), 'numpy.sin', 'np.sin', (['(2 * np.pi * x)'], {}), '(2 * np.pi * x)\n', (685, 700), True, 'import numpy as np\n'), ((714, 736), 'numpy.fft.fftfreq', 'np.fft.fftfreq', (['y.size'], {}), '(y.size)\n', (728, 736), True, 'import numpy as np\n'), ((791, 804), 'numpy.fft.fft', 'np.fft.fft', (['y'], {}), '(y)\n', (801, 804), True, 'import numpy as np\n')] |
"""
Module: LMR_verify_gridRNL.py
Purpose: Generates spatial verification statistics of various LMR gridded fields
against 20th century reanalyses.
Originator: <NAME>, U. of Washington, March 2016
Revisions:
"""
import matplotlib
# need to do this backend when running remotely or to suppress figures interactively
matplotlib.use('Agg')
# generic imports
import numpy as np
import glob, os, sys
from datetime import datetime, timedelta
from netCDF4 import Dataset
import mpl_toolkits.basemap as bm
import matplotlib.pyplot as plt
from matplotlib import ticker
from spharm import Spharmt, getspecindx, regrid
import warnings
# LMR specific imports
sys.path.append('../')
from LMR_utils import global_hemispheric_means, assimilated_proxies, coefficient_efficiency
from load_gridded_data import read_gridded_data_CMIP5_model
from LMR_plot_support import *
# change default value of latlon kwarg to True.
bm.latlon_default = True
warnings.filterwarnings('ignore')
##################################
# START: set user parameters here
##################################
# option to suppress figures
iplot = True
iplot_individual_years = False
# centered time mean (nya must be odd! 3 = 3 yr mean; 5 = 5 year mean; etc 0 = none)
nya = 0
# option to print figures
fsave = True
#fsave = False
# set paths, the filename for plots, and global plotting preferences
# where to find reconstruction data
#datadir_output = './data/'
#datadir_output = '/home/disk/kalman2/wperkins/LMR_output/archive'
datadir_output = '/home/disk/kalman3/rtardif/LMR/output'
#datadir_output = '/home/disk/ekman4/rtardif/LMR/output'
#datadir_output = '/home/disk/kalman3/hakim/LMR'
# Directory where reanalysis data can be found
datadir_reanl = '/home/disk/kalman3/rtardif/LMR/data/model/'
# file specification
#
# current datasets
# ---
#nexp = 'production_gis_ccsm4_pagesall_0.75'
#nexp = 'production_mlost_ccsm4_pagesall_0.75'
#nexp = 'production_cru_ccsm4_pagesall_0.75'
#nexp = 'production_mlost_era20c_pagesall_0.75'
#nexp = 'production_mlost_era20cm_pagesall_0.75'
# ---
nexp = 'test'
# ---
# perform verification using all recon. MC realizations ( MCset = None )
# or over a custom selection ( MCset = (begin,end) )
# ex. MCset = (0,0) -> only the first MC run
# MCset = (0,10) -> the first 11 MC runs (from 0 to 10 inclusively)
# MCset = (80,100) -> the 80th to 100th MC runs (21 realizations)
MCset = None
#MCset = (0,10)
# Definition of variables to verify
# kind name variable long name bounds units mult. factor
verif_dict = \
{
#'psl_sfc_Amon' : ('anom', 'MSLP', 'Mean sea level pressure',-8.0,8.0,'(hPa)',0.01), \
'zg_500hPa_Amon' : ('anom','Z500', '500hPa geopotential height',-60.0,60.0,'(m)',1.0), \
#'wap_500hPa_Amon' : ('anom','W500', '500hPa vertical motion',-0.04,0.04,'(Pa/s)',1.0), \
#'ua_1000hPa_Amon' : ('anom','U1000', '1000hPa zonal wind',-2.0,2.0,'(m/s)',1.0), \
#'va_1000hPa_Amon' : ('anom','V1000', '1000hPa meridional wind',-2.0,2.0,'(m/s)',1.0), \
#'ua_850hPa_Amon' : ('anom','U850', '850hPa zonal wind',-2.0,2.0,'(m/s)',1.0), \
#'va_850hPa_Amon' : ('anom','V850', '850hPa meridional wind',-2.0,2.0,'(m/s)',1.0), \
#'ua_700hPa_Amon' : ('anom','U700', '700hPa zonal wind',-2.0,2.0,'(m/s)',1.0), \
#'va_700hPa_Amon' : ('anom','V700', '700hPa meridional wind',-2.0,2.0,'(m/s)',1.0), \
#'ua_600hPa_Amon' : ('anom','U600', '600hPa zonal wind',-2.0,2.0,'(m/s)',1.0), \
#'va_600hPa_Amon' : ('anom','V600', '600hPa meridional wind',-2.0,2.0,'(m/s)',1.0), \
#'ua_500hPa_Amon' : ('anom','U500', '500hPa zonal wind',-2.0,2.0,'(m/s)',1.0), \
#'ua_250hPa_Amon' : ('anom','U250', '250Pa zonal wind',-2.0,2.0,'(m/s)',1.0), \
#'prw_int_Amon' : ('anom','PRW', 'Precipitable water',-10.0,10.0,'(kg/m^2)',1.0), \
}
# time range for verification (in years CE)
trange = [1850,2000] #works for nya = 0
#trange = [1880,2000] #works for nya = 0
#trange = [1900,2000] #works for nya = 0
#trange = [1885,1995] #works for nya = 5
#trange = [1890,1990] #works for nya = 10
# reference period over which mean is calculated & subtracted
# from all datasets (in years CE)
#ref_period = [1951, 1980] # as in instrumental-era products (e.g. GISTEMP)
ref_period = [1900, 1999] # 20th century
valid_frac = 0.0
# number of contours for plots
nlevs = 21
# plot alpha transparency
alpha = 0.5
# set the default size of the figure in inches. ['figure.figsize'] = width, height;
# aspect ratio appears preserved on smallest of the two
plt.rcParams['figure.figsize'] = 10, 10 # that's default image size for this interactive session
plt.rcParams['axes.linewidth'] = 2.0 # set the value globally
plt.rcParams['font.weight'] = 'bold' # set the font weight globally
plt.rcParams['font.size'] = 11 # set the font size globally
#plt.rc('text', usetex=True)
plt.rc('text', usetex=False)
##################################
# END: set user parameters here
##################################
verif_vars = list(verif_dict.keys())
workdir = datadir_output + '/' + nexp
print('working directory = %s' % workdir)
print('\n getting file system information...\n')
# get number of mc realizations from directory count
# RT: modified way to determine list of directories with mc realizations
# get a listing of the iteration directories
dirs = glob.glob(workdir+"/r*")
# selecting the MC iterations to keep
if MCset:
dirset = dirs[MCset[0]:MCset[1]+1]
else:
dirset = dirs
mcdir = [item.split('/')[-1] for item in dirset]
niters = len(mcdir)
print('mcdir: %s' % str(mcdir))
print('niters = %s' % str(niters))
# check availability of target variables
vars_to_remove = []
for var in verif_vars:
available = True
for dir in mcdir:
ensfiln = workdir + '/' + dir + '/ensemble_mean_'+var+'.npz'
if not os.path.exists(ensfiln):
available = False
continue
if not available:
print('WARNING: Variable %s not found in reconstruction output...' %var)
vars_to_remove.append(var)
if len(vars_to_remove) > 0:
for var in vars_to_remove:
verif_vars.remove(var)
# Finally, loop over available verif. variables
for var in verif_vars:
# read ensemble mean data
print('\n reading LMR ensemble-mean data...\n')
first = True
k = -1
for dir in mcdir:
k = k + 1
ensfiln = workdir + '/' + dir + '/ensemble_mean_'+var+'.npz'
npzfile = np.load(ensfiln)
print(npzfile.files)
tmp = npzfile['xam']
print('shape of tmp: %s' % str(np.shape(tmp)))
if first:
first = False
recon_times = npzfile['years']
LMR_time = np.array(list(map(int,recon_times)))
lat = npzfile['lat']
lon = npzfile['lon']
nlat = npzfile['nlat']
nlon = npzfile['nlon']
lat2 = np.reshape(lat,(nlat,nlon))
lon2 = np.reshape(lon,(nlat,nlon))
years = npzfile['years']
nyrs = len(years)
xam = np.zeros([nyrs,np.shape(tmp)[1],np.shape(tmp)[2]])
xam_all = np.zeros([niters,nyrs,np.shape(tmp)[1],np.shape(tmp)[2]])
xam = xam + tmp
xam_all[k,:,:,:] = tmp
# this is the sample mean computed with low-memory accumulation
xam = xam/len(mcdir)
# this is the sample mean computed with numpy on all data
xam_check = xam_all.mean(0)
# check..
max_err = np.max(np.max(np.max(xam_check - xam)))
if max_err > 1e-4:
print('max error = %s' % str(max_err))
raise Exception('sample mean does not match what is in the ensemble files!')
# sample variance
xam_var = xam_all.var(0)
print(np.shape(xam_var))
print('\n shape of the ensemble array: %s \n' % str(np.shape(xam_all)))
print('\n shape of the ensemble-mean array: %s \n' % str(np.shape(xam)))
#################################################################
# BEGIN: load verification data (20CR and ERA20C) #
#################################################################
print('\nloading verification data...\n')
# Define month sequence for the calendar year
# (argument needed in upload of reanalysis data)
annual = list(range(1,13))
# load 20th century reanalysis (TCR) reanalysis --------------------------------
vardict = {var: verif_dict[var][0]}
vardef = var
datadir = datadir_reanl +'20cr'
datafile = vardef +'_20CR_185101-201112.nc'
dd = read_gridded_data_CMIP5_model(datadir,datafile,vardict,outtimeavg=annual,
anom_ref=ref_period)
rtime = dd[vardef]['years']
TCR_time = np.array([d.year for d in rtime])
lats = dd[vardef]['lat']
lons = dd[vardef]['lon']
latshape = lats.shape
lonshape = lons.shape
if len(latshape) == 2 & len(lonshape) == 2:
# stored in 2D arrays
lat_TCR = np.unique(lats)
lon_TCR = np.unique(lons)
nlat_TCR, = lat_TCR.shape
nlon_TCR, = lon_TCR.shape
else:
# stored in 1D arrays
lon_TCR = lons
lat_TCR = lats
nlat_TCR = len(lat_TCR)
nlon_TCR = len(lon_TCR)
lon2d_TCR, lat2d_TCR = np.meshgrid(lon_TCR, lat_TCR)
#TCR = dd[vardef]['value'] + dd[vardef]['climo'] # Full field
TCR = dd[vardef]['value'] # Anomalies
# load ERA20C reanalysis -------------------------------------------------------
vardict = {var: verif_dict[var][0]}
vardef = var
datadir = datadir_reanl+'era20c'
datafile = var+'_ERA20C_190001-201012.nc'
dd = read_gridded_data_CMIP5_model(datadir,datafile,vardict,outtimeavg=annual,
anom_ref=ref_period)
rtime = dd[vardef]['years']
ERA20C_time = np.array([d.year for d in rtime])
lats = dd[vardef]['lat']
lons = dd[vardef]['lon']
latshape = lats.shape
lonshape = lons.shape
if len(latshape) == 2 & len(lonshape) == 2:
# stored in 2D arrays
lat_ERA20C = np.unique(lats)
lon_ERA20C = np.unique(lons)
nlat_ERA20C, = lat_ERA20C.shape
nlon_ERA20C, = lon_ERA20C.shape
else:
# stored in 1D arrays
lon_ERA20C = lons
lat_ERA20C = lats
nlat_ERA20C = len(lat_ERA20C)
nlon_ERA20C = len(lon_ERA20C)
lon2_ERA20C, lat2_ERA20C = np.meshgrid(lon_ERA20C, lat_ERA20C)
#ERA20C = dd[vardef]['value'] + dd[vardef]['climo'] # Full field
ERA20C = dd[vardef]['value'] # Anomalies
###############################################################
# END: load verification data (20CR and ERA20C) #
###############################################################
# ----------------------------------------------------------
# Adjust so that all anomaly data pertain to the mean over a
# user-defined reference period (e.g. 20th century)
# ----------------------------------------------------------
stime = ref_period[0]
etime = ref_period[1]
# LMR
LMR = xam
smatch, ematch = find_date_indices(LMR_time,stime,etime)
LMR = LMR - np.mean(LMR[smatch:ematch,:,:],axis=0)
# TCR
smatch, ematch = find_date_indices(TCR_time,stime,etime)
TCR = TCR - np.mean(TCR[smatch:ematch,:,:],axis=0)
# ERA
smatch, ematch = find_date_indices(ERA20C_time,stime,etime)
ERA20C = ERA20C - np.mean(ERA20C[smatch:ematch,:,:],axis=0)
# -----------------------------------
# Regridding the data for comparisons
# -----------------------------------
print('\n regridding data to a common T42 grid...\n')
iplot_loc= False
#iplot_loc= True
# create instance of the spherical harmonics object for each grid
specob_lmr = Spharmt(nlon,nlat,gridtype='regular',legfunc='computed')
specob_tcr = Spharmt(nlon_TCR,nlat_TCR,gridtype='regular',legfunc='computed')
specob_era20c = Spharmt(nlon_ERA20C,nlat_ERA20C,gridtype='regular',legfunc='computed')
# truncate to a lower resolution grid (common:21, 42, 62, 63, 85, 106, 255, 382, 799)
ntrunc_new = 42 # T42
ifix = np.remainder(ntrunc_new,2.0).astype(int)
nlat_new = ntrunc_new + ifix
nlon_new = int(nlat_new*1.5)
# lat, lon grid in the truncated space
dlat = 90./((nlat_new-1)/2.)
dlon = 360./nlon_new
veclat = np.arange(-90.,90.+dlat,dlat)
veclon = np.arange(0.,360.,dlon)
blank = np.zeros([nlat_new,nlon_new])
lat2_new = (veclat + blank.T).T
lon2_new = (veclon + blank)
# create instance of the spherical harmonics object for the new grid
specob_new = Spharmt(nlon_new,nlat_new,gridtype='regular',legfunc='computed')
# loop over years of interest and transform...specify trange at top of file
iw = 0
if nya > 0:
iw = (nya-1)/2
cyears = list(range(trange[0],trange[1]))
lt_csave = np.zeros([len(cyears)])
le_csave = np.zeros([len(cyears)])
te_csave = np.zeros([len(cyears)])
lmr_allyears = np.zeros([len(cyears),nlat_new,nlon_new])
tcr_allyears = np.zeros([len(cyears),nlat_new,nlon_new])
era20c_allyears = np.zeros([len(cyears),nlat_new,nlon_new])
lmr_zm = np.zeros([len(cyears),nlat_new])
tcr_zm = np.zeros([len(cyears),nlat_new])
era20c_zm = np.zeros([len(cyears),nlat_new])
k = -1
for yr in cyears:
k = k + 1
LMR_smatch, LMR_ematch = find_date_indices(LMR_time,yr-iw,yr+iw+1)
TCR_smatch, TCR_ematch = find_date_indices(TCR_time,yr-iw,yr+iw+1)
ERA20C_smatch, ERA20C_ematch = find_date_indices(ERA20C_time,yr-iw,yr+iw+1)
print('------------------------------------------------------------------------')
print('working on year... %5s' % str(yr))
print(' %5s LMR index= %5s : LMR year= %5s' % (str(yr), str(LMR_smatch),str(LMR_time[LMR_smatch])))
# LMR
pdata_lmr = np.mean(LMR[LMR_smatch:LMR_ematch,:,:],0)
lmr_trunc = regrid(specob_lmr, specob_new, pdata_lmr, ntrunc=nlat_new-1, smooth=None)
# TCR
if TCR_smatch and TCR_ematch:
pdata_tcr = np.mean(TCR[TCR_smatch:TCR_ematch,:,:],0)
else:
pdata_tcr = np.zeros(shape=[nlat_TCR,nlon_TCR])
pdata_tcr.fill(np.nan)
# regrid on LMR grid
if np.isnan(pdata_tcr).all():
tcr_trunc = np.zeros(shape=[nlat_new,nlon_new])
tcr_trunc.fill(np.nan)
else:
tcr_trunc = regrid(specob_tcr, specob_new, pdata_tcr, ntrunc=nlat_new-1, smooth=None)
# ERA20C
if ERA20C_smatch and ERA20C_ematch:
pdata_era20c = np.mean(ERA20C[ERA20C_smatch:ERA20C_ematch,:,:],0)
else:
pdata_era20c = np.zeros(shape=[nlat_ERA20C,nlon_ERA20C])
pdata_era20c.fill(np.nan)
# regrid on LMR grid
if np.isnan(pdata_era20c).all():
era20c_trunc = np.zeros(shape=[nlat_new,nlon_new])
era20c_trunc.fill(np.nan)
else:
era20c_trunc = regrid(specob_era20c, specob_new, pdata_era20c, ntrunc=nlat_new-1, smooth=None)
if iplot_individual_years:
# Reanalysis comparison figures (annually-averaged anomaly fields)
#fmin = -60.0; fmax = +60.0; nflevs=41
fmin = verif_dict[var][3]; fmax = verif_dict[var][4]; nflevs=41
fig = plt.figure()
ax = fig.add_subplot(3,1,1)
LMR_plotter(lmr_trunc*verif_dict[var][6],lat2_new,lon2_new,'bwr',nflevs,vmin=fmin,vmax=fmax,extend='both')
plt.title('LMR '+'T'+str(nlat_new-ifix)+' '+verif_dict[var][1]+' anom. '+verif_dict[var][5]+' '+str(yr), fontweight='bold')
plt.clim(fmin,fmax)
ax = fig.add_subplot(3,1,2)
LMR_plotter(tcr_trunc*verif_dict[var][6],lat2_new,lon2_new,'bwr',nflevs,vmin=fmin,vmax=fmax,extend='both')
plt.title('20CR-V2 '+'T'+str(nlat_new-ifix)+' '+verif_dict[var][1]+' anom. '+verif_dict[var][5]+' '+str(yr), fontweight='bold')
#LMR_plotter(pdata_tcr*verif_dict[var][6],lat2_TCR,lon2_TCR,'bwr',nflevs,vmin=fmin,vmax=fmax,extend='both')
#plt.title('20CR-V2 '+'orig. grid'+' '+verif_dict[var][1]+' anom. '+verif_dict[var][5]+' '+str(yr), fontweight='bold')
plt.clim(fmin,fmax)
ax = fig.add_subplot(3,1,3)
LMR_plotter(era20c_trunc*verif_dict[var][6],lat2_new,lon2_new,'bwr',nflevs,vmin=fmin,vmax=fmax,extend='both')
plt.title('ERA-20C '+'T'+str(nlat_new-ifix)+' '+verif_dict[var][1]+' anom. '+verif_dict[var][5]+' '+str(yr), fontweight='bold')
#LMR_plotter(pdata_era20c*verif_dict[var][6],lat2_ERA20C,lon2_ERA20C,'bwr',nflevs,vmin=fmin,vmax=fmax,extend='both')
#plt.title('ERA-20C '+'orig. grid'+' '+verif_dict[var][1]+' anom. '+verif_dict[var][5]+' '+str(yr), fontweight='bold')
plt.clim(fmin,fmax)
fig.tight_layout()
plt.savefig(nexp+'_LMR_TCR_ERA20C_'+verif_dict[var][1]+'anom_'+str(yr)+'.png')
plt.close()
# save the full grids
lmr_allyears[k,:,:] = lmr_trunc
tcr_allyears[k,:,:] = tcr_trunc
era20c_allyears[k,:,:] = era20c_trunc
# -----------------------
# zonal-mean verification
# -----------------------
# LMR
lmr_zm[k,:] = np.mean(lmr_trunc,1)
# TCR
fracok = np.sum(np.isfinite(tcr_trunc),axis=1,dtype=np.float16)/float(nlon_TCR)
boolok = np.where(fracok >= valid_frac)
boolnotok = np.where(fracok < valid_frac)
for i in boolok:
tcr_zm[k,i] = np.nanmean(tcr_trunc[i,:],axis=1)
tcr_zm[k,boolnotok] = np.NAN
# ERA
fracok = np.sum(np.isfinite(era20c_trunc),axis=1,dtype=np.float16)/float(nlon_ERA20C)
boolok = np.where(fracok >= valid_frac)
boolnotok = np.where(fracok < valid_frac)
for i in boolok:
era20c_zm[k,i] = np.nanmean(era20c_trunc[i,:],axis=1)
era20c_zm[k,boolnotok] = np.NAN
if iplot_loc:
ncints = 30
cmap = 'bwr'
nticks = 6 # number of ticks on the colorbar
# set contours based on 20CR
maxabs = np.nanmax(np.abs(tcr_trunc))
# round the contour interval, and then set limits to fit
dc = np.round(maxabs*2/ncints,2)
cl = dc*ncints/2.
cints = np.linspace(-cl,cl,ncints,endpoint=True)
# compare LMR and TCR and ERA20C
fig = plt.figure()
ax = fig.add_subplot(2,2,1)
m1 = bm.Basemap(projection='robin',lon_0=0)
# maxabs = np.nanmax(np.abs(lmr_trunc))
cs = m1.contourf(lon2_new,lat2_new,lmr_trunc,cints,cmap=plt.get_cmap(cmap),vmin=-maxabs,vmax=maxabs)
m1.drawcoastlines()
cb = m1.colorbar(cs)
tick_locator = ticker.MaxNLocator(nbins=nticks)
cb.locator = tick_locator
cb.ax.yaxis.set_major_locator(matplotlib.ticker.AutoLocator())
cb.update_ticks()
ax.set_title('LMR '+verif_dict[var][1]+' '+str(ntrunc_new) + ' ' + str(yr))
ax = fig.add_subplot(2,2,2)
m2 = bm.Basemap(projection='robin',lon_0=0)
# maxabs = np.nanmax(np.abs(tcr_trunc))
cs = m2.contourf(lon2_new,lat2_new,tcr_trunc,cints,cmap=plt.get_cmap(cmap),vmin=-maxabs,vmax=maxabs)
m2.drawcoastlines()
cb = m1.colorbar(cs)
tick_locator = ticker.MaxNLocator(nbins=nticks)
cb.locator = tick_locator
cb.ax.yaxis.set_major_locator(matplotlib.ticker.AutoLocator())
cb.update_ticks()
ax.set_title('20CR-V2 '+verif_dict[var][1]+' '+str(ntrunc_new) + ' ' + str(yr))
ax = fig.add_subplot(2,2,3)
m3 = bm.Basemap(projection='robin',lon_0=0)
# maxabs = np.nanmax(np.abs(gis_trunc))
cs = m3.contourf(lon2_new,lat2_new,era20c_trunc,cints,cmap=plt.get_cmap(cmap),vmin=-maxabs,vmax=maxabs)
m3.drawcoastlines()
cb = m1.colorbar(cs)
tick_locator = ticker.MaxNLocator(nbins=nticks)
cb.locator = tick_locator
cb.ax.yaxis.set_major_locator(matplotlib.ticker.AutoLocator())
cb.update_ticks()
ax.set_title('ERA20C '+verif_dict[var][1]+' '+str(ntrunc_new) + ' ' + str(yr))
plt.clim(-maxabs,maxabs)
# get these numbers by adjusting the figure interactively!!!
plt.subplots_adjust(left=0.05, bottom=0.45, right=0.95, top=0.95, wspace=0.1, hspace=0.0)
# plt.tight_layout(pad=0.3)
fig.suptitle(verif_dict[var][1] + ' for ' +str(nya) +' year centered average')
# anomaly correlation
lmrvec = np.reshape(lmr_trunc,(1,nlat_new*nlon_new))
tcrvec = np.reshape(tcr_trunc,(1,nlat_new*nlon_new))
era20cvec = np.reshape(era20c_trunc,(1,nlat_new*nlon_new))
# lmr <-> tcr
indok = np.isfinite(tcrvec); nbok = np.sum(indok); nball = tcrvec.shape[1]
ratio = float(nbok)/float(nball)
if ratio > valid_frac:
lt_csave[k] = np.corrcoef(lmrvec[indok],tcrvec[indok])[0,1]
else:
lt_csave[k] = np.nan
print(' lmr-tcr correlation : %s' % str(lt_csave[k]))
# lmr <-> era
indok = np.isfinite(era20cvec); nbok = np.sum(indok); nball = era20cvec.shape[1]
ratio = float(nbok)/float(nball)
if ratio > valid_frac:
le_csave[k] = np.corrcoef(lmrvec[indok],era20cvec[indok])[0,1]
else:
le_csave[k] = np.nan
print(' lmr-era correlation : %s' % str(le_csave[k]))
# tcr <-> era
indok = np.isfinite(era20cvec); nbok = np.sum(indok); nball = era20cvec.shape[1]
ratio = float(nbok)/float(nball)
if ratio > valid_frac:
te_csave[k] = np.corrcoef(tcrvec[indok],era20cvec[indok])[0,1]
else:
te_csave[k] = np.nan
print(' tcr-era correlation : %s' % str(te_csave[k]))
# plots for anomaly correlation statistics
# number of bins in the histograms
nbins = 15
corr_range = [-0.6,1.0]
bins = np.linspace(corr_range[0],corr_range[1],nbins)
# LMR compared to TCR and ERA20C
fig = plt.figure()
# TCR
ax = fig.add_subplot(3,2,1)
ax.plot(cyears,lt_csave,lw=2)
ax.plot([trange[0],trange[-1]],[0,0],'k:')
ax.set_title('LMR - 20CR-V2')
ax.set_xlim(trange[0],trange[-1])
ax.set_ylim(corr_range[0],corr_range[-1])
ax.set_ylabel('Correlation',fontweight='bold')
#
ax = fig.add_subplot(3,2,2)
ax.hist(lt_csave[~np.isnan(lt_csave)],bins=bins,histtype='stepfilled',alpha=0.25)
ax.set_title('LMR - 20CR-V2')
ax.set_xlim(corr_range[0],corr_range[-1])
ax.set_ylabel('Counts',fontweight='bold')
xmin,xmax = ax.get_xlim()
ymin,ymax = ax.get_ylim()
ypos = ymax-0.15*(ymax-ymin)
xpos = xmin+0.025*(xmax-xmin)
ax.text(xpos,ypos,'Mean = %s' %"{:.2f}".format(np.nanmean(lt_csave)),fontsize=11,fontweight='bold')
# ERA20C
ax = fig.add_subplot(3,2,3)
ax.plot(cyears,le_csave,lw=2)
ax.plot([trange[0],trange[-1]],[0,0],'k:')
ax.set_title('LMR - ERA-20C')
ax.set_xlim(trange[0],trange[-1])
ax.set_ylim(corr_range[0],corr_range[-1])
ax.set_ylabel('Correlation',fontweight='bold')
#
ax = fig.add_subplot(3,2,4)
ax.hist(le_csave[~np.isnan(le_csave)],bins=bins,histtype='stepfilled',alpha=0.25)
ax.set_title('LMR - ERA-20C')
ax.set_xlim(corr_range[0],corr_range[-1])
ax.set_ylabel('Counts',fontweight='bold')
xmin,xmax = ax.get_xlim()
ymin,ymax = ax.get_ylim()
ypos = ymax-0.15*(ymax-ymin)
xpos = xmin+0.025*(xmax-xmin)
ax.text(xpos,ypos,'Mean = %s' %"{:.2f}".format(np.nanmean(le_csave)),fontsize=11,fontweight='bold')
# ERA20C compared to TCR
ax = fig.add_subplot(3,2,5)
ax.plot(cyears,te_csave,lw=2)
ax.plot([trange[0],trange[-1]],[0,0],'k:')
ax.set_title('ERA-20C - 20CR-V2')
ax.set_xlim(trange[0],trange[-1])
ax.set_ylim(corr_range[0],corr_range[-1])
ax.set_ylabel('Correlation',fontweight='bold')
ax.set_xlabel('Year CE',fontweight='bold')
#
ax = fig.add_subplot(3,2,6)
ax.hist(te_csave[~np.isnan(te_csave)],bins=bins,histtype='stepfilled',alpha=0.25)
ax.set_title('ERA-20C - 20CR-V2')
ax.set_xlim(corr_range[0],corr_range[-1])
ax.set_ylabel('Counts',fontweight='bold')
ax.set_xlabel('Correlation',fontweight='bold')
xmin,xmax = ax.get_xlim()
ymin,ymax = ax.get_ylim()
ypos = ymax-0.15*(ymax-ymin)
xpos = xmin+0.025*(xmax-xmin)
ax.text(xpos,ypos,'Mean = %s' %"{:.2f}".format(np.nanmean(te_csave)),fontsize=11,fontweight='bold')
#fig.tight_layout()
plt.subplots_adjust(left=0.1, bottom=0.45, right=0.95, top=0.93, wspace=0.5, hspace=0.5)
fig.suptitle(verif_dict[var][2]+' anomaly correlation',fontweight='bold')
if fsave:
print('saving to .png')
plt.savefig(nexp+'_verify_grid_'+verif_dict[var][1]+'_anomaly_correlation_LMR_'+str(trange[0])+'-'+str(trange[1])+'.png')
plt.savefig(nexp+'_verify_grid_'+verif_dict[var][1]+'_anomaly_correlation_LMR_'+str(trange[0])+'-'+str(trange[1])+'.pdf', bbox_inches='tight', dpi=300, format='pdf')
plt.close()
# =======================================================================================================
# For paper 1 :
fig = plt.figure()
# TCR
ax = fig.add_subplot(2,2,1)
ax.plot(cyears,lt_csave,lw=2)
ax.plot([trange[0],trange[-1]],[0,0],'k:')
ax.set_title('LMR - 20CR-V2')
ax.set_xlim(trange[0],trange[-1])
ax.set_ylim(corr_range[0],corr_range[-1])
ax.set_ylabel('Correlation',fontweight='bold')
ax = fig.add_subplot(2,2,2)
ax.hist(lt_csave[~np.isnan(lt_csave)],bins=bins,histtype='stepfilled',alpha=0.25)
ax.set_title('LMR - 20CR-V2')
ax.set_xlim(corr_range[0],corr_range[-1])
ax.set_ylabel('Counts',fontweight='bold')
xmin,xmax = ax.get_xlim()
ymin,ymax = ax.get_ylim()
ypos = ymax-0.15*(ymax-ymin)
xpos = xmin+0.025*(xmax-xmin)
ax.text(xpos,ypos,'Mean = %s' %"{:.2f}".format(np.nanmean(lt_csave)),fontsize=11,fontweight='bold')
# ERA20C
ax = fig.add_subplot(2,2,3)
ax.plot(cyears,le_csave,lw=2)
ax.plot([trange[0],trange[-1]],[0,0],'k:')
ax.set_title('LMR - ERA-20C')
ax.set_xlim(trange[0],trange[-1])
ax.set_ylim(corr_range[0],corr_range[-1])
ax.set_ylabel('Correlation',fontweight='bold')
ax.set_xlabel('Year CE',fontweight='bold')
#
ax = fig.add_subplot(2,2,4)
ax.hist(le_csave[~np.isnan(le_csave)],bins=bins,histtype='stepfilled',alpha=0.25)
ax.set_title('LMR - ERA-20C')
ax.set_xlim(corr_range[0],corr_range[-1])
ax.set_ylabel('Counts',fontweight='bold')
ax.set_xlabel('Correlation',fontweight='bold')
xmin,xmax = ax.get_xlim()
ymin,ymax = ax.get_ylim()
ypos = ymax-0.15*(ymax-ymin)
xpos = xmin+0.025*(xmax-xmin)
ax.text(xpos,ypos,'Mean = %s' %"{:.2f}".format(np.nanmean(le_csave)),fontsize=11,fontweight='bold')
fig.tight_layout()
plt.subplots_adjust(left=0.1, bottom=0.45, right=0.95, top=0.93, wspace=0.5, hspace=0.5)
fig.suptitle(verif_dict[var][2]+' anomaly correlation',fontweight='bold')
plt.savefig(nexp+'_verify_grid_'+verif_dict[var][1]+'_anomaly_correlation_LMR_'+str(trange[0])+'-'+str(trange[1])+'_paper.png')
plt.savefig(nexp+'_verify_grid_'+verif_dict[var][1]+'_anomaly_correlation_LMR_'+str(trange[0])+'-'+str(trange[1])+'_paper.pdf', bbox_inches='tight', dpi=300, format='pdf')
plt.close()
# =======================================================================================================
#
# BEGIN bias, r and CE calculations
#
# correlation and CE at each (lat,lon) point
lt_err = lmr_allyears - tcr_allyears
le_err = lmr_allyears - era20c_allyears
te_err = tcr_allyears - era20c_allyears
r_lt = np.zeros([nlat_new,nlon_new])
ce_lt = np.zeros([nlat_new,nlon_new])
r_le = np.zeros([nlat_new,nlon_new])
ce_le = np.zeros([nlat_new,nlon_new])
r_te = np.zeros([nlat_new,nlon_new])
ce_te = np.zeros([nlat_new,nlon_new])
# bias
# CE
ce_lt = coefficient_efficiency(tcr_allyears,lmr_allyears)
ce_le = coefficient_efficiency(era20c_allyears,lmr_allyears)
ce_te = coefficient_efficiency(era20c_allyears,tcr_allyears)
# Correlation
for la in range(nlat_new):
for lo in range(nlon_new):
# LMR-TCR
indok = np.isfinite(tcr_allyears[:,la,lo])
nbok = np.sum(indok)
nball = lmr_allyears[:,la,lo].shape[0]
ratio = float(nbok)/float(nball)
if ratio > valid_frac:
r_lt[la,lo] = np.corrcoef(lmr_allyears[indok,la,lo],tcr_allyears[indok,la,lo])[0,1]
else:
r_lt[la,lo] = np.nan
# LMR-ERA20C
indok = np.isfinite(era20c_allyears[:,la,lo])
nbok = np.sum(indok)
nball = lmr_allyears[:,la,lo].shape[0]
ratio = float(nbok)/float(nball)
if ratio > valid_frac:
r_le[la,lo] = np.corrcoef(lmr_allyears[indok,la,lo],era20c_allyears[indok,la,lo])[0,1]
else:
r_le[la,lo] = np.nan
# TCR-ERA20C
indok = np.isfinite(era20c_allyears[:,la,lo])
nbok = np.sum(indok)
nball = tcr_allyears[:,la,lo].shape[0]
ratio = float(nbok)/float(nball)
if ratio > valid_frac:
r_te[la,lo] = np.corrcoef(tcr_allyears[indok,la,lo],era20c_allyears[indok,la,lo])[0,1]
else:
r_te[la,lo] = np.nan
# median
lat_trunc = np.squeeze(lat2_new[:,0])
indlat = np.where((lat_trunc[:] > -60.0) & (lat_trunc[:] < 60.0))
lt_rmedian = str(float('%.2g' % np.median(np.median(r_lt)) ))
print('lmr-tcr all-grid median r : %s' % str(lt_rmedian))
lt_rmedian60 = str(float('%.2g' % np.median(np.median(r_lt[indlat,:])) ))
print('lmr-tcr 60S-60N median r : %s' % str(lt_rmedian60))
lt_cemedian = str(float('%.2g' % np.median(np.median(ce_lt)) ))
print('lmr-tcr all-grid median ce : %s' % str(lt_cemedian))
lt_cemedian60 = str(float('%.2g' % np.median(np.median(ce_lt[indlat,:])) ))
print('lmr-tcr 60S-60N median ce : %s' % str(lt_cemedian60))
le_rmedian = str(float('%.2g' % np.median(np.median(r_le)) ))
print('lmr-era20c all-grid median r : %s' % str(le_rmedian))
le_rmedian60 = str(float('%.2g' % np.median(np.median(r_le[indlat,:])) ))
print('lmr-era20c 60S-60N median r : %s' % str(le_rmedian60))
le_cemedian = str(float('%.2g' % np.median(np.median(ce_le)) ))
print('lmr-era20c all-grid median ce : %s' % str(le_cemedian))
le_cemedian60 = str(float('%.2g' % np.median(np.median(ce_le[indlat,:])) ))
print('lmr-era20c 60S-60N median ce : %s' % str(le_cemedian60))
te_rmedian = str(float('%.2g' % np.median(np.median(r_te)) ))
print('tcr-era20c all-grid median r : %s' % str(te_rmedian))
te_rmedian60 = str(float('%.2g' % np.median(np.median(r_te[indlat,:])) ))
print('tcr-era20c 60S-60N median r : %s' % str(te_rmedian60))
te_cemedian = str(float('%.2g' % np.median(np.median(ce_te)) ))
print('tcr-era20c all-grid median ce : %s' % str(te_cemedian))
te_cemedian60 = str(float('%.2g' % np.median(np.median(ce_te[indlat,:])) ))
print('tcr-era20c 60S-60N median ce : %s' % str(te_cemedian60))
# spatial mean (area weighted)
# LMR-TCR
[rmean_global,rmean_nh,rmean_sh] = global_hemispheric_means(r_lt,veclat)
[cemean_global,cemean_nh,cemean_sh] = global_hemispheric_means(ce_lt,veclat)
lt_rmean_global = str(float('%.2f' %rmean_global[0]))
lt_rmean_nh = str(float('%.2f' %rmean_nh[0]))
lt_rmean_sh = str(float('%.2f' %rmean_sh[0]))
lt_cemean_global = str(float('%.2f' %cemean_global[0]))
lt_cemean_nh = str(float('%.2f' %cemean_nh[0]))
lt_cemean_sh = str(float('%.2f' %cemean_sh[0]))
# LMR-ERA
[rmean_global,rmean_nh,rmean_sh] = global_hemispheric_means(r_le,veclat)
[cemean_global,cemean_nh,cemean_sh] = global_hemispheric_means(ce_le,veclat)
le_rmean_global = str(float('%.2f' %rmean_global[0]))
le_rmean_nh = str(float('%.2f' %rmean_nh[0]))
le_rmean_sh = str(float('%.2f' %rmean_sh[0]))
le_cemean_global = str(float('%.2f' %cemean_global[0]))
le_cemean_nh = str(float('%.2f' %cemean_nh[0]))
le_cemean_sh = str(float('%.2f' %cemean_sh[0]))
# TCR-ERA
[rmean_global,rmean_nh,rmean_sh] = global_hemispheric_means(r_te,veclat)
[cemean_global,cemean_nh,cemean_sh] = global_hemispheric_means(ce_te,veclat)
te_rmean_global = str(float('%.2f' %rmean_global[0]))
te_rmean_nh = str(float('%.2f' %rmean_nh[0]))
te_rmean_sh = str(float('%.2f' %rmean_sh[0]))
te_cemean_global = str(float('%.2f' %cemean_global[0]))
te_cemean_nh = str(float('%.2f' %cemean_nh[0]))
te_cemean_sh = str(float('%.2f' %cemean_sh[0]))
# zonal mean verification
r_lt_zm = np.zeros([nlat_new])
ce_lt_zm = np.zeros([nlat_new])
lt_err_zm = lmr_zm - tcr_zm
# era20c verification
r_le_zm = np.zeros([nlat_new])
ce_le_zm = np.zeros([nlat_new])
le_err_zm = lmr_zm - era20c_zm
for la in range(nlat_new):
# LMR-TCR
ce_lt_zm[la] = coefficient_efficiency(tcr_zm[:,la],lmr_zm[:,la],valid=valid_frac)
indok = np.isfinite(tcr_zm[:,la])
nbok = np.sum(indok)
nball = len(cyears)
ratio = float(nbok)/float(nball)
if ratio > valid_frac:
r_lt_zm[la] = np.corrcoef(lmr_zm[indok,la],tcr_zm[indok,la])[0,1]
else:
r_lt_zm[la] = np.nan
# LMR-ERA20C
ce_le_zm[la] = coefficient_efficiency(era20c_zm[:,la],lmr_zm[:,la],valid=valid_frac)
indok = np.isfinite(era20c_zm[:,la])
nbok = np.sum(indok)
nball = len(cyears)
ratio = float(nbok)/float(nball)
if ratio > valid_frac:
r_le_zm[la] = np.corrcoef(lmr_zm[indok,la],era20c_zm[indok,la])[0,1]
else:
r_le_zm[la] = np.nan
#
# END r and CE
#
major_ticks = np.arange(-90, 91, 30)
fig = plt.figure()
ax = fig.add_subplot(1,2,1)
tcrleg, = ax.plot(r_lt_zm,veclat,'k-',linestyle='--',lw=2,label='20CR-V2')
eraleg, = ax.plot(r_le_zm,veclat,'k-',linestyle='-',lw=2,label='ERA-20C')
ax.plot([0,0],[-90,90],'k:')
ax.set_yticks(major_ticks)
plt.ylim([-90,90])
plt.xlim([-1,1])
plt.ylabel('Latitude',fontweight='bold')
plt.xlabel('Correlation',fontweight='bold')
ax.legend(handles=[tcrleg,eraleg],handlelength=3.0,ncol=1,fontsize=12,loc='upper left',frameon=False)
ax = fig.add_subplot(1,2,2)
ax.plot(ce_lt_zm,veclat,'k-',linestyle='--',lw=2)
ax.plot(ce_le_zm,veclat,'k-',linestyle='-',lw=2)
ax.plot([0,0],[-90,90],'k:')
ax.set_yticks([])
plt.ylim([-90,90])
plt.xlim([-1.5,1])
plt.xlabel('Coefficient of efficiency',fontweight='bold')
#plt.title('CE (TCR dashed; ERA20C solid)')
plt.suptitle('LMR zonal-mean verification - '+verif_dict[var][2],fontweight='bold')
fig.tight_layout(pad = 2.0)
if fsave:
print('saving to .png')
plt.savefig(nexp+'_verify_grid_'+verif_dict[var][1]+'_r_ce_zonal_mean_'+str(trange[0])+'-'+str(trange[1])+'.png')
plt.savefig(nexp+'_verify_grid_'+verif_dict[var][1]+'_r_ce_zonal_mean_'+str(trange[0])+'-'+str(trange[1])+'.pdf',bbox_inches='tight', dpi=300, format='pdf')
plt.close()
#
# r and ce plots
#
cbarfmt = '%4.1f'
nticks = 4 # number of ticks on the colorbar
if iplot:
fig = plt.figure()
ax = fig.add_subplot(4,2,1)
LMR_plotter(r_lt,lat2_new,lon2_new,'bwr',nlevs,vmin=-1,vmax=1,extend='neither',cbarfmt=cbarfmt,nticks=nticks)
plt.title('LMR - 20CR-V2 '+verif_dict[var][1]+' r '+str(cyears[0])+'-'+str(cyears[-1]) + ' mean='+str(lt_rmean_global))
plt.clim(-1,1)
ax.title.set_position([.5, 1.05])
ax = fig.add_subplot(4,2,2)
LMR_plotter(ce_lt,lat2_new,lon2_new,'bwr',nlevs,vmin=-1,vmax=1,extend='min',cbarfmt=cbarfmt,nticks=nticks)
plt.title('LMR - 20CR-V2 '+verif_dict[var][1]+' CE '+str(cyears[0])+'-'+str(cyears[-1]) + ' mean='+str(lt_cemean_global))
plt.clim(-1,1)
ax.title.set_position([.5, 1.05])
ax = fig.add_subplot(4,2,3)
LMR_plotter(r_le,lat2_new,lon2_new,'bwr',nlevs,vmin=-1,vmax=1,extend='neither',cbarfmt=cbarfmt,nticks=nticks)
plt.title('LMR - ERA-20C '+verif_dict[var][1]+' r '+str(cyears[0])+'-'+str(cyears[-1]) + ' mean='+str(le_rmean_global))
plt.clim(-1,1)
ax.title.set_position([.5, 1.05])
ax = fig.add_subplot(4,2,4)
LMR_plotter(ce_le,lat2_new,lon2_new,'bwr',nlevs,vmin=-1,vmax=1,extend='min',cbarfmt=cbarfmt,nticks=nticks)
plt.title('LMR - ERA-20C '+verif_dict[var][1]+' CE '+str(cyears[0])+'-'+str(cyears[-1]) + ' mean='+str(le_cemean_global))
plt.clim(-1,1)
ax.title.set_position([.5, 1.05])
ax = fig.add_subplot(4,2,5)
LMR_plotter(r_te,lat2_new,lon2_new,'bwr',nlevs,vmin=-1,vmax=1,extend='neither',cbarfmt=cbarfmt,nticks=nticks)
plt.title('20CR-V2 - ERA-20C '+verif_dict[var][1]+' r '+str(cyears[0])+'-'+str(cyears[-1]) + ' mean='+str(te_rmean_global))
plt.clim(-1,1)
ax.title.set_position([.5, 1.05])
ax = fig.add_subplot(4,2,6)
LMR_plotter(ce_te,lat2_new,lon2_new,'bwr',nlevs,vmin=-1,vmax=1,extend='min',cbarfmt=cbarfmt,nticks=nticks)
plt.title('20CR-V2 - ERA-20C '+verif_dict[var][1]+' CE '+str(cyears[0])+'-'+str(cyears[-1]) + ' mean='+str(te_cemean_global))
plt.clim(-1,1)
ax.title.set_position([.5, 1.05])
fig.tight_layout()
if fsave:
print('saving to .png')
plt.savefig(nexp+'_verify_grid_'+verif_dict[var][1]+'_r_ce_'+str(trange[0])+'-'+str(trange[1])+'.png')
plt.savefig(nexp+'_verify_grid_'+verif_dict[var][1]+'_r_ce_'+str(trange[0])+'-'+str(trange[1])+'.pdf',bbox_inches='tight', dpi=300, format='pdf')
plt.close()
# ================================================================================================================
# For paper 1 :
fig = plt.figure()
ax = fig.add_subplot(4,2,1)
LMR_plotter(r_lt,lat2_new,lon2_new,'bwr',nlevs,vmin=-1,vmax=1,extend='neither',cbarfmt=cbarfmt,nticks=nticks)
plt.title('LMR - 20CR-V2 '+verif_dict[var][1]+' r '+str(cyears[0])+'-'+str(cyears[-1]) + ' mean='+str(lt_rmean_global))
plt.clim(-1,1)
ax.title.set_position([.5, 1.05])
ax = fig.add_subplot(4,2,2)
LMR_plotter(ce_lt,lat2_new,lon2_new,'bwr',nlevs,vmin=-1,vmax=1,extend='min',cbarfmt=cbarfmt,nticks=nticks)
plt.title('LMR - 20CR-V2 '+verif_dict[var][1]+' CE '+str(cyears[0])+'-'+str(cyears[-1]) + ' mean='+str(lt_cemean_global))
plt.clim(-1,1)
ax.title.set_position([.5, 1.05])
ax = fig.add_subplot(4,2,3)
LMR_plotter(r_le,lat2_new,lon2_new,'bwr',nlevs,vmin=-1,vmax=1,extend='neither',cbarfmt=cbarfmt,nticks=nticks)
plt.title('LMR - ERA-20C '+verif_dict[var][1]+' r '+str(cyears[0])+'-'+str(cyears[-1]) + ' mean='+str(le_rmean_global))
plt.clim(-1,1)
ax.title.set_position([.5, 1.05])
ax = fig.add_subplot(4,2,4)
LMR_plotter(ce_le,lat2_new,lon2_new,'bwr',nlevs,vmin=-1,vmax=1,extend='min',cbarfmt=cbarfmt,nticks=nticks)
plt.title('LMR - ERA-20C '+verif_dict[var][1]+' CE '+str(cyears[0])+'-'+str(cyears[-1]) + ' mean='+str(le_cemean_global))
plt.clim(-1,1)
ax.title.set_position([.5, 1.05])
fig.tight_layout()
print('saving to .png')
plt.savefig(nexp+'_verify_grid_'+verif_dict[var][1]+'_r_ce_'+str(trange[0])+'-'+str(trange[1])+'_paper.png')
plt.savefig(nexp+'_verify_grid_'+verif_dict[var][1]+'_r_ce_'+str(trange[0])+'-'+str(trange[1])+'_paper.pdf',bbox_inches='tight', dpi=300, format='pdf')
plt.close()
# ================================================================================================================
# in loop over lat,lon, add a call to the rank histogram function; need to move up the function def
# NEW look at trends over specified time periods as a function of latitude
# zonal means of the original LMR data
| [
"spharm.Spharmt",
"matplotlib.pyplot.ylabel",
"numpy.array",
"numpy.nanmean",
"matplotlib.ticker.MaxNLocator",
"numpy.isfinite",
"matplotlib.ticker.AutoLocator",
"sys.path.append",
"numpy.arange",
"numpy.mean",
"os.path.exists",
"numpy.reshape",
"numpy.where",
"matplotlib.pyplot.xlabel",
... | [((332, 353), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (346, 353), False, 'import matplotlib\n'), ((667, 689), 'sys.path.append', 'sys.path.append', (['"""../"""'], {}), "('../')\n", (682, 689), False, 'import glob, os, sys\n'), ((948, 981), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (971, 981), False, 'import warnings\n'), ((4901, 4929), 'matplotlib.pyplot.rc', 'plt.rc', (['"""text"""'], {'usetex': '(False)'}), "('text', usetex=False)\n", (4907, 4929), True, 'import matplotlib.pyplot as plt\n'), ((5382, 5408), 'glob.glob', 'glob.glob', (["(workdir + '/r*')"], {}), "(workdir + '/r*')\n", (5391, 5408), False, 'import glob, os, sys\n'), ((8553, 8654), 'load_gridded_data.read_gridded_data_CMIP5_model', 'read_gridded_data_CMIP5_model', (['datadir', 'datafile', 'vardict'], {'outtimeavg': 'annual', 'anom_ref': 'ref_period'}), '(datadir, datafile, vardict, outtimeavg=annual,\n anom_ref=ref_period)\n', (8582, 8654), False, 'from load_gridded_data import read_gridded_data_CMIP5_model\n'), ((8734, 8767), 'numpy.array', 'np.array', (['[d.year for d in rtime]'], {}), '([d.year for d in rtime])\n', (8742, 8767), True, 'import numpy as np\n'), ((9269, 9298), 'numpy.meshgrid', 'np.meshgrid', (['lon_TCR', 'lat_TCR'], {}), '(lon_TCR, lat_TCR)\n', (9280, 9298), True, 'import numpy as np\n'), ((9671, 9772), 'load_gridded_data.read_gridded_data_CMIP5_model', 'read_gridded_data_CMIP5_model', (['datadir', 'datafile', 'vardict'], {'outtimeavg': 'annual', 'anom_ref': 'ref_period'}), '(datadir, datafile, vardict, outtimeavg=annual,\n anom_ref=ref_period)\n', (9700, 9772), False, 'from load_gridded_data import read_gridded_data_CMIP5_model\n'), ((9855, 9888), 'numpy.array', 'np.array', (['[d.year for d in rtime]'], {}), '([d.year for d in rtime])\n', (9863, 9888), True, 'import numpy as np\n'), ((10430, 10465), 'numpy.meshgrid', 'np.meshgrid', (['lon_ERA20C', 'lat_ERA20C'], {}), '(lon_ERA20C, lat_ERA20C)\n', (10441, 10465), True, 'import numpy as np\n'), ((11839, 11898), 'spharm.Spharmt', 'Spharmt', (['nlon', 'nlat'], {'gridtype': '"""regular"""', 'legfunc': '"""computed"""'}), "(nlon, nlat, gridtype='regular', legfunc='computed')\n", (11846, 11898), False, 'from spharm import Spharmt, getspecindx, regrid\n'), ((11913, 11980), 'spharm.Spharmt', 'Spharmt', (['nlon_TCR', 'nlat_TCR'], {'gridtype': '"""regular"""', 'legfunc': '"""computed"""'}), "(nlon_TCR, nlat_TCR, gridtype='regular', legfunc='computed')\n", (11920, 11980), False, 'from spharm import Spharmt, getspecindx, regrid\n'), ((11998, 12071), 'spharm.Spharmt', 'Spharmt', (['nlon_ERA20C', 'nlat_ERA20C'], {'gridtype': '"""regular"""', 'legfunc': '"""computed"""'}), "(nlon_ERA20C, nlat_ERA20C, gridtype='regular', legfunc='computed')\n", (12005, 12071), False, 'from spharm import Spharmt, getspecindx, regrid\n'), ((12418, 12453), 'numpy.arange', 'np.arange', (['(-90.0)', '(90.0 + dlat)', 'dlat'], {}), '(-90.0, 90.0 + dlat, dlat)\n', (12427, 12453), True, 'import numpy as np\n'), ((12461, 12488), 'numpy.arange', 'np.arange', (['(0.0)', '(360.0)', 'dlon'], {}), '(0.0, 360.0, dlon)\n', (12470, 12488), True, 'import numpy as np\n'), ((12497, 12527), 'numpy.zeros', 'np.zeros', (['[nlat_new, nlon_new]'], {}), '([nlat_new, nlon_new])\n', (12505, 12527), True, 'import numpy as np\n'), ((12690, 12757), 'spharm.Spharmt', 'Spharmt', (['nlon_new', 'nlat_new'], {'gridtype': '"""regular"""', 'legfunc': '"""computed"""'}), "(nlon_new, nlat_new, gridtype='regular', legfunc='computed')\n", (12697, 12757), False, 'from spharm import Spharmt, getspecindx, regrid\n'), ((22341, 22389), 'numpy.linspace', 'np.linspace', (['corr_range[0]', 'corr_range[1]', 'nbins'], {}), '(corr_range[0], corr_range[1], nbins)\n', (22352, 22389), True, 'import numpy as np\n'), ((22436, 22448), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (22446, 22448), True, 'import matplotlib.pyplot as plt\n'), ((24928, 25020), 'matplotlib.pyplot.subplots_adjust', 'plt.subplots_adjust', ([], {'left': '(0.1)', 'bottom': '(0.45)', 'right': '(0.95)', 'top': '(0.93)', 'wspace': '(0.5)', 'hspace': '(0.5)'}), '(left=0.1, bottom=0.45, right=0.95, top=0.93, wspace=0.5,\n hspace=0.5)\n', (24947, 25020), True, 'import matplotlib.pyplot as plt\n'), ((28349, 28379), 'numpy.zeros', 'np.zeros', (['[nlat_new, nlon_new]'], {}), '([nlat_new, nlon_new])\n', (28357, 28379), True, 'import numpy as np\n'), ((28391, 28421), 'numpy.zeros', 'np.zeros', (['[nlat_new, nlon_new]'], {}), '([nlat_new, nlon_new])\n', (28399, 28421), True, 'import numpy as np\n'), ((28432, 28462), 'numpy.zeros', 'np.zeros', (['[nlat_new, nlon_new]'], {}), '([nlat_new, nlon_new])\n', (28440, 28462), True, 'import numpy as np\n'), ((28474, 28504), 'numpy.zeros', 'np.zeros', (['[nlat_new, nlon_new]'], {}), '([nlat_new, nlon_new])\n', (28482, 28504), True, 'import numpy as np\n'), ((28515, 28545), 'numpy.zeros', 'np.zeros', (['[nlat_new, nlon_new]'], {}), '([nlat_new, nlon_new])\n', (28523, 28545), True, 'import numpy as np\n'), ((28557, 28587), 'numpy.zeros', 'np.zeros', (['[nlat_new, nlon_new]'], {}), '([nlat_new, nlon_new])\n', (28565, 28587), True, 'import numpy as np\n'), ((28621, 28671), 'LMR_utils.coefficient_efficiency', 'coefficient_efficiency', (['tcr_allyears', 'lmr_allyears'], {}), '(tcr_allyears, lmr_allyears)\n', (28643, 28671), False, 'from LMR_utils import global_hemispheric_means, assimilated_proxies, coefficient_efficiency\n'), ((28683, 28736), 'LMR_utils.coefficient_efficiency', 'coefficient_efficiency', (['era20c_allyears', 'lmr_allyears'], {}), '(era20c_allyears, lmr_allyears)\n', (28705, 28736), False, 'from LMR_utils import global_hemispheric_means, assimilated_proxies, coefficient_efficiency\n'), ((28748, 28801), 'LMR_utils.coefficient_efficiency', 'coefficient_efficiency', (['era20c_allyears', 'tcr_allyears'], {}), '(era20c_allyears, tcr_allyears)\n', (28770, 28801), False, 'from LMR_utils import global_hemispheric_means, assimilated_proxies, coefficient_efficiency\n'), ((30125, 30151), 'numpy.squeeze', 'np.squeeze', (['lat2_new[:, 0]'], {}), '(lat2_new[:, 0])\n', (30135, 30151), True, 'import numpy as np\n'), ((30164, 30220), 'numpy.where', 'np.where', (['((lat_trunc[:] > -60.0) & (lat_trunc[:] < 60.0))'], {}), '((lat_trunc[:] > -60.0) & (lat_trunc[:] < 60.0))\n', (30172, 30220), True, 'import numpy as np\n'), ((32000, 32038), 'LMR_utils.global_hemispheric_means', 'global_hemispheric_means', (['r_lt', 'veclat'], {}), '(r_lt, veclat)\n', (32024, 32038), False, 'from LMR_utils import global_hemispheric_means, assimilated_proxies, coefficient_efficiency\n'), ((32080, 32119), 'LMR_utils.global_hemispheric_means', 'global_hemispheric_means', (['ce_lt', 'veclat'], {}), '(ce_lt, veclat)\n', (32104, 32119), False, 'from LMR_utils import global_hemispheric_means, assimilated_proxies, coefficient_efficiency\n'), ((32516, 32554), 'LMR_utils.global_hemispheric_means', 'global_hemispheric_means', (['r_le', 'veclat'], {}), '(r_le, veclat)\n', (32540, 32554), False, 'from LMR_utils import global_hemispheric_means, assimilated_proxies, coefficient_efficiency\n'), ((32596, 32635), 'LMR_utils.global_hemispheric_means', 'global_hemispheric_means', (['ce_le', 'veclat'], {}), '(ce_le, veclat)\n', (32620, 32635), False, 'from LMR_utils import global_hemispheric_means, assimilated_proxies, coefficient_efficiency\n'), ((33032, 33070), 'LMR_utils.global_hemispheric_means', 'global_hemispheric_means', (['r_te', 'veclat'], {}), '(r_te, veclat)\n', (33056, 33070), False, 'from LMR_utils import global_hemispheric_means, assimilated_proxies, coefficient_efficiency\n'), ((33112, 33151), 'LMR_utils.global_hemispheric_means', 'global_hemispheric_means', (['ce_te', 'veclat'], {}), '(ce_te, veclat)\n', (33136, 33151), False, 'from LMR_utils import global_hemispheric_means, assimilated_proxies, coefficient_efficiency\n'), ((33538, 33558), 'numpy.zeros', 'np.zeros', (['[nlat_new]'], {}), '([nlat_new])\n', (33546, 33558), True, 'import numpy as np\n'), ((33574, 33594), 'numpy.zeros', 'np.zeros', (['[nlat_new]'], {}), '([nlat_new])\n', (33582, 33594), True, 'import numpy as np\n'), ((33667, 33687), 'numpy.zeros', 'np.zeros', (['[nlat_new]'], {}), '([nlat_new])\n', (33675, 33687), True, 'import numpy as np\n'), ((33703, 33723), 'numpy.zeros', 'np.zeros', (['[nlat_new]'], {}), '([nlat_new])\n', (33711, 33723), True, 'import numpy as np\n'), ((34668, 34690), 'numpy.arange', 'np.arange', (['(-90)', '(91)', '(30)'], {}), '(-90, 91, 30)\n', (34677, 34690), True, 'import numpy as np\n'), ((34701, 34713), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (34711, 34713), True, 'import matplotlib.pyplot as plt\n'), ((35030, 35049), 'matplotlib.pyplot.ylim', 'plt.ylim', (['[-90, 90]'], {}), '([-90, 90])\n', (35038, 35049), True, 'import matplotlib.pyplot as plt\n'), ((35053, 35070), 'matplotlib.pyplot.xlim', 'plt.xlim', (['[-1, 1]'], {}), '([-1, 1])\n', (35061, 35070), True, 'import matplotlib.pyplot as plt\n'), ((35074, 35115), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Latitude"""'], {'fontweight': '"""bold"""'}), "('Latitude', fontweight='bold')\n", (35084, 35115), True, 'import matplotlib.pyplot as plt\n'), ((35119, 35163), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Correlation"""'], {'fontweight': '"""bold"""'}), "('Correlation', fontweight='bold')\n", (35129, 35163), True, 'import matplotlib.pyplot as plt\n'), ((35527, 35546), 'matplotlib.pyplot.ylim', 'plt.ylim', (['[-90, 90]'], {}), '([-90, 90])\n', (35535, 35546), True, 'import matplotlib.pyplot as plt\n'), ((35550, 35569), 'matplotlib.pyplot.xlim', 'plt.xlim', (['[-1.5, 1]'], {}), '([-1.5, 1])\n', (35558, 35569), True, 'import matplotlib.pyplot as plt\n'), ((35573, 35631), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Coefficient of efficiency"""'], {'fontweight': '"""bold"""'}), "('Coefficient of efficiency', fontweight='bold')\n", (35583, 35631), True, 'import matplotlib.pyplot as plt\n'), ((35683, 35773), 'matplotlib.pyplot.suptitle', 'plt.suptitle', (["('LMR zonal-mean verification - ' + verif_dict[var][2])"], {'fontweight': '"""bold"""'}), "('LMR zonal-mean verification - ' + verif_dict[var][2],\n fontweight='bold')\n", (35695, 35773), True, 'import matplotlib.pyplot as plt\n'), ((6484, 6500), 'numpy.load', 'np.load', (['ensfiln'], {}), '(ensfiln)\n', (6491, 6500), True, 'import numpy as np\n'), ((7741, 7758), 'numpy.shape', 'np.shape', (['xam_var'], {}), '(xam_var)\n', (7749, 7758), True, 'import numpy as np\n'), ((8974, 8989), 'numpy.unique', 'np.unique', (['lats'], {}), '(lats)\n', (8983, 8989), True, 'import numpy as np\n'), ((9008, 9023), 'numpy.unique', 'np.unique', (['lons'], {}), '(lons)\n', (9017, 9023), True, 'import numpy as np\n'), ((10098, 10113), 'numpy.unique', 'np.unique', (['lats'], {}), '(lats)\n', (10107, 10113), True, 'import numpy as np\n'), ((10135, 10150), 'numpy.unique', 'np.unique', (['lons'], {}), '(lons)\n', (10144, 10150), True, 'import numpy as np\n'), ((11217, 11258), 'numpy.mean', 'np.mean', (['LMR[smatch:ematch, :, :]'], {'axis': '(0)'}), '(LMR[smatch:ematch, :, :], axis=0)\n', (11224, 11258), True, 'import numpy as np\n'), ((11344, 11385), 'numpy.mean', 'np.mean', (['TCR[smatch:ematch, :, :]'], {'axis': '(0)'}), '(TCR[smatch:ematch, :, :], axis=0)\n', (11351, 11385), True, 'import numpy as np\n'), ((11480, 11524), 'numpy.mean', 'np.mean', (['ERA20C[smatch:ematch, :, :]'], {'axis': '(0)'}), '(ERA20C[smatch:ematch, :, :], axis=0)\n', (11487, 11524), True, 'import numpy as np\n'), ((13968, 14012), 'numpy.mean', 'np.mean', (['LMR[LMR_smatch:LMR_ematch, :, :]', '(0)'], {}), '(LMR[LMR_smatch:LMR_ematch, :, :], 0)\n', (13975, 14012), True, 'import numpy as np\n'), ((14034, 14109), 'spharm.regrid', 'regrid', (['specob_lmr', 'specob_new', 'pdata_lmr'], {'ntrunc': '(nlat_new - 1)', 'smooth': 'None'}), '(specob_lmr, specob_new, pdata_lmr, ntrunc=nlat_new - 1, smooth=None)\n', (14040, 14109), False, 'from spharm import Spharmt, getspecindx, regrid\n'), ((17412, 17433), 'numpy.mean', 'np.mean', (['lmr_trunc', '(1)'], {}), '(lmr_trunc, 1)\n', (17419, 17433), True, 'import numpy as np\n'), ((17559, 17589), 'numpy.where', 'np.where', (['(fracok >= valid_frac)'], {}), '(fracok >= valid_frac)\n', (17567, 17589), True, 'import numpy as np\n'), ((17610, 17639), 'numpy.where', 'np.where', (['(fracok < valid_frac)'], {}), '(fracok < valid_frac)\n', (17618, 17639), True, 'import numpy as np\n'), ((17895, 17925), 'numpy.where', 'np.where', (['(fracok >= valid_frac)'], {}), '(fracok >= valid_frac)\n', (17903, 17925), True, 'import numpy as np\n'), ((17946, 17975), 'numpy.where', 'np.where', (['(fracok < valid_frac)'], {}), '(fracok < valid_frac)\n', (17954, 17975), True, 'import numpy as np\n'), ((20925, 20972), 'numpy.reshape', 'np.reshape', (['lmr_trunc', '(1, nlat_new * nlon_new)'], {}), '(lmr_trunc, (1, nlat_new * nlon_new))\n', (20935, 20972), True, 'import numpy as np\n'), ((20986, 21033), 'numpy.reshape', 'np.reshape', (['tcr_trunc', '(1, nlat_new * nlon_new)'], {}), '(tcr_trunc, (1, nlat_new * nlon_new))\n', (20996, 21033), True, 'import numpy as np\n'), ((21050, 21100), 'numpy.reshape', 'np.reshape', (['era20c_trunc', '(1, nlat_new * nlon_new)'], {}), '(era20c_trunc, (1, nlat_new * nlon_new))\n', (21060, 21100), True, 'import numpy as np\n'), ((21136, 21155), 'numpy.isfinite', 'np.isfinite', (['tcrvec'], {}), '(tcrvec)\n', (21147, 21155), True, 'import numpy as np\n'), ((21164, 21177), 'numpy.sum', 'np.sum', (['indok'], {}), '(indok)\n', (21170, 21177), True, 'import numpy as np\n'), ((21497, 21519), 'numpy.isfinite', 'np.isfinite', (['era20cvec'], {}), '(era20cvec)\n', (21508, 21519), True, 'import numpy as np\n'), ((21528, 21541), 'numpy.sum', 'np.sum', (['indok'], {}), '(indok)\n', (21534, 21541), True, 'import numpy as np\n'), ((21867, 21889), 'numpy.isfinite', 'np.isfinite', (['era20cvec'], {}), '(era20cvec)\n', (21878, 21889), True, 'import numpy as np\n'), ((21898, 21911), 'numpy.sum', 'np.sum', (['indok'], {}), '(indok)\n', (21904, 21911), True, 'import numpy as np\n'), ((25454, 25465), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (25463, 25465), True, 'import matplotlib.pyplot as plt\n'), ((25620, 25632), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (25630, 25632), True, 'import matplotlib.pyplot as plt\n'), ((27475, 27567), 'matplotlib.pyplot.subplots_adjust', 'plt.subplots_adjust', ([], {'left': '(0.1)', 'bottom': '(0.45)', 'right': '(0.95)', 'top': '(0.93)', 'wspace': '(0.5)', 'hspace': '(0.5)'}), '(left=0.1, bottom=0.45, right=0.95, top=0.93, wspace=0.5,\n hspace=0.5)\n', (27494, 27567), True, 'import matplotlib.pyplot as plt\n'), ((27972, 27983), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (27981, 27983), True, 'import matplotlib.pyplot as plt\n'), ((33832, 33902), 'LMR_utils.coefficient_efficiency', 'coefficient_efficiency', (['tcr_zm[:, la]', 'lmr_zm[:, la]'], {'valid': 'valid_frac'}), '(tcr_zm[:, la], lmr_zm[:, la], valid=valid_frac)\n', (33854, 33902), False, 'from LMR_utils import global_hemispheric_means, assimilated_proxies, coefficient_efficiency\n'), ((33915, 33941), 'numpy.isfinite', 'np.isfinite', (['tcr_zm[:, la]'], {}), '(tcr_zm[:, la])\n', (33926, 33941), True, 'import numpy as np\n'), ((33956, 33969), 'numpy.sum', 'np.sum', (['indok'], {}), '(indok)\n', (33962, 33969), True, 'import numpy as np\n'), ((34241, 34314), 'LMR_utils.coefficient_efficiency', 'coefficient_efficiency', (['era20c_zm[:, la]', 'lmr_zm[:, la]'], {'valid': 'valid_frac'}), '(era20c_zm[:, la], lmr_zm[:, la], valid=valid_frac)\n', (34263, 34314), False, 'from LMR_utils import global_hemispheric_means, assimilated_proxies, coefficient_efficiency\n'), ((34331, 34360), 'numpy.isfinite', 'np.isfinite', (['era20c_zm[:, la]'], {}), '(era20c_zm[:, la])\n', (34342, 34360), True, 'import numpy as np\n'), ((34375, 34388), 'numpy.sum', 'np.sum', (['indok'], {}), '(indok)\n', (34381, 34388), True, 'import numpy as np\n'), ((36141, 36152), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (36150, 36152), True, 'import matplotlib.pyplot as plt\n'), ((36288, 36300), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (36298, 36300), True, 'import matplotlib.pyplot as plt\n'), ((36595, 36610), 'matplotlib.pyplot.clim', 'plt.clim', (['(-1)', '(1)'], {}), '(-1, 1)\n', (36603, 36610), True, 'import matplotlib.pyplot as plt\n'), ((36946, 36961), 'matplotlib.pyplot.clim', 'plt.clim', (['(-1)', '(1)'], {}), '(-1, 1)\n', (36954, 36961), True, 'import matplotlib.pyplot as plt\n'), ((37298, 37313), 'matplotlib.pyplot.clim', 'plt.clim', (['(-1)', '(1)'], {}), '(-1, 1)\n', (37306, 37313), True, 'import matplotlib.pyplot as plt\n'), ((37649, 37664), 'matplotlib.pyplot.clim', 'plt.clim', (['(-1)', '(1)'], {}), '(-1, 1)\n', (37657, 37664), True, 'import matplotlib.pyplot as plt\n'), ((38005, 38020), 'matplotlib.pyplot.clim', 'plt.clim', (['(-1)', '(1)'], {}), '(-1, 1)\n', (38013, 38020), True, 'import matplotlib.pyplot as plt\n'), ((38360, 38375), 'matplotlib.pyplot.clim', 'plt.clim', (['(-1)', '(1)'], {}), '(-1, 1)\n', (38368, 38375), True, 'import matplotlib.pyplot as plt\n'), ((5869, 5892), 'os.path.exists', 'os.path.exists', (['ensfiln'], {}), '(ensfiln)\n', (5883, 5892), False, 'import glob, os, sys\n'), ((6916, 6945), 'numpy.reshape', 'np.reshape', (['lat', '(nlat, nlon)'], {}), '(lat, (nlat, nlon))\n', (6926, 6945), True, 'import numpy as np\n'), ((6963, 6992), 'numpy.reshape', 'np.reshape', (['lon', '(nlat, nlon)'], {}), '(lon, (nlat, nlon))\n', (6973, 6992), True, 'import numpy as np\n'), ((7498, 7521), 'numpy.max', 'np.max', (['(xam_check - xam)'], {}), '(xam_check - xam)\n', (7504, 7521), True, 'import numpy as np\n'), ((12197, 12226), 'numpy.remainder', 'np.remainder', (['ntrunc_new', '(2.0)'], {}), '(ntrunc_new, 2.0)\n', (12209, 12226), True, 'import numpy as np\n'), ((14189, 14233), 'numpy.mean', 'np.mean', (['TCR[TCR_smatch:TCR_ematch, :, :]', '(0)'], {}), '(TCR[TCR_smatch:TCR_ematch, :, :], 0)\n', (14196, 14233), True, 'import numpy as np\n'), ((14269, 14305), 'numpy.zeros', 'np.zeros', ([], {'shape': '[nlat_TCR, nlon_TCR]'}), '(shape=[nlat_TCR, nlon_TCR])\n', (14277, 14305), True, 'import numpy as np\n'), ((14432, 14468), 'numpy.zeros', 'np.zeros', ([], {'shape': '[nlat_new, nlon_new]'}), '(shape=[nlat_new, nlon_new])\n', (14440, 14468), True, 'import numpy as np\n'), ((14541, 14616), 'spharm.regrid', 'regrid', (['specob_tcr', 'specob_new', 'pdata_tcr'], {'ntrunc': '(nlat_new - 1)', 'smooth': 'None'}), '(specob_tcr, specob_new, pdata_tcr, ntrunc=nlat_new - 1, smooth=None)\n', (14547, 14616), False, 'from spharm import Spharmt, getspecindx, regrid\n'), ((14704, 14757), 'numpy.mean', 'np.mean', (['ERA20C[ERA20C_smatch:ERA20C_ematch, :, :]', '(0)'], {}), '(ERA20C[ERA20C_smatch:ERA20C_ematch, :, :], 0)\n', (14711, 14757), True, 'import numpy as np\n'), ((14796, 14838), 'numpy.zeros', 'np.zeros', ([], {'shape': '[nlat_ERA20C, nlon_ERA20C]'}), '(shape=[nlat_ERA20C, nlon_ERA20C])\n', (14804, 14838), True, 'import numpy as np\n'), ((14974, 15010), 'numpy.zeros', 'np.zeros', ([], {'shape': '[nlat_new, nlon_new]'}), '(shape=[nlat_new, nlon_new])\n', (14982, 15010), True, 'import numpy as np\n'), ((15089, 15175), 'spharm.regrid', 'regrid', (['specob_era20c', 'specob_new', 'pdata_era20c'], {'ntrunc': '(nlat_new - 1)', 'smooth': 'None'}), '(specob_era20c, specob_new, pdata_era20c, ntrunc=nlat_new - 1, smooth\n =None)\n', (15095, 15175), False, 'from spharm import Spharmt, getspecindx, regrid\n'), ((15431, 15443), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (15441, 15443), True, 'import matplotlib.pyplot as plt\n'), ((15755, 15775), 'matplotlib.pyplot.clim', 'plt.clim', (['fmin', 'fmax'], {}), '(fmin, fmax)\n', (15763, 15775), True, 'import matplotlib.pyplot as plt\n'), ((16341, 16361), 'matplotlib.pyplot.clim', 'plt.clim', (['fmin', 'fmax'], {}), '(fmin, fmax)\n', (16349, 16361), True, 'import matplotlib.pyplot as plt\n'), ((16939, 16959), 'matplotlib.pyplot.clim', 'plt.clim', (['fmin', 'fmax'], {}), '(fmin, fmax)\n', (16947, 16959), True, 'import matplotlib.pyplot as plt\n'), ((17093, 17104), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (17102, 17104), True, 'import matplotlib.pyplot as plt\n'), ((17691, 17726), 'numpy.nanmean', 'np.nanmean', (['tcr_trunc[i, :]'], {'axis': '(1)'}), '(tcr_trunc[i, :], axis=1)\n', (17701, 17726), True, 'import numpy as np\n'), ((18030, 18068), 'numpy.nanmean', 'np.nanmean', (['era20c_trunc[i, :]'], {'axis': '(1)'}), '(era20c_trunc[i, :], axis=1)\n', (18040, 18068), True, 'import numpy as np\n'), ((18419, 18451), 'numpy.round', 'np.round', (['(maxabs * 2 / ncints)', '(2)'], {}), '(maxabs * 2 / ncints, 2)\n', (18427, 18451), True, 'import numpy as np\n'), ((18497, 18540), 'numpy.linspace', 'np.linspace', (['(-cl)', 'cl', 'ncints'], {'endpoint': '(True)'}), '(-cl, cl, ncints, endpoint=True)\n', (18508, 18540), True, 'import numpy as np\n'), ((18610, 18622), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (18620, 18622), True, 'import matplotlib.pyplot as plt\n'), ((18689, 18728), 'mpl_toolkits.basemap.Basemap', 'bm.Basemap', ([], {'projection': '"""robin"""', 'lon_0': '(0)'}), "(projection='robin', lon_0=0)\n", (18699, 18728), True, 'import mpl_toolkits.basemap as bm\n'), ((18985, 19017), 'matplotlib.ticker.MaxNLocator', 'ticker.MaxNLocator', ([], {'nbins': 'nticks'}), '(nbins=nticks)\n', (19003, 19017), False, 'from matplotlib import ticker\n'), ((19315, 19354), 'mpl_toolkits.basemap.Basemap', 'bm.Basemap', ([], {'projection': '"""robin"""', 'lon_0': '(0)'}), "(projection='robin', lon_0=0)\n", (19325, 19354), True, 'import mpl_toolkits.basemap as bm\n'), ((19611, 19643), 'matplotlib.ticker.MaxNLocator', 'ticker.MaxNLocator', ([], {'nbins': 'nticks'}), '(nbins=nticks)\n', (19629, 19643), False, 'from matplotlib import ticker\n'), ((19945, 19984), 'mpl_toolkits.basemap.Basemap', 'bm.Basemap', ([], {'projection': '"""robin"""', 'lon_0': '(0)'}), "(projection='robin', lon_0=0)\n", (19955, 19984), True, 'import mpl_toolkits.basemap as bm\n'), ((20244, 20276), 'matplotlib.ticker.MaxNLocator', 'ticker.MaxNLocator', ([], {'nbins': 'nticks'}), '(nbins=nticks)\n', (20262, 20276), False, 'from matplotlib import ticker\n'), ((20532, 20557), 'matplotlib.pyplot.clim', 'plt.clim', (['(-maxabs)', 'maxabs'], {}), '(-maxabs, maxabs)\n', (20540, 20557), True, 'import matplotlib.pyplot as plt\n'), ((20651, 20745), 'matplotlib.pyplot.subplots_adjust', 'plt.subplots_adjust', ([], {'left': '(0.05)', 'bottom': '(0.45)', 'right': '(0.95)', 'top': '(0.95)', 'wspace': '(0.1)', 'hspace': '(0.0)'}), '(left=0.05, bottom=0.45, right=0.95, top=0.95, wspace=\n 0.1, hspace=0.0)\n', (20670, 20745), True, 'import matplotlib.pyplot as plt\n'), ((28928, 28964), 'numpy.isfinite', 'np.isfinite', (['tcr_allyears[:, la, lo]'], {}), '(tcr_allyears[:, la, lo])\n', (28939, 28964), True, 'import numpy as np\n'), ((28982, 28995), 'numpy.sum', 'np.sum', (['indok'], {}), '(indok)\n', (28988, 28995), True, 'import numpy as np\n'), ((29328, 29367), 'numpy.isfinite', 'np.isfinite', (['era20c_allyears[:, la, lo]'], {}), '(era20c_allyears[:, la, lo])\n', (29339, 29367), True, 'import numpy as np\n'), ((29385, 29398), 'numpy.sum', 'np.sum', (['indok'], {}), '(indok)\n', (29391, 29398), True, 'import numpy as np\n'), ((29734, 29773), 'numpy.isfinite', 'np.isfinite', (['era20c_allyears[:, la, lo]'], {}), '(era20c_allyears[:, la, lo])\n', (29745, 29773), True, 'import numpy as np\n'), ((29791, 29804), 'numpy.sum', 'np.sum', (['indok'], {}), '(indok)\n', (29797, 29804), True, 'import numpy as np\n'), ((38786, 38797), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (38795, 38797), True, 'import matplotlib.pyplot as plt\n'), ((38973, 38985), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (38983, 38985), True, 'import matplotlib.pyplot as plt\n'), ((39296, 39311), 'matplotlib.pyplot.clim', 'plt.clim', (['(-1)', '(1)'], {}), '(-1, 1)\n', (39304, 39311), True, 'import matplotlib.pyplot as plt\n'), ((39667, 39682), 'matplotlib.pyplot.clim', 'plt.clim', (['(-1)', '(1)'], {}), '(-1, 1)\n', (39675, 39682), True, 'import matplotlib.pyplot as plt\n'), ((40039, 40054), 'matplotlib.pyplot.clim', 'plt.clim', (['(-1)', '(1)'], {}), '(-1, 1)\n', (40047, 40054), True, 'import matplotlib.pyplot as plt\n'), ((40410, 40425), 'matplotlib.pyplot.clim', 'plt.clim', (['(-1)', '(1)'], {}), '(-1, 1)\n', (40418, 40425), True, 'import matplotlib.pyplot as plt\n'), ((40836, 40847), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (40845, 40847), True, 'import matplotlib.pyplot as plt\n'), ((7817, 7834), 'numpy.shape', 'np.shape', (['xam_all'], {}), '(xam_all)\n', (7825, 7834), True, 'import numpy as np\n'), ((7898, 7911), 'numpy.shape', 'np.shape', (['xam'], {}), '(xam)\n', (7906, 7911), True, 'import numpy as np\n'), ((14381, 14400), 'numpy.isnan', 'np.isnan', (['pdata_tcr'], {}), '(pdata_tcr)\n', (14389, 14400), True, 'import numpy as np\n'), ((14917, 14939), 'numpy.isnan', 'np.isnan', (['pdata_era20c'], {}), '(pdata_era20c)\n', (14925, 14939), True, 'import numpy as np\n'), ((17475, 17497), 'numpy.isfinite', 'np.isfinite', (['tcr_trunc'], {}), '(tcr_trunc)\n', (17486, 17497), True, 'import numpy as np\n'), ((17805, 17830), 'numpy.isfinite', 'np.isfinite', (['era20c_trunc'], {}), '(era20c_trunc)\n', (17816, 17830), True, 'import numpy as np\n'), ((18314, 18331), 'numpy.abs', 'np.abs', (['tcr_trunc'], {}), '(tcr_trunc)\n', (18320, 18331), True, 'import numpy as np\n'), ((19098, 19129), 'matplotlib.ticker.AutoLocator', 'matplotlib.ticker.AutoLocator', ([], {}), '()\n', (19127, 19129), False, 'import matplotlib\n'), ((19724, 19755), 'matplotlib.ticker.AutoLocator', 'matplotlib.ticker.AutoLocator', ([], {}), '()\n', (19753, 19755), False, 'import matplotlib\n'), ((20357, 20388), 'matplotlib.ticker.AutoLocator', 'matplotlib.ticker.AutoLocator', ([], {}), '()\n', (20386, 20388), False, 'import matplotlib\n'), ((21301, 21342), 'numpy.corrcoef', 'np.corrcoef', (['lmrvec[indok]', 'tcrvec[indok]'], {}), '(lmrvec[indok], tcrvec[indok])\n', (21312, 21342), True, 'import numpy as np\n'), ((21668, 21712), 'numpy.corrcoef', 'np.corrcoef', (['lmrvec[indok]', 'era20cvec[indok]'], {}), '(lmrvec[indok], era20cvec[indok])\n', (21679, 21712), True, 'import numpy as np\n'), ((22038, 22082), 'numpy.corrcoef', 'np.corrcoef', (['tcrvec[indok]', 'era20cvec[indok]'], {}), '(tcrvec[indok], era20cvec[indok])\n', (22049, 22082), True, 'import numpy as np\n'), ((22802, 22820), 'numpy.isnan', 'np.isnan', (['lt_csave'], {}), '(lt_csave)\n', (22810, 22820), True, 'import numpy as np\n'), ((23170, 23190), 'numpy.nanmean', 'np.nanmean', (['lt_csave'], {}), '(lt_csave)\n', (23180, 23190), True, 'import numpy as np\n'), ((23580, 23598), 'numpy.isnan', 'np.isnan', (['le_csave'], {}), '(le_csave)\n', (23588, 23598), True, 'import numpy as np\n'), ((23948, 23968), 'numpy.nanmean', 'np.nanmean', (['le_csave'], {}), '(le_csave)\n', (23958, 23968), True, 'import numpy as np\n'), ((24424, 24442), 'numpy.isnan', 'np.isnan', (['te_csave'], {}), '(te_csave)\n', (24432, 24442), True, 'import numpy as np\n'), ((24847, 24867), 'numpy.nanmean', 'np.nanmean', (['te_csave'], {}), '(te_csave)\n', (24857, 24867), True, 'import numpy as np\n'), ((34096, 34145), 'numpy.corrcoef', 'np.corrcoef', (['lmr_zm[indok, la]', 'tcr_zm[indok, la]'], {}), '(lmr_zm[indok, la], tcr_zm[indok, la])\n', (34107, 34145), True, 'import numpy as np\n'), ((34515, 34567), 'numpy.corrcoef', 'np.corrcoef', (['lmr_zm[indok, la]', 'era20c_zm[indok, la]'], {}), '(lmr_zm[indok, la], era20c_zm[indok, la])\n', (34526, 34567), True, 'import numpy as np\n'), ((6598, 6611), 'numpy.shape', 'np.shape', (['tmp'], {}), '(tmp)\n', (6606, 6611), True, 'import numpy as np\n'), ((18848, 18866), 'matplotlib.pyplot.get_cmap', 'plt.get_cmap', (['cmap'], {}), '(cmap)\n', (18860, 18866), True, 'import matplotlib.pyplot as plt\n'), ((19474, 19492), 'matplotlib.pyplot.get_cmap', 'plt.get_cmap', (['cmap'], {}), '(cmap)\n', (19486, 19492), True, 'import matplotlib.pyplot as plt\n'), ((20107, 20125), 'matplotlib.pyplot.get_cmap', 'plt.get_cmap', (['cmap'], {}), '(cmap)\n', (20119, 20125), True, 'import matplotlib.pyplot as plt\n'), ((26019, 26037), 'numpy.isnan', 'np.isnan', (['lt_csave'], {}), '(lt_csave)\n', (26027, 26037), True, 'import numpy as np\n'), ((26419, 26439), 'numpy.nanmean', 'np.nanmean', (['lt_csave'], {}), '(lt_csave)\n', (26429, 26439), True, 'import numpy as np\n'), ((26927, 26945), 'numpy.isnan', 'np.isnan', (['le_csave'], {}), '(le_csave)\n', (26935, 26945), True, 'import numpy as np\n'), ((27382, 27402), 'numpy.nanmean', 'np.nanmean', (['le_csave'], {}), '(le_csave)\n', (27392, 27402), True, 'import numpy as np\n'), ((29157, 29226), 'numpy.corrcoef', 'np.corrcoef', (['lmr_allyears[indok, la, lo]', 'tcr_allyears[indok, la, lo]'], {}), '(lmr_allyears[indok, la, lo], tcr_allyears[indok, la, lo])\n', (29168, 29226), True, 'import numpy as np\n'), ((29560, 29632), 'numpy.corrcoef', 'np.corrcoef', (['lmr_allyears[indok, la, lo]', 'era20c_allyears[indok, la, lo]'], {}), '(lmr_allyears[indok, la, lo], era20c_allyears[indok, la, lo])\n', (29571, 29632), True, 'import numpy as np\n'), ((29966, 30038), 'numpy.corrcoef', 'np.corrcoef', (['tcr_allyears[indok, la, lo]', 'era20c_allyears[indok, la, lo]'], {}), '(tcr_allyears[indok, la, lo], era20c_allyears[indok, la, lo])\n', (29977, 30038), True, 'import numpy as np\n'), ((30268, 30283), 'numpy.median', 'np.median', (['r_lt'], {}), '(r_lt)\n', (30277, 30283), True, 'import numpy as np\n'), ((30402, 30428), 'numpy.median', 'np.median', (['r_lt[indlat, :]'], {}), '(r_lt[indlat, :])\n', (30411, 30428), True, 'import numpy as np\n'), ((30547, 30563), 'numpy.median', 'np.median', (['ce_lt'], {}), '(ce_lt)\n', (30556, 30563), True, 'import numpy as np\n'), ((30684, 30711), 'numpy.median', 'np.median', (['ce_lt[indlat, :]'], {}), '(ce_lt[indlat, :])\n', (30693, 30711), True, 'import numpy as np\n'), ((30830, 30845), 'numpy.median', 'np.median', (['r_le'], {}), '(r_le)\n', (30839, 30845), True, 'import numpy as np\n'), ((30964, 30990), 'numpy.median', 'np.median', (['r_le[indlat, :]'], {}), '(r_le[indlat, :])\n', (30973, 30990), True, 'import numpy as np\n'), ((31109, 31125), 'numpy.median', 'np.median', (['ce_le'], {}), '(ce_le)\n', (31118, 31125), True, 'import numpy as np\n'), ((31246, 31273), 'numpy.median', 'np.median', (['ce_le[indlat, :]'], {}), '(ce_le[indlat, :])\n', (31255, 31273), True, 'import numpy as np\n'), ((31392, 31407), 'numpy.median', 'np.median', (['r_te'], {}), '(r_te)\n', (31401, 31407), True, 'import numpy as np\n'), ((31526, 31552), 'numpy.median', 'np.median', (['r_te[indlat, :]'], {}), '(r_te[indlat, :])\n', (31535, 31552), True, 'import numpy as np\n'), ((31671, 31687), 'numpy.median', 'np.median', (['ce_te'], {}), '(ce_te)\n', (31680, 31687), True, 'import numpy as np\n'), ((31808, 31835), 'numpy.median', 'np.median', (['ce_te[indlat, :]'], {}), '(ce_te[indlat, :])\n', (31817, 31835), True, 'import numpy as np\n'), ((7092, 7105), 'numpy.shape', 'np.shape', (['tmp'], {}), '(tmp)\n', (7100, 7105), True, 'import numpy as np\n'), ((7109, 7122), 'numpy.shape', 'np.shape', (['tmp'], {}), '(tmp)\n', (7117, 7122), True, 'import numpy as np\n'), ((7172, 7185), 'numpy.shape', 'np.shape', (['tmp'], {}), '(tmp)\n', (7180, 7185), True, 'import numpy as np\n'), ((7189, 7202), 'numpy.shape', 'np.shape', (['tmp'], {}), '(tmp)\n', (7197, 7202), True, 'import numpy as np\n')] |
import sys
sys.path.insert(0, "../")
import numpy as np
import cv2
import argparse
import torch
from torchvision.transforms import functional as F
from mmcls.apis import init_model
import os
from tqdm import tqdm
class MmClassifier(object):
def __init__(self, cls_c, cls_w, device):
self.model_w = cls_w
self.device = device
self.cls_model = init_model(cls_c, cls_w, device=device)
self.cls_model.export = True # set export and return convolution result
self.short_size = 256
self.dst_w = 224
self.dst_h = 224
self.input_size = [self.dst_h, self.dst_w]
self.mean = np.array([123.675, 116.28, 103.53])
self.std = np.array([58.395, 57.12, 57.375])
self.std_inv = 1/self.std
self.cls_name = self.cls_model.CLASSES
self.result = dict()
def crop_img_short_size(self, cv_img):
# resize the short size
h, w, _ = cv_img.shape
print(h, w)
if h >= w:
h = int(h * self.short_size / w)
w = int(self.short_size)
else:
w = int(w * self.short_size / h)
h = int(self.short_size)
cv_img = cv2.resize(cv_img, (w, h), cv2.INTER_LINEAR)
# center crop
y1 = max(0, int(round((h - self.input_size[1]) / 2.)))
x1 = max(0, int(round((w - self.input_size[0]) / 2.)))
y2 = min(h-1, y1 + self.input_size[1])
x2 = min(w-1, x1 + self.input_size[0])
cv_img = cv_img[y1:y2, x1:x2, :]
return cv_img
def crop_img_long_size(self, cv_img):
long_size = max(cv_img.shape[:2])
pad_h = (long_size - cv_img.shape[0]) // 2
pad_w = (long_size - cv_img.shape[1]) // 2
img_input = np.ones((long_size, long_size, 3), dtype=np.uint8) * 0
img_input[pad_h:cv_img.shape[0] + pad_h, pad_w:cv_img.shape[1] + pad_w, :] = cv_img
img_input = cv2.resize(img_input, (self.input_size[1], self.input_size[0]), cv2.INTER_LINEAR)
return img_input
def get_cls_result(self, cv_img):
# cv_img = self.crop_img_short_size(cv_img)
cv_img = self.crop_img_long_size(cv_img)
assert list(cv_img.shape[:2]) == self.input_size
# normalize
cv_img = cv_img.copy().astype(np.float32)
self.mean = np.float64(self.mean.reshape(1, -1))
self.std_inv = 1 / np.float64(self.std.reshape(1, -1))
if True:
cv2.cvtColor(cv_img, cv2.COLOR_BGR2RGB, cv_img) # inplace
cv2.subtract(cv_img, self.mean, cv_img) # inplace
cv2.multiply(cv_img, self.std_inv, cv_img) # inplace
with torch.no_grad():
self.img_t = F.to_tensor(cv_img.copy()) # no resize
self.img_t = self.img_t.unsqueeze(0)
if 'cpu' not in self.device:
self.img_t = self.img_t.cuda()
output = self.cls_model(self.img_t, return_loss=False) # forward
pred_score = np.max(output, axis=1)[0]
pred_label = np.argmax(output, axis=1)[0]
self.result.update({'pred_label': pred_label, 'pred_score': float(pred_score), 'pred_class':self.cls_name[pred_label]})
return self.result
#
def export_onnx_model(self):
self.cls_model.export = True
img_dry = torch.zeros((1, 3, self.dst_h, self.dst_w))
with torch.no_grad():
y = self.cls_model(img_dry, return_loss=False) # forward
try:
import onnx
print('\nStarting ONNX export with onnx %s...' % onnx.__version__)
f = self.model_w.replace('.pth', '.onnx') # filename
# print(model.t)
torch.onnx.export(self.cls_model, img_dry, f, verbose=False, opset_version=11, \
input_names=['images'], output_names=['output'])
# Checks
onnx_model = onnx.load(f) # load onnx model
onnx.checker.check_model(onnx_model) # check onnx model
print(onnx.helper.printable_graph(onnx_model.graph)) # print a human readable model
# simpily onnx
from onnxsim import simplify
model_simp, check = simplify(onnx_model)
assert check, "Simplified ONNX model could not be validated"
f2 = f.replace('.onnx', '_sim.onnx') # filename
onnx.save(model_simp, f2)
print('====ONNX SIM export success, saved as %s' % f2)
from onnx import shape_inference
f3 = f2.replace('.onnx', '_shape.onnx') # filename
onnx.save(onnx.shape_inference.infer_shapes(onnx.load(f2)), f3)
print('====ONNX shape inference export success, saved as %s' % f3)
print('ONNX export success, saved as %s' % f)
except Exception as e:
print('ONNX export failure: %s' % e)
def export_pth_model(self):
self.cls_model.export = True
img_dry = torch.zeros((1, 3, self.dst_h, self.dst_w))
with torch.no_grad():
y = self.cls_model(img_dry) # forward
# torch.save(self.cls_model.state_dict(), "my_model.pth") # 只保存模型的参数
f = self.model_w.replace('.pth', '_gram.pth') # filename
print("save pth model:", f)
torch.save(self.cls_model, f) # 保存整个模型
if __name__ == "__main__":
print("Start Porc...")
parser = argparse.ArgumentParser()
parser.add_argument('--pose_config', help='Config file for detection')
parser.add_argument('--pose_checkpoint', help='Checkpoint file')
parser.add_argument('--device', default='cuda:0', help='Device used for inference')
opt = parser.parse_args()
opt.pose_config = "../configs/resnet/resnet50_b32x8_imagenet.py"
opt.pose_checkpoint = "../checkpoints/imagenet/resnet50_batch256_imagenet_20200708-cfb998bf.pth"
opt.device = "cpu"
mm_classifier = MmClassifier(opt.pose_config, opt.pose_checkpoint, opt.device)
img_path = "demo/cat.jpg"
img = cv2.imread(img_path)
# export onnx
# mm_classifier.export_onnx_model()
mm_classifier.export_pth_model()
exit(1)
# Start pose detector
img_path = "/home/liyongjing/Egolee/programs/mmclassification-master/demo/cat.jpg"
root_dir = "/home/liyongjing/Egolee/data/dataset/cls_fall_down/fall_down_person"
dst_dir = "/home/liyongjing/Egolee/programs/mmclassification-master/data/cls_fall_down/find_fall_down_from_opendataset/crowd_person_train"
img_names = list(filter(lambda x: os.path.splitext(x)[-1] in [".jpg"], os.listdir(root_dir)))
for img_name in tqdm(img_names):
img_path = os.path.join(root_dir, img_name)
img = cv2.imread(img_path)
cls_result = mm_classifier.get_cls_result(img)
print(cls_result)
cv2.namedWindow("img", 0)
cv2.imshow("img", img)
if cls_result['pred_label'] != 1:
# dst_path = img_path.replace(root_dir, dst_dir)
# shutil.copy(img_path, dst_path)
wait_key = cv2.waitKey(0)
if wait_key == 27:
exit(1)
# pred_result = mm_classifier.get_cls_result(img)
# print(pred_result)
# cv2.namedWindow("img", 0)
# cv2.imshow("img", img)
# wait_key = cv2.waitKey(0)
# if wait_key == 0:
# exit(1)
| [
"sys.path.insert",
"onnx.save",
"cv2.imshow",
"numpy.array",
"onnx.load",
"os.listdir",
"argparse.ArgumentParser",
"cv2.multiply",
"numpy.max",
"cv2.waitKey",
"torch.onnx.export",
"numpy.ones",
"onnxsim.simplify",
"os.path.splitext",
"numpy.argmax",
"torch.save",
"cv2.cvtColor",
"m... | [((11, 36), 'sys.path.insert', 'sys.path.insert', (['(0)', '"""../"""'], {}), "(0, '../')\n", (26, 36), False, 'import sys\n'), ((5345, 5370), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (5368, 5370), False, 'import argparse\n'), ((5951, 5971), 'cv2.imread', 'cv2.imread', (['img_path'], {}), '(img_path)\n', (5961, 5971), False, 'import cv2\n'), ((6541, 6556), 'tqdm.tqdm', 'tqdm', (['img_names'], {}), '(img_names)\n', (6545, 6556), False, 'from tqdm import tqdm\n'), ((373, 412), 'mmcls.apis.init_model', 'init_model', (['cls_c', 'cls_w'], {'device': 'device'}), '(cls_c, cls_w, device=device)\n', (383, 412), False, 'from mmcls.apis import init_model\n'), ((648, 683), 'numpy.array', 'np.array', (['[123.675, 116.28, 103.53]'], {}), '([123.675, 116.28, 103.53])\n', (656, 683), True, 'import numpy as np\n'), ((703, 736), 'numpy.array', 'np.array', (['[58.395, 57.12, 57.375]'], {}), '([58.395, 57.12, 57.375])\n', (711, 736), True, 'import numpy as np\n'), ((1190, 1234), 'cv2.resize', 'cv2.resize', (['cv_img', '(w, h)', 'cv2.INTER_LINEAR'], {}), '(cv_img, (w, h), cv2.INTER_LINEAR)\n', (1200, 1234), False, 'import cv2\n'), ((1917, 2003), 'cv2.resize', 'cv2.resize', (['img_input', '(self.input_size[1], self.input_size[0])', 'cv2.INTER_LINEAR'], {}), '(img_input, (self.input_size[1], self.input_size[0]), cv2.\n INTER_LINEAR)\n', (1927, 2003), False, 'import cv2\n'), ((2509, 2548), 'cv2.subtract', 'cv2.subtract', (['cv_img', 'self.mean', 'cv_img'], {}), '(cv_img, self.mean, cv_img)\n', (2521, 2548), False, 'import cv2\n'), ((2568, 2610), 'cv2.multiply', 'cv2.multiply', (['cv_img', 'self.std_inv', 'cv_img'], {}), '(cv_img, self.std_inv, cv_img)\n', (2580, 2610), False, 'import cv2\n'), ((3296, 3339), 'torch.zeros', 'torch.zeros', (['(1, 3, self.dst_h, self.dst_w)'], {}), '((1, 3, self.dst_h, self.dst_w))\n', (3307, 3339), False, 'import torch\n'), ((4922, 4965), 'torch.zeros', 'torch.zeros', (['(1, 3, self.dst_h, self.dst_w)'], {}), '((1, 3, self.dst_h, self.dst_w))\n', (4933, 4965), False, 'import torch\n'), ((5236, 5265), 'torch.save', 'torch.save', (['self.cls_model', 'f'], {}), '(self.cls_model, f)\n', (5246, 5265), False, 'import torch\n'), ((6577, 6609), 'os.path.join', 'os.path.join', (['root_dir', 'img_name'], {}), '(root_dir, img_name)\n', (6589, 6609), False, 'import os\n'), ((6624, 6644), 'cv2.imread', 'cv2.imread', (['img_path'], {}), '(img_path)\n', (6634, 6644), False, 'import cv2\n'), ((6735, 6760), 'cv2.namedWindow', 'cv2.namedWindow', (['"""img"""', '(0)'], {}), "('img', 0)\n", (6750, 6760), False, 'import cv2\n'), ((6769, 6791), 'cv2.imshow', 'cv2.imshow', (['"""img"""', 'img'], {}), "('img', img)\n", (6779, 6791), False, 'import cv2\n'), ((1750, 1800), 'numpy.ones', 'np.ones', (['(long_size, long_size, 3)'], {'dtype': 'np.uint8'}), '((long_size, long_size, 3), dtype=np.uint8)\n', (1757, 1800), True, 'import numpy as np\n'), ((2442, 2489), 'cv2.cvtColor', 'cv2.cvtColor', (['cv_img', 'cv2.COLOR_BGR2RGB', 'cv_img'], {}), '(cv_img, cv2.COLOR_BGR2RGB, cv_img)\n', (2454, 2489), False, 'import cv2\n'), ((2636, 2651), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (2649, 2651), False, 'import torch\n'), ((3353, 3368), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (3366, 3368), False, 'import torch\n'), ((3664, 3796), 'torch.onnx.export', 'torch.onnx.export', (['self.cls_model', 'img_dry', 'f'], {'verbose': '(False)', 'opset_version': '(11)', 'input_names': "['images']", 'output_names': "['output']"}), "(self.cls_model, img_dry, f, verbose=False, opset_version=\n 11, input_names=['images'], output_names=['output'])\n", (3681, 3796), False, 'import torch\n'), ((3870, 3882), 'onnx.load', 'onnx.load', (['f'], {}), '(f)\n', (3879, 3882), False, 'import onnx\n'), ((3914, 3950), 'onnx.checker.check_model', 'onnx.checker.check_model', (['onnx_model'], {}), '(onnx_model)\n', (3938, 3950), False, 'import onnx\n'), ((4169, 4189), 'onnxsim.simplify', 'simplify', (['onnx_model'], {}), '(onnx_model)\n', (4177, 4189), False, 'from onnxsim import simplify\n'), ((4337, 4362), 'onnx.save', 'onnx.save', (['model_simp', 'f2'], {}), '(model_simp, f2)\n', (4346, 4362), False, 'import onnx\n'), ((4979, 4994), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (4992, 4994), False, 'import torch\n'), ((6498, 6518), 'os.listdir', 'os.listdir', (['root_dir'], {}), '(root_dir)\n', (6508, 6518), False, 'import os\n'), ((6964, 6978), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], {}), '(0)\n', (6975, 6978), False, 'import cv2\n'), ((2961, 2983), 'numpy.max', 'np.max', (['output'], {'axis': '(1)'}), '(output, axis=1)\n', (2967, 2983), True, 'import numpy as np\n'), ((3012, 3037), 'numpy.argmax', 'np.argmax', (['output'], {'axis': '(1)'}), '(output, axis=1)\n', (3021, 3037), True, 'import numpy as np\n'), ((3989, 4034), 'onnx.helper.printable_graph', 'onnx.helper.printable_graph', (['onnx_model.graph'], {}), '(onnx_model.graph)\n', (4016, 4034), False, 'import onnx\n'), ((4596, 4609), 'onnx.load', 'onnx.load', (['f2'], {}), '(f2)\n', (4605, 4609), False, 'import onnx\n'), ((6461, 6480), 'os.path.splitext', 'os.path.splitext', (['x'], {}), '(x)\n', (6477, 6480), False, 'import os\n')] |
import os
import numpy as np
import pytest
from .. import snapshot
from .. import utils
_test_dir = os.path.dirname(__file__)
_data_dir = os.path.join(_test_dir, "testing_data")
def test_load_particle_data():
pd = snapshot.ParticleData(_data_dir+"/snapshot_002.hdf5")
assert pd.n_parts == 64**3
assert pd.box_size == 50.0
assert pd.pos.shape == (64**3, 3)
assert pd.vel.shape == (64**3, 3)
assert pd.ids.shape == (64**3,)
assert pd.OmegaLambda == 0.691
assert pd.OmegaMatter == 0.309
assert pd.h == 0.677
def test_snapshot_tree():
pd = snapshot.ParticleData(_data_dir+"/snapshot_002.hdf5",
load_ids=False, load_vels=False, make_tree=True)
assert np.isclose(pd.tree.boxsize, pd.box_size).all()
# test query_radius with center_box_pbc
inds = pd.query_radius(np.array([0,0,0]), 10)
pos_centered = utils.center_box_pbc(pd.pos[inds], np.array([0,0,0]), pd.box_size)
assert (np.linalg.norm(pos_centered, axis=1) <= 10).all()
exclude = np.delete(pd.pos, inds, axis=0)
pos_centered = utils.center_box_pbc(exclude, np.array([0,0,0]), pd.box_size)
assert (np.linalg.norm(pos_centered, axis=1) > 10).all()
# query_ids should not work when ids are not loaded
with pytest.raises(RuntimeError):
pd.query_ids(np.array([1,2,3]))
def test_load_group_data():
hc = snapshot.HaloCatalog(_data_dir+"/fof_subhalo_tab_002.hdf5")
| [
"numpy.isclose",
"numpy.delete",
"os.path.join",
"os.path.dirname",
"numpy.array",
"pytest.raises",
"numpy.linalg.norm"
] | [((102, 127), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (117, 127), False, 'import os\n'), ((140, 179), 'os.path.join', 'os.path.join', (['_test_dir', '"""testing_data"""'], {}), "(_test_dir, 'testing_data')\n", (152, 179), False, 'import os\n'), ((1011, 1042), 'numpy.delete', 'np.delete', (['pd.pos', 'inds'], {'axis': '(0)'}), '(pd.pos, inds, axis=0)\n', (1020, 1042), True, 'import numpy as np\n'), ((826, 845), 'numpy.array', 'np.array', (['[0, 0, 0]'], {}), '([0, 0, 0])\n', (834, 845), True, 'import numpy as np\n'), ((903, 922), 'numpy.array', 'np.array', (['[0, 0, 0]'], {}), '([0, 0, 0])\n', (911, 922), True, 'import numpy as np\n'), ((1092, 1111), 'numpy.array', 'np.array', (['[0, 0, 0]'], {}), '([0, 0, 0])\n', (1100, 1111), True, 'import numpy as np\n'), ((1250, 1277), 'pytest.raises', 'pytest.raises', (['RuntimeError'], {}), '(RuntimeError)\n', (1263, 1277), False, 'import pytest\n'), ((708, 748), 'numpy.isclose', 'np.isclose', (['pd.tree.boxsize', 'pd.box_size'], {}), '(pd.tree.boxsize, pd.box_size)\n', (718, 748), True, 'import numpy as np\n'), ((1300, 1319), 'numpy.array', 'np.array', (['[1, 2, 3]'], {}), '([1, 2, 3])\n', (1308, 1319), True, 'import numpy as np\n'), ((947, 983), 'numpy.linalg.norm', 'np.linalg.norm', (['pos_centered'], {'axis': '(1)'}), '(pos_centered, axis=1)\n', (961, 983), True, 'import numpy as np\n'), ((1136, 1172), 'numpy.linalg.norm', 'np.linalg.norm', (['pos_centered'], {'axis': '(1)'}), '(pos_centered, axis=1)\n', (1150, 1172), True, 'import numpy as np\n')] |
#script aiming at testing FileListProcessor_input_test
import cv2
import matplotlib.pyplot as plt
import tensorflow as tf
import os
import datetime
import numpy as np
import argparse
import DataProvider_input_pipeline
workingFolder='test_datapipeline'
sessionFolder=os.path.join(workingFolder, datetime.datetime.now().strftime("%Y-%m-%d--%H:%M:%S"))
os.makedirs(sessionFolder)
os.chdir(sessionFolder)
'''first focus on a set of folders with raw ad reference data,
here all data parameters are hard written since all data is supposed to be versionned
'''
#raw_data_dir_train = "../../datasamples/semantic_segmentation/raw_data/"
#reference_data_dir_train = "../../datasamples/semantic_segmentation/labels/"
raw_data_dir_train ="/home/alben/workspace/Datasets/CityScapes/leftImg8bit_trainvaltest/leftImg8bit/train/"
reference_data_dir_train = "/home/alben/workspace/Datasets/CityScapes/gtFine_trainvaltest/gtFine/train/"
nb_classes=34
patchSize=256
patchesPerImage=1000
allow_display=True
process_labels_histogram=False
nan_management='zeros'
parser = argparse.ArgumentParser(description='DataProvider_input_pipeline_test')
parser.add_argument('--avoid-display', dest='avoid_display', action='store_true',
help='avoid display in a Xwindow to let the scrip work on non X systems')
parser.add_argument('--check-data', dest='check_data', action='store_true',
help='If True/1, then iteratively tries to read each image of the dataset to ensure readability')
parser.add_argument('--mode-test', dest='mode_test', action='store_true',
help='Switch from Training mode (random crops by default) to Testing mode (adjacent cropping with overlap)')
parser.add_argument('--mode-labels-count', dest='labels_count', action='store_true',
help='compute class histogram over all the dataset')
parser.add_argument('--data-folder', dest='data_folder', default='',
help='change the data folder from default svn versionned image samples to a specific directory')
parser.add_argument('--field_of_view', dest='field_of_view', default=0,
help='specify the boundary width reduction on the reference data to remove')
parser.add_argument('--write_tfRecords', dest='write_tfRecords', action='store_true',
help='activate tf records writing, to be loaded at full speed for the next training session')
parser.add_argument('--tfRecords_name', dest='tfRecords_name', default='myDataset',
help='specifiy a file name to your tfrecord files, default is myDataset')
parser.add_argument('--read_tfRecords', dest='read_tfRecords', action='store_true',
help='activate tfrecord read test to check what has been writen, what is read next')
processCommands = parser.parse_args()
field_of_view=processCommands.field_of_view
if processCommands.data_folder != '':
print('Testing of specific data folder : '+ processCommands.data_folder)
raw_data_dir_train=processCommands.data_folder
if processCommands.avoid_display:
allow_display = False
if processCommands.labels_count:
process_labels_histogram = True
#get list of filenames
dataset_raw_files=DataProvider_input_pipeline.extractFilenames(raw_data_dir_train, '*.png')
dataset_references_files=DataProvider_input_pipeline.extractFilenames(reference_data_dir_train, '*labelIds.png')
###############################
#prepare dataset input pipeline
isTraining=not(processCommands.mode_test)
def apply_pixel_transforms(isTraining):
if isTraining:
return 0.5
else:
return None
data_provider=DataProvider_input_pipeline.FileListProcessor_Semantic_Segmentation(dataset_raw_files, dataset_references_files,
nbEpoch=1,
shuffle_samples=isTraining,
patch_ratio_vs_input=patchSize,
max_patches_per_image=patchesPerImage,
image_area_coverage_factor=int(isTraining)+1.0,#factor 2 on training, 1 on testing
num_reader_threads=10,#4 threads on training, 1 on testing
apply_random_flip_left_right=isTraining,
apply_random_flip_up_down=False,
apply_random_brightness=apply_pixel_transforms(isTraining),
apply_random_saturation=apply_pixel_transforms(isTraining),
apply_whitening=True,
batch_size=1,
use_alternative_imread='opencv',
balance_classes_distribution=isTraining,
classes_entropy_threshold=0.6,
opencv_read_flags=cv2.IMREAD_UNCHANGED,
field_of_view=field_of_view,
manage_nan_values=nan_management,
additionnal_filters=None,
crops_postprocess=None)
### semantic contours extraction
@tf.function
def get_semantic_contours(reference_crop):
''' deepnet_feed is a 3D tensor (height, width, 1) but
the contour detection expects a batch of mono channel images (batch, height, width)
==> here it then needs a 3D tensor (1, height, width)
'''
print('input batch shape= '+str(reference_crop.get_shape().as_list()))
formatted_reference_crop=tf.squeeze(tf.cast(reference_crop, tf.int32), -1)
contours = DataProvider_input_pipeline.convert_semanticMap_contourMap(formatted_reference_crop)
return contours
#######################################################################
### Optionnal samples recording setup (check here:https://www.tensorflow.org/api_docs/python/tf/io/TFRecordWriter?version=nightly)
def _bytes_feature(value):
"""Returns a bytes_list from a string / byte."""
if isinstance(value, type(tf.constant(0))):
value = value.numpy() # BytesList won't unpack a string from an EagerTensor.
return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))
def _float32_feature_list(value):
"""Returns a float_list from a float / double."""
return tf.train.Feature(float_list=tf.train.FloatList(value=value))
def _int64_feature_scalar(value):
"""Returns an int64_list from a bool / enum / int / uint."""
return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))
# Create a dictionary with features that may be relevant.
def image_example(image_tensor, label=None):
image_shape = image_tensor.shape
print('image_example.shape',image_shape)
feature = {
'height': _int64_feature_scalar(image_shape[0]),
'width': _int64_feature_scalar(image_shape[1]),
'depth': _int64_feature_scalar(image_shape[2]),
'image_raw': _float32_feature_list(image_tensor.numpy().flatten().tolist()),
}
if label is not None:
feature.update({'label': _int64_feature_scalar(label)})
return tf.train.Example(features=tf.train.Features(feature=feature)).SerializeToString()
if processCommands.write_tfRecords:
#setup
file_out = "%s.tfrecords" % processCommands.tfRecords_name
print('Samples will be written as tfrecords in files: ', file_out)
def write_dataset_no_display():
# add serialization node to the dataprovider and write the dataset directly
def serialize_sample(sample):
''' takes as input a tensor, transform to protobuffer and
returns it serialized
'''
return tf.py_function(image_example, [sample[0]], tf.string)
writer = tf.data.experimental.TFRecordWriter(file_out)
print('Writing dataset without display...can be long...')
writer.write(data_provider.dataset.map(serialize_sample))
print('Dataset writing done !')
def read_dataset_display():
if processCommands.write_tfRecords:
writer=tf.io.TFRecordWriter(file_out)
#######################################################################
### Samples extraction loop
class_pixel_counts=np.zeros(nb_classes)
for step, batch in enumerate(data_provider.dataset):
print('====== New step='+str(step))#, 'batch=',batch[0])
sample=batch[0]
if processCommands.write_tfRecords:
sample_proto=image_example(sample)
#print('Serialized sample:', sample_proto)
writer.write(sample_proto)
writer.flush()
reference =sample[:,:,3:].numpy()
class_pixel_counts+=np.array(np.histogram(reference, bins=[-1]+np.linspace(start=0, stop=33, num=34).tolist())[0])
if allow_display is True:
input_crop=sample[:,:,:3].numpy()
contours=get_semantic_contours(tf.expand_dims(sample[:,:,3:],0)).numpy().squeeze(0)
print('input_crop shape =', input_crop.shape)
print('reference_crop shape =', reference.shape)
print('contours_crop shape =', contours.shape)
sample_minVal=np.min(input_crop)
sample_maxVal=np.max(input_crop)
print('Sample value range (min, max)=({minVal}, {maxVal})'.format(minVal=sample_minVal, maxVal=sample_maxVal))
input_crop_norm=(input_crop-sample_minVal)*255.0/(sample_maxVal-sample_minVal)
cv2.imshow('input crop', cv2.cvtColor(input_crop_norm.astype(np.uint8), cv2.COLOR_RGB2BGR))
cv2.imshow('reference crop', reference.astype(np.uint8)*int(255/nb_classes))
cv2.imshow('reference contours_disp', contours.astype(np.uint8)*255)
cv2.waitKey(1000)
if processCommands.write_tfRecords:
writer.close()
if allow_display is True:
print('finished crop sample display, press a key to stop from an active opencv image show window')
cv2.waitKey()
if process_labels_histogram is True:
plt.plot(class_pixel_counts)
plt.title('Class pixels count')
plt.savefig('RS_dataset_Class probabilities.eps')
print('class_pixel_counts', class_pixel_counts)
#DataProvider_input_pipeline.plot_sample_channel_histograms(result, filenameID="last_crop_")
if allow_display is True:
plt.show()
if processCommands.write_tfRecords and processCommands.avoid_display:
write_dataset_no_display()
else:
read_dataset_display()
if processCommands.write_tfRecords and processCommands.read_tfRecords:
print('Attempting to read the writen tfrecords...')
DataProvider_input_pipeline.test_image_tfrecords_dataset(filename=file_out)
print('tfrecord reading done')
print('Test script end')
| [
"tensorflow.train.Int64List",
"tensorflow.cast",
"argparse.ArgumentParser",
"tensorflow.py_function",
"matplotlib.pyplot.plot",
"numpy.max",
"DataProvider_input_pipeline.extractFilenames",
"numpy.linspace",
"tensorflow.train.FloatList",
"numpy.min",
"cv2.waitKey",
"DataProvider_input_pipeline.... | [((352, 378), 'os.makedirs', 'os.makedirs', (['sessionFolder'], {}), '(sessionFolder)\n', (363, 378), False, 'import os\n'), ((379, 402), 'os.chdir', 'os.chdir', (['sessionFolder'], {}), '(sessionFolder)\n', (387, 402), False, 'import os\n'), ((1054, 1125), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""DataProvider_input_pipeline_test"""'}), "(description='DataProvider_input_pipeline_test')\n", (1077, 1125), False, 'import argparse\n'), ((3199, 3272), 'DataProvider_input_pipeline.extractFilenames', 'DataProvider_input_pipeline.extractFilenames', (['raw_data_dir_train', '"""*.png"""'], {}), "(raw_data_dir_train, '*.png')\n", (3243, 3272), False, 'import DataProvider_input_pipeline\n'), ((3298, 3389), 'DataProvider_input_pipeline.extractFilenames', 'DataProvider_input_pipeline.extractFilenames', (['reference_data_dir_train', '"""*labelIds.png"""'], {}), "(reference_data_dir_train,\n '*labelIds.png')\n", (3342, 3389), False, 'import DataProvider_input_pipeline\n'), ((5135, 5224), 'DataProvider_input_pipeline.convert_semanticMap_contourMap', 'DataProvider_input_pipeline.convert_semanticMap_contourMap', (['formatted_reference_crop'], {}), '(\n formatted_reference_crop)\n', (5193, 5224), False, 'import DataProvider_input_pipeline\n'), ((7169, 7214), 'tensorflow.data.experimental.TFRecordWriter', 'tf.data.experimental.TFRecordWriter', (['file_out'], {}), '(file_out)\n', (7204, 7214), True, 'import tensorflow as tf\n'), ((7603, 7623), 'numpy.zeros', 'np.zeros', (['nb_classes'], {}), '(nb_classes)\n', (7611, 7623), True, 'import numpy as np\n'), ((9822, 9897), 'DataProvider_input_pipeline.test_image_tfrecords_dataset', 'DataProvider_input_pipeline.test_image_tfrecords_dataset', ([], {'filename': 'file_out'}), '(filename=file_out)\n', (9878, 9897), False, 'import DataProvider_input_pipeline\n'), ((5081, 5114), 'tensorflow.cast', 'tf.cast', (['reference_crop', 'tf.int32'], {}), '(reference_crop, tf.int32)\n', (5088, 5114), True, 'import tensorflow as tf\n'), ((7103, 7156), 'tensorflow.py_function', 'tf.py_function', (['image_example', '[sample[0]]', 'tf.string'], {}), '(image_example, [sample[0]], tf.string)\n', (7117, 7156), True, 'import tensorflow as tf\n'), ((7447, 7477), 'tensorflow.io.TFRecordWriter', 'tf.io.TFRecordWriter', (['file_out'], {}), '(file_out)\n', (7467, 7477), True, 'import tensorflow as tf\n'), ((9175, 9188), 'cv2.waitKey', 'cv2.waitKey', ([], {}), '()\n', (9186, 9188), False, 'import cv2\n'), ((9234, 9262), 'matplotlib.pyplot.plot', 'plt.plot', (['class_pixel_counts'], {}), '(class_pixel_counts)\n', (9242, 9262), True, 'import matplotlib.pyplot as plt\n'), ((9269, 9300), 'matplotlib.pyplot.title', 'plt.title', (['"""Class pixels count"""'], {}), "('Class pixels count')\n", (9278, 9300), True, 'import matplotlib.pyplot as plt\n'), ((9307, 9356), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""RS_dataset_Class probabilities.eps"""'], {}), "('RS_dataset_Class probabilities.eps')\n", (9318, 9356), True, 'import matplotlib.pyplot as plt\n'), ((296, 319), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (317, 319), False, 'import datetime\n'), ((5550, 5564), 'tensorflow.constant', 'tf.constant', (['(0)'], {}), '(0)\n', (5561, 5564), True, 'import tensorflow as tf\n'), ((5686, 5719), 'tensorflow.train.BytesList', 'tf.train.BytesList', ([], {'value': '[value]'}), '(value=[value])\n', (5704, 5719), True, 'import tensorflow as tf\n'), ((5845, 5876), 'tensorflow.train.FloatList', 'tf.train.FloatList', ([], {'value': 'value'}), '(value=value)\n', (5863, 5876), True, 'import tensorflow as tf\n'), ((6013, 6046), 'tensorflow.train.Int64List', 'tf.train.Int64List', ([], {'value': '[value]'}), '(value=[value])\n', (6031, 6046), True, 'import tensorflow as tf\n'), ((8441, 8459), 'numpy.min', 'np.min', (['input_crop'], {}), '(input_crop)\n', (8447, 8459), True, 'import numpy as np\n'), ((8480, 8498), 'numpy.max', 'np.max', (['input_crop'], {}), '(input_crop)\n', (8486, 8498), True, 'import numpy as np\n'), ((8963, 8980), 'cv2.waitKey', 'cv2.waitKey', (['(1000)'], {}), '(1000)\n', (8974, 8980), False, 'import cv2\n'), ((9552, 9562), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (9560, 9562), True, 'import matplotlib.pyplot as plt\n'), ((6616, 6650), 'tensorflow.train.Features', 'tf.train.Features', ([], {'feature': 'feature'}), '(feature=feature)\n', (6633, 6650), True, 'import tensorflow as tf\n'), ((8208, 8243), 'tensorflow.expand_dims', 'tf.expand_dims', (['sample[:, :, 3:]', '(0)'], {}), '(sample[:, :, 3:], 0)\n', (8222, 8243), True, 'import tensorflow as tf\n'), ((8049, 8086), 'numpy.linspace', 'np.linspace', ([], {'start': '(0)', 'stop': '(33)', 'num': '(34)'}), '(start=0, stop=33, num=34)\n', (8060, 8086), True, 'import numpy as np\n')] |
from astropy.io import fits
from astropy.stats import sigma_clip, sigma_clipped_stats
from astropy.modeling import models, fitting
import numpy as np
from matplotlib import pyplot as plt
from utils import *
from tqdm import tqdm
def find_slit_edges(master_flat_name, edge_cut=50, threshold=20, gap=20, has_primary=False, plot_results=False):
"""
Obtain the slit edges for each detector using a simple thresholding method.
edge_cut: how much to trim off the edges to avoid pesky edge spikes (should be between the edge of the
image and the edge of the slit)
threshold: value that the slit must rise over in order to be deemed a positive hit
plot_results: save a bunch of debugging data to ./pngs/flats/
"""
det_edges = []
det_profiles = []
hw = int(gap / 2) # Halfwidth of gap
with fits.open(master_flat_name) as HDUList:
# Iterate over detectors
if has_primary:
HDUList = HDUList[1:]
for i in range(len(HDUList)):
data = HDUList[i].data
xs, lows, highs = [], [], []
hw = int(gap / 2)
# Now take slices along the wavelength path, get a slit profile, and find the slit edges at each slice
for j in range(hw, len(data[0]) - gap, gap):
data_slice = data[:, j- hw:j + hw]
slit_profile = np.median(data_slice, axis=1)[edge_cut:-edge_cut]
good = np.argwhere(slit_profile[edge_cut:-edge_cut] > threshold)
if len(good) > 0:
low, high = good[0] + 2 * edge_cut, good[-1] + 2 * edge_cut
else:
low, high = 0, data.shape[0]
xs.append(j)
lows.append(int(low))
highs.append(int(high))
xs, lows, highs = np.array(xs), np.array(lows), np.array(highs)
# Use the median for a simple judge of the slit edge
det_edges.append((int(np.median(lows)),
int(np.median(highs))))
# Sigma clip the gathered values, mask, and take a simple linear regression
lows_sc = sigma_clip(lows, masked=True)
xs_low = xs[~lows_sc.mask]
lows = lows[~lows_sc.mask]
# low_line = linregress(xs_low, lows)
low_line = np.polyfit(xs_low, lows, deg=1)
highs_sc = sigma_clip(highs, masked=True)
xs_high = xs[~highs_sc.mask]
highs = highs[~highs_sc.mask]
# high_line = linregress(xs_high, highs)
high_line = np.polyfit(xs_high, highs, deg=1)
det_profiles.append((low_line, high_line))
if plot_results:
check_and_make_dirs(["pngs/flats/"])
fig = plt.figure(figsize=(8, 6), facecolor="white")
plt.plot(slit_profile)
plt.axvline(low - edge_cut, color="black", lw=4, label=low, alpha=0.4)
plt.axvline(high - edge_cut, color="red", lw=4, label=high, alpha=0.4)
plt.title("Det no." + str(i + 1))
plt.legend()
plt.tight_layout()
plt.savefig("pngs/flats/slitprof_" + str(i + 1) + ".png", dpi=200)
fig = plt.figure(figsize=(10, 6), facecolor="white")
quickplot_spectra(data, show=False, make_figure=False)
plt.axhline(low, color="red", ls="dotted")
plt.axhline(high, color="red", ls="dotted")
xs = np.arange(0, data.shape[1])
plt.plot(xs, get_polyfit_line(low_line, xs), color="red")
plt.plot(xs, get_polyfit_line(high_line, xs), color="red")
plt.tight_layout()
plt.savefig("pngs/flats/slits_" + str(i + 1) + ".png", dpi=200)
return det_edges, det_profiles
slit_edges, edge_profiles = find_slit_edges("test_dir/" + "binned_flat_master", threshold=10, gap=100,
plot_results=False)
def find_inner_edges(master_flat_name, edges, threshold=20, gap=20, plot_results=False, plot_individual=False,
has_primary=False,
**kwargs):
"""
Find the inner edges for a frame.
"""
inner_edges, inner_profiles = [], []
hw = int(gap / 2)
gaussian_width = 15
limit_trim = 50
with fits.open(master_flat_name) as HDUList:
if has_primary:
HDUList = HDUList[1:]
for i in tqdm(range(0, len(HDUList)), desc="Determining inner slit profiles"):
data_full = HDUList[i].data
if data_full is None:
continue
this_edge = edges[i]
# Trim data in y, we have the edge data so we will add this back later
data = data_full[this_edge[0] + limit_trim:this_edge[1] - limit_trim, :]
xs, lows, highs = [], [], []
for j in range(hw, len(data[0]) - gap, gap):
# Take slice along wavelength path
data_slice = data[:, j - hw:j + hw]
hh = (int(data_slice.shape[0] / 2))
# Since there are three slices, we will divide into halves
def fit_slice(img_slice):
# Now get the slice profile, and to better fit a Gaussian, subtract
# the median and reverse the profile.
# The guess for x_0 will be halfway along the axis
slice_profile = np.sum(img_slice, axis=1)
slice_profile -= np.median(slice_profile)
slice_profile /= -np.max(np.abs(slice_profile))
# Smooth the profile with a S-G filter to reduce noise interference
slice_profile = smooth(slice_profile, 25)
slice_profile = smooth(slice_profile, 25)
maxguess = np.argmax(slice_profile)
# Now do a gaussian fit, taking the argmax as the guess
# This should capture almost all of it
gaussian = models.Gaussian1D(amplitude=1, mean=maxguess,
stddev=gaussian_width)
gaussian.amplitude.min = 0
fit_gauss = fitting.LevMarLSQFitter()
g = fit_gauss(gaussian, np.arange(0, len(slice_profile)), slice_profile)
slit_centre = int(g.mean.value)
return slit_centre
slice_upper = data_slice[0:hh]
slice_lower = data_slice[hh:]
lower_slice_location = fit_slice(slice_lower) + this_edge[0] + limit_trim + hh
upper_slice_location = fit_slice(slice_upper) + this_edge[0] + limit_trim
xs.append(j)
lows.append(lower_slice_location)
highs.append(upper_slice_location)
if plot_individual:
# fig, ax = plt.subplots(2, 1, facecolor="white")
# ax[0].imshow(np.transpose(slice_1))
# ax[1].scatter(np.arange(len(slice_profile)), slice_profile)
# xs = np.arange(0, len(slice_profile), 0.01)
# ax[1].plot(xs, g(xs), color="red")
# plt.tight_layout()
# plt.savefig("pngs/slit_profiles/good_test_" + str(np.random.randint(1000))
# + ".png")
plt.figure(figsize=(10, 2), facecolor="white")
plt.imshow(np.transpose(data_full[:, j - hw:j + hw]))
plt.axvline(this_edge[0], color="white")
plt.axvline(this_edge[1], color="white")
plt.axvline(upper_slice_location, color="red")
plt.axvline(lower_slice_location, color="orange")
plt.xticks([])
plt.yticks([])
plt.tight_layout()
plt.savefig("pngs/slit_profiles/full_slits_" + str(i) + "_" + str(j) + ".png", dpi=200)
xs, lows, highs = np.array(xs), np.array(lows), np.array(highs)
# Use simple median for the edge estimate
low_guess, high_guess = int(np.median(lows)), int(np.median(highs))
inner_edges.append((high_guess, low_guess))
# Sigma clip the gathered values, mask, and take a simple linear regression
lows_sc = sigma_clip(lows, masked=True)
xs_low = xs[~lows_sc.mask]
lows = lows[~lows_sc.mask]
# low_line = linregress(xs_low, lows)
low_line = np.polyfit(xs_low, lows, deg=1)
highs_sc = sigma_clip(highs, masked=True)
xs_high = xs[~highs_sc.mask]
highs = highs[~highs_sc.mask]
# high_line = linregress(xs_high, highs)
high_line = np.polyfit(xs_high, highs, deg=1)
inner_profiles.append((high_line, low_line))
if plot_results:
xs = np.arange(0, data_full.shape[1])
low_line_obj = np.poly1d(low_line)
high_line_obj = np.poly1d(high_line)
plt.figure(figsize=(10, 6), facecolor="white")
plt.imshow(data_full)
plt.axhline(this_edge[0], color="white")
plt.axhline(this_edge[1], color="white")
plt.plot(xs, low_line_obj(xs), color="red")
plt.plot(xs, high_line_obj(xs), color="orange")
# plt.axhline(low_guess, color="red")
# plt.axhline(high_guess, color="orange")
plt.savefig("pngs/slit_profiles/slits_full_" + str(i) + ".png", dpi=200)
return inner_edges, inner_profiles | [
"numpy.polyfit",
"astropy.modeling.models.Gaussian1D",
"numpy.array",
"astropy.io.fits.open",
"numpy.poly1d",
"numpy.arange",
"matplotlib.pyplot.imshow",
"astropy.stats.sigma_clip",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.axhline",
"matplotlib.pyplot.yticks",
"numpy.abs",
"matplotlib.py... | [((856, 883), 'astropy.io.fits.open', 'fits.open', (['master_flat_name'], {}), '(master_flat_name)\n', (865, 883), False, 'from astropy.io import fits\n'), ((4394, 4421), 'astropy.io.fits.open', 'fits.open', (['master_flat_name'], {}), '(master_flat_name)\n', (4403, 4421), False, 'from astropy.io import fits\n'), ((2173, 2202), 'astropy.stats.sigma_clip', 'sigma_clip', (['lows'], {'masked': '(True)'}), '(lows, masked=True)\n', (2183, 2202), False, 'from astropy.stats import sigma_clip, sigma_clipped_stats\n'), ((2354, 2385), 'numpy.polyfit', 'np.polyfit', (['xs_low', 'lows'], {'deg': '(1)'}), '(xs_low, lows, deg=1)\n', (2364, 2385), True, 'import numpy as np\n'), ((2410, 2440), 'astropy.stats.sigma_clip', 'sigma_clip', (['highs'], {'masked': '(True)'}), '(highs, masked=True)\n', (2420, 2440), False, 'from astropy.stats import sigma_clip, sigma_clipped_stats\n'), ((2601, 2634), 'numpy.polyfit', 'np.polyfit', (['xs_high', 'highs'], {'deg': '(1)'}), '(xs_high, highs, deg=1)\n', (2611, 2634), True, 'import numpy as np\n'), ((8638, 8667), 'astropy.stats.sigma_clip', 'sigma_clip', (['lows'], {'masked': '(True)'}), '(lows, masked=True)\n', (8648, 8667), False, 'from astropy.stats import sigma_clip, sigma_clipped_stats\n'), ((8819, 8850), 'numpy.polyfit', 'np.polyfit', (['xs_low', 'lows'], {'deg': '(1)'}), '(xs_low, lows, deg=1)\n', (8829, 8850), True, 'import numpy as np\n'), ((8875, 8905), 'astropy.stats.sigma_clip', 'sigma_clip', (['highs'], {'masked': '(True)'}), '(highs, masked=True)\n', (8885, 8905), False, 'from astropy.stats import sigma_clip, sigma_clipped_stats\n'), ((9066, 9099), 'numpy.polyfit', 'np.polyfit', (['xs_high', 'highs'], {'deg': '(1)'}), '(xs_high, highs, deg=1)\n', (9076, 9099), True, 'import numpy as np\n'), ((1462, 1519), 'numpy.argwhere', 'np.argwhere', (['(slit_profile[edge_cut:-edge_cut] > threshold)'], {}), '(slit_profile[edge_cut:-edge_cut] > threshold)\n', (1473, 1519), True, 'import numpy as np\n'), ((1844, 1856), 'numpy.array', 'np.array', (['xs'], {}), '(xs)\n', (1852, 1856), True, 'import numpy as np\n'), ((1858, 1872), 'numpy.array', 'np.array', (['lows'], {}), '(lows)\n', (1866, 1872), True, 'import numpy as np\n'), ((1874, 1889), 'numpy.array', 'np.array', (['highs'], {}), '(highs)\n', (1882, 1889), True, 'import numpy as np\n'), ((2797, 2842), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(8, 6)', 'facecolor': '"""white"""'}), "(figsize=(8, 6), facecolor='white')\n", (2807, 2842), True, 'from matplotlib import pyplot as plt\n'), ((2859, 2881), 'matplotlib.pyplot.plot', 'plt.plot', (['slit_profile'], {}), '(slit_profile)\n', (2867, 2881), True, 'from matplotlib import pyplot as plt\n'), ((2898, 2968), 'matplotlib.pyplot.axvline', 'plt.axvline', (['(low - edge_cut)'], {'color': '"""black"""', 'lw': '(4)', 'label': 'low', 'alpha': '(0.4)'}), "(low - edge_cut, color='black', lw=4, label=low, alpha=0.4)\n", (2909, 2968), True, 'from matplotlib import pyplot as plt\n'), ((2985, 3055), 'matplotlib.pyplot.axvline', 'plt.axvline', (['(high - edge_cut)'], {'color': '"""red"""', 'lw': '(4)', 'label': 'high', 'alpha': '(0.4)'}), "(high - edge_cut, color='red', lw=4, label=high, alpha=0.4)\n", (2996, 3055), True, 'from matplotlib import pyplot as plt\n'), ((3122, 3134), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (3132, 3134), True, 'from matplotlib import pyplot as plt\n'), ((3151, 3169), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (3167, 3169), True, 'from matplotlib import pyplot as plt\n'), ((3276, 3322), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(10, 6)', 'facecolor': '"""white"""'}), "(figsize=(10, 6), facecolor='white')\n", (3286, 3322), True, 'from matplotlib import pyplot as plt\n'), ((3410, 3452), 'matplotlib.pyplot.axhline', 'plt.axhline', (['low'], {'color': '"""red"""', 'ls': '"""dotted"""'}), "(low, color='red', ls='dotted')\n", (3421, 3452), True, 'from matplotlib import pyplot as plt\n'), ((3469, 3512), 'matplotlib.pyplot.axhline', 'plt.axhline', (['high'], {'color': '"""red"""', 'ls': '"""dotted"""'}), "(high, color='red', ls='dotted')\n", (3480, 3512), True, 'from matplotlib import pyplot as plt\n'), ((3535, 3562), 'numpy.arange', 'np.arange', (['(0)', 'data.shape[1]'], {}), '(0, data.shape[1])\n', (3544, 3562), True, 'import numpy as np\n'), ((3729, 3747), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (3745, 3747), True, 'from matplotlib import pyplot as plt\n'), ((8290, 8302), 'numpy.array', 'np.array', (['xs'], {}), '(xs)\n', (8298, 8302), True, 'import numpy as np\n'), ((8304, 8318), 'numpy.array', 'np.array', (['lows'], {}), '(lows)\n', (8312, 8318), True, 'import numpy as np\n'), ((8320, 8335), 'numpy.array', 'np.array', (['highs'], {}), '(highs)\n', (8328, 8335), True, 'import numpy as np\n'), ((9209, 9241), 'numpy.arange', 'np.arange', (['(0)', 'data_full.shape[1]'], {}), '(0, data_full.shape[1])\n', (9218, 9241), True, 'import numpy as np\n'), ((9273, 9292), 'numpy.poly1d', 'np.poly1d', (['low_line'], {}), '(low_line)\n', (9282, 9292), True, 'import numpy as np\n'), ((9325, 9345), 'numpy.poly1d', 'np.poly1d', (['high_line'], {}), '(high_line)\n', (9334, 9345), True, 'import numpy as np\n'), ((9363, 9409), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(10, 6)', 'facecolor': '"""white"""'}), "(figsize=(10, 6), facecolor='white')\n", (9373, 9409), True, 'from matplotlib import pyplot as plt\n'), ((9426, 9447), 'matplotlib.pyplot.imshow', 'plt.imshow', (['data_full'], {}), '(data_full)\n', (9436, 9447), True, 'from matplotlib import pyplot as plt\n'), ((9465, 9505), 'matplotlib.pyplot.axhline', 'plt.axhline', (['this_edge[0]'], {'color': '"""white"""'}), "(this_edge[0], color='white')\n", (9476, 9505), True, 'from matplotlib import pyplot as plt\n'), ((9522, 9562), 'matplotlib.pyplot.axhline', 'plt.axhline', (['this_edge[1]'], {'color': '"""white"""'}), "(this_edge[1], color='white')\n", (9533, 9562), True, 'from matplotlib import pyplot as plt\n'), ((1389, 1418), 'numpy.median', 'np.median', (['data_slice'], {'axis': '(1)'}), '(data_slice, axis=1)\n', (1398, 1418), True, 'import numpy as np\n'), ((5512, 5537), 'numpy.sum', 'np.sum', (['img_slice'], {'axis': '(1)'}), '(img_slice, axis=1)\n', (5518, 5537), True, 'import numpy as np\n'), ((5575, 5599), 'numpy.median', 'np.median', (['slice_profile'], {}), '(slice_profile)\n', (5584, 5599), True, 'import numpy as np\n'), ((5913, 5937), 'numpy.argmax', 'np.argmax', (['slice_profile'], {}), '(slice_profile)\n', (5922, 5937), True, 'import numpy as np\n'), ((6105, 6173), 'astropy.modeling.models.Gaussian1D', 'models.Gaussian1D', ([], {'amplitude': '(1)', 'mean': 'maxguess', 'stddev': 'gaussian_width'}), '(amplitude=1, mean=maxguess, stddev=gaussian_width)\n', (6122, 6173), False, 'from astropy.modeling import models, fitting\n'), ((6302, 6327), 'astropy.modeling.fitting.LevMarLSQFitter', 'fitting.LevMarLSQFitter', ([], {}), '()\n', (6325, 6327), False, 'from astropy.modeling import models, fitting\n'), ((7658, 7704), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(10, 2)', 'facecolor': '"""white"""'}), "(figsize=(10, 2), facecolor='white')\n", (7668, 7704), True, 'from matplotlib import pyplot as plt\n'), ((7800, 7840), 'matplotlib.pyplot.axvline', 'plt.axvline', (['this_edge[0]'], {'color': '"""white"""'}), "(this_edge[0], color='white')\n", (7811, 7840), True, 'from matplotlib import pyplot as plt\n'), ((7861, 7901), 'matplotlib.pyplot.axvline', 'plt.axvline', (['this_edge[1]'], {'color': '"""white"""'}), "(this_edge[1], color='white')\n", (7872, 7901), True, 'from matplotlib import pyplot as plt\n'), ((7923, 7969), 'matplotlib.pyplot.axvline', 'plt.axvline', (['upper_slice_location'], {'color': '"""red"""'}), "(upper_slice_location, color='red')\n", (7934, 7969), True, 'from matplotlib import pyplot as plt\n'), ((7990, 8039), 'matplotlib.pyplot.axvline', 'plt.axvline', (['lower_slice_location'], {'color': '"""orange"""'}), "(lower_slice_location, color='orange')\n", (8001, 8039), True, 'from matplotlib import pyplot as plt\n'), ((8061, 8075), 'matplotlib.pyplot.xticks', 'plt.xticks', (['[]'], {}), '([])\n', (8071, 8075), True, 'from matplotlib import pyplot as plt\n'), ((8096, 8110), 'matplotlib.pyplot.yticks', 'plt.yticks', (['[]'], {}), '([])\n', (8106, 8110), True, 'from matplotlib import pyplot as plt\n'), ((8132, 8150), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (8148, 8150), True, 'from matplotlib import pyplot as plt\n'), ((8431, 8446), 'numpy.median', 'np.median', (['lows'], {}), '(lows)\n', (8440, 8446), True, 'import numpy as np\n'), ((8453, 8469), 'numpy.median', 'np.median', (['highs'], {}), '(highs)\n', (8462, 8469), True, 'import numpy as np\n'), ((1990, 2005), 'numpy.median', 'np.median', (['lows'], {}), '(lows)\n', (1999, 2005), True, 'import numpy as np\n'), ((2042, 2058), 'numpy.median', 'np.median', (['highs'], {}), '(highs)\n', (2051, 2058), True, 'import numpy as np\n'), ((7736, 7777), 'numpy.transpose', 'np.transpose', (['data_full[:, j - hw:j + hw]'], {}), '(data_full[:, j - hw:j + hw])\n', (7748, 7777), True, 'import numpy as np\n'), ((5645, 5666), 'numpy.abs', 'np.abs', (['slice_profile'], {}), '(slice_profile)\n', (5651, 5666), True, 'import numpy as np\n')] |
import unittest
import numpy as np
from pysal.lib import cg, examples
import pysal.explore.spaghetti as spgh
class TestNetwork(unittest.TestCase):
def setUp(self):
self.ntw = spgh.Network(in_data=examples.get_path('streets.shp'))
def tearDown(self):
pass
def test_extract_network(self):
self.assertEqual(len(self.ntw.edges), 303)
self.assertEqual(len(self.ntw.nodes), 230)
edgelengths = self.ntw.edge_lengths.values()
self.assertAlmostEqual(sum(edgelengths), 104414.0920159, places=5)
self.assertIn(0, self.ntw.adjacencylist[1])
self.assertIn(0, self.ntw.adjacencylist[2])
self.assertNotIn(0, self.ntw.adjacencylist[3])
def test_contiguity_weights(self):
w = self.ntw.contiguityweights(graph=False)
self.assertEqual(w.n, 303)
self.assertEqual(w.histogram,
[(2, 35), (3, 89), (4, 105), (5, 61), (6, 13)])
def test_contiguity_weights_graph(self):
w = self.ntw.contiguityweights(graph=True)
self.assertEqual(w.n, 179)
self.assertEqual(w.histogram,
[(2, 2), (3, 2), (4, 45), (5, 82), (6, 48)])
def test_distance_band_weights(self):
# I do not trust this result, test should be manually checked.
w = self.ntw.distancebandweights(threshold=500)
self.assertEqual(w.n, 230)
self.assertEqual(w.histogram,
[(1, 22), (2, 58), (3, 63), (4, 40),
(5, 36), (6, 3), (7, 5), (8, 3)])
def test_edge_segmentation(self):
n200 = self.ntw.segment_edges(200.0)
self.assertEqual(len(n200.edges), 688)
n200 = None
def test_enum_links_node(self):
coincident = self.ntw.enum_links_node(24)
self.assertIn((24, 48), coincident)
class TestNetworkPointPattern(unittest.TestCase):
def setUp(self):
self.ntw = spgh.Network(in_data=examples.get_path('streets.shp'))
for obs in ['schools', 'crimes']:
in_data = examples.get_path('{}.shp'.format(obs))
self.ntw.snapobservations(in_data, obs, attribute=True)
setattr(self, obs, self.ntw.pointpatterns[obs])
def tearDown(self):
pass
def test_add_point_pattern(self):
self.assertEqual(self.crimes.npoints, 287)
self.assertIn('properties', self.crimes.points[0])
self.assertIn([1, 1], self.crimes.points[0]['properties'])
def test_count_per_edge(self):
counts = self.ntw.count_per_edge(
self.ntw.pointpatterns['crimes'].obs_to_edge, graph=False)
meancounts = sum(counts.values()) / float(len(counts.keys()))
self.assertAlmostEqual(meancounts, 2.682242, places=5)
def test_count_per_graph_edge(self):
counts = self.ntw.count_per_edge(
self.ntw.pointpatterns['crimes'].obs_to_edge, graph=True)
meancounts = sum(counts.values()) / float(len(counts.keys()))
self.assertAlmostEqual(meancounts, 3.29885, places=5)
def test_simulate_normal_observations(self):
npoints = self.ntw.pointpatterns['crimes'].npoints
sim = self.ntw.simulate_observations(npoints)
self.assertEqual(npoints, sim.npoints)
def test_simulate_poisson_observations(self):
npoints = self.ntw.pointpatterns['crimes'].npoints
sim = self.ntw.simulate_observations(npoints, distribution='poisson')
self.assertEqual(npoints, sim.npoints)
def test_all_neighbor_distances(self):
matrix1, tree = self.ntw.allneighbordistances('schools', gen_tree=True)
known_mtx_val = 17682.436988
known_tree_val = (173, 64)
self.assertAlmostEqual(np.nansum(matrix1[0]), known_mtx_val, places=4)
self.assertEqual(tree[(6, 7)], known_tree_val)
for k, (distances, predlist) in self.ntw.alldistances.items():
self.assertEqual(distances[k], 0)
for p, plists in predlist.items():
self.assertEqual(plists[-1], k)
self.assertEqual(self.ntw.node_list, list(predlist.keys()))
matrix2 = self.ntw.allneighbordistances('schools', fill_diagonal=0.)
observed = matrix2.diagonal()
known = np.zeros(matrix2.shape[0])
self.assertEqual(observed.all(), known.all())
matrix3 = self.ntw.allneighbordistances('schools', snap_dist=True)
known_mtx_val = 3218.2597894
observed_mtx_val = matrix3
self.assertAlmostEqual(observed_mtx_val[0, 1], known_mtx_val, places=4)
def test_nearest_neighbor_distances(self):
# general test
with self.assertRaises(KeyError):
self.ntw.nearestneighbordistances('i_should_not_exist')
nnd1 = self.ntw.nearestneighbordistances('schools')
nnd2 = self.ntw.nearestneighbordistances('schools',
destpattern='schools')
nndv1 = np.array(list(nnd1.values()))[:,1].astype(float)
nndv2 = np.array(list(nnd2.values()))[:,1].astype(float)
np.testing.assert_array_almost_equal_nulp(nndv1, nndv2)
# nearest neighbor keeping zero test
known_zero = ([19], 0.0)[0]
nn_c = self.ntw.nearestneighbordistances('crimes',
keep_zero_dist=True)
self.assertEqual(nn_c[18][0], known_zero)
# nearest neighbor omitting zero test
known_nonzero = ([11], 165.33982412719126)[1]
nn_c = self.ntw.nearestneighbordistances('crimes',
keep_zero_dist=False)
self.assertAlmostEqual(nn_c[18][1], known_nonzero, places=4)
# nearest neighbor with snap distance
known_neigh = ([3], 402.5219673922477)[1]
nn_c = self.ntw.nearestneighbordistances('crimes',
keep_zero_dist=True,
snap_dist=True)
self.assertAlmostEqual(nn_c[0][1], known_neigh, places=4)
class TestNetworkAnalysis(unittest.TestCase):
def setUp(self):
self.ntw = spgh.Network(in_data=examples.get_path('streets.shp'))
pt_str = 'crimes'
in_data = examples.get_path('{}.shp'.format(pt_str))
self.ntw.snapobservations(in_data, pt_str, attribute=True)
npts = self.ntw.pointpatterns['crimes'].npoints
self.ntw.simulate_observations(npts)
def tearDown(self):
pass
def test_network_f(self):
obtained = self.ntw.NetworkF(self.ntw.pointpatterns['crimes'],
permutations=5, nsteps=20)
self.assertEqual(obtained.lowerenvelope.shape[0], 20)
def test_network_g(self):
obtained = self.ntw.NetworkG(self.ntw.pointpatterns['crimes'],
permutations=5, nsteps=20)
self.assertEqual(obtained.lowerenvelope.shape[0], 20)
def test_network_k(self):
obtained = self.ntw.NetworkK(self.ntw.pointpatterns['crimes'],
permutations=5, nsteps=20)
self.assertEqual(obtained.lowerenvelope.shape[0], 20)
class TestNetworkUtils(unittest.TestCase):
def setUp(self):
self.ntw = spgh.Network(in_data=examples.get_path('streets.shp'))
def tearDown(self):
pass
def test_compute_length(self):
self.point1, self.point2 = (0,0), (1,1)
self.length = spgh.util.compute_length( self.point1, self.point2)
self.assertAlmostEqual(self.length, 1.4142135623730951, places=4)
def test_get_neighbor_distances(self):
self.known_neighs = {1: 102.62353453439829, 2: 660.000001049743}
self.neighs = spgh.util.get_neighbor_distances(self.ntw, 0,
self.ntw.edge_lengths)
self.assertAlmostEqual(self.neighs[1], 102.62353453439829, places=4)
self.assertAlmostEqual(self.neighs[2], 660.000001049743, places=4)
def test_generate_tree(self):
self.known_path = [23, 22, 20, 19, 170, 2, 0]
self.distance, self.pred = spgh.util.dijkstra(self.ntw,
self.ntw.edge_lengths,
0)
self.tree = spgh.util.generatetree(self.pred)
self.assertEqual(self.tree[3], self.known_path)
def test_dijkstra(self):
self.distance, self.pred = spgh.dijkstra(self.ntw,
self.ntw.edge_lengths, 0)
self.assertAlmostEqual(self.distance[196], 5505.668247, places=4)
self.assertEqual(self.pred[196], 133)
def test_dijkstra_mp(self):
self.distance, self.pred = spgh.dijkstra_mp((self.ntw,
self.ntw.edge_lengths, 0))
self.assertAlmostEqual(self.distance[196], 5505.668247, places=4)
self.assertEqual(self.pred[196], 133)
def test_square_distance_point_segment(self):
self.point, self.segment = (1,1), ((0,0), (2,0))
self.sqrd_nearp = spgh.util.squared_distance_point_segment(self.point,
self.segment)
self.assertEqual(self.sqrd_nearp[0], 1.0)
self.assertEqual(self.sqrd_nearp[1].all(), np.array([1., 0.]).all())
def test_snap_points_on_segments(self):
self.points = {0: cg.shapes.Point((1,1))}
self.segments = [cg.shapes.Chain([cg.shapes.Point((0,0)),
cg.shapes.Point((2,0))])]
self.snapped = spgh.util.snap_points_on_segments(self.points,
self.segments)
self.known_coords = [xy._Point__loc for xy in self.snapped[0][0]]
self.assertEqual(self.known_coords, [(0.0, 0.0), (2.0, 0.0)])
self.assertEqual(self.snapped[0][1].all(), np.array([1., 0.]).all())
if __name__ == '__main__':
unittest.main()
| [
"pysal.explore.spaghetti.dijkstra",
"pysal.explore.spaghetti.dijkstra_mp",
"pysal.explore.spaghetti.util.snap_points_on_segments",
"pysal.explore.spaghetti.util.generatetree",
"pysal.lib.cg.shapes.Point",
"numpy.testing.assert_array_almost_equal_nulp",
"numpy.zeros",
"numpy.array",
"pysal.explore.sp... | [((10153, 10168), 'unittest.main', 'unittest.main', ([], {}), '()\n', (10166, 10168), False, 'import unittest\n'), ((4329, 4355), 'numpy.zeros', 'np.zeros', (['matrix2.shape[0]'], {}), '(matrix2.shape[0])\n', (4337, 4355), True, 'import numpy as np\n'), ((5161, 5216), 'numpy.testing.assert_array_almost_equal_nulp', 'np.testing.assert_array_almost_equal_nulp', (['nndv1', 'nndv2'], {}), '(nndv1, nndv2)\n', (5202, 5216), True, 'import numpy as np\n'), ((7592, 7642), 'pysal.explore.spaghetti.util.compute_length', 'spgh.util.compute_length', (['self.point1', 'self.point2'], {}), '(self.point1, self.point2)\n', (7616, 7642), True, 'import pysal.explore.spaghetti as spgh\n'), ((7861, 7929), 'pysal.explore.spaghetti.util.get_neighbor_distances', 'spgh.util.get_neighbor_distances', (['self.ntw', '(0)', 'self.ntw.edge_lengths'], {}), '(self.ntw, 0, self.ntw.edge_lengths)\n', (7893, 7929), True, 'import pysal.explore.spaghetti as spgh\n'), ((8265, 8319), 'pysal.explore.spaghetti.util.dijkstra', 'spgh.util.dijkstra', (['self.ntw', 'self.ntw.edge_lengths', '(0)'], {}), '(self.ntw, self.ntw.edge_lengths, 0)\n', (8283, 8319), True, 'import pysal.explore.spaghetti as spgh\n'), ((8448, 8481), 'pysal.explore.spaghetti.util.generatetree', 'spgh.util.generatetree', (['self.pred'], {}), '(self.pred)\n', (8470, 8481), True, 'import pysal.explore.spaghetti as spgh\n'), ((8607, 8656), 'pysal.explore.spaghetti.dijkstra', 'spgh.dijkstra', (['self.ntw', 'self.ntw.edge_lengths', '(0)'], {}), '(self.ntw, self.ntw.edge_lengths, 0)\n', (8620, 8656), True, 'import pysal.explore.spaghetti as spgh\n'), ((8898, 8952), 'pysal.explore.spaghetti.dijkstra_mp', 'spgh.dijkstra_mp', (['(self.ntw, self.ntw.edge_lengths, 0)'], {}), '((self.ntw, self.ntw.edge_lengths, 0))\n', (8914, 8952), True, 'import pysal.explore.spaghetti as spgh\n'), ((9264, 9330), 'pysal.explore.spaghetti.util.squared_distance_point_segment', 'spgh.util.squared_distance_point_segment', (['self.point', 'self.segment'], {}), '(self.point, self.segment)\n', (9304, 9330), True, 'import pysal.explore.spaghetti as spgh\n'), ((9780, 9841), 'pysal.explore.spaghetti.util.snap_points_on_segments', 'spgh.util.snap_points_on_segments', (['self.points', 'self.segments'], {}), '(self.points, self.segments)\n', (9813, 9841), True, 'import pysal.explore.spaghetti as spgh\n'), ((3781, 3802), 'numpy.nansum', 'np.nansum', (['matrix1[0]'], {}), '(matrix1[0])\n', (3790, 3802), True, 'import numpy as np\n'), ((9599, 9622), 'pysal.lib.cg.shapes.Point', 'cg.shapes.Point', (['(1, 1)'], {}), '((1, 1))\n', (9614, 9622), False, 'from pysal.lib import cg, examples\n'), ((215, 247), 'pysal.lib.examples.get_path', 'examples.get_path', (['"""streets.shp"""'], {}), "('streets.shp')\n", (232, 247), False, 'from pysal.lib import cg, examples\n'), ((1984, 2016), 'pysal.lib.examples.get_path', 'examples.get_path', (['"""streets.shp"""'], {}), "('streets.shp')\n", (2001, 2016), False, 'from pysal.lib import cg, examples\n'), ((6272, 6304), 'pysal.lib.examples.get_path', 'examples.get_path', (['"""streets.shp"""'], {}), "('streets.shp')\n", (6289, 6304), False, 'from pysal.lib import cg, examples\n'), ((7406, 7438), 'pysal.lib.examples.get_path', 'examples.get_path', (['"""streets.shp"""'], {}), "('streets.shp')\n", (7423, 7438), False, 'from pysal.lib import cg, examples\n'), ((9498, 9518), 'numpy.array', 'np.array', (['[1.0, 0.0]'], {}), '([1.0, 0.0])\n', (9506, 9518), True, 'import numpy as np\n'), ((9665, 9688), 'pysal.lib.cg.shapes.Point', 'cg.shapes.Point', (['(0, 0)'], {}), '((0, 0))\n', (9680, 9688), False, 'from pysal.lib import cg, examples\n'), ((9731, 9754), 'pysal.lib.cg.shapes.Point', 'cg.shapes.Point', (['(2, 0)'], {}), '((2, 0))\n', (9746, 9754), False, 'from pysal.lib import cg, examples\n'), ((10094, 10114), 'numpy.array', 'np.array', (['[1.0, 0.0]'], {}), '([1.0, 0.0])\n', (10102, 10114), True, 'import numpy as np\n')] |
"""
.. _quadtree_gridded-forecast-evaluation:
Quadtree Grid-based Forecast Evaluation
=======================================
This example demonstrates how to create a quadtree based single resolution-grid and multi-resolution grid.
Multi-resolution grid is created using earthquake catalog, in which seismic density determines the size of a grid cell.
In creating a multi-resolution grid we select a threshold (:math:`N_{max}`) as a maximum number of earthquake in each cell.
In single-resolution grid, we simply select a zoom-level (L) that determines a single resolution grid.
The number of cells in single-resolution grid are equal to :math:`4^L`. The zoom-level L=11 leads to 4.2 million cells, nearest to 0.1x0.1 grid.
We use these grids to create and evaluate a time-independent forecast. Grid-based
forecasts assume the variability of the forecasts is Poissonian. Therefore, poisson-based evaluations
should be used to evaluate grid-based forecasts defined using quadtree regions.
Overview:
1. Define spatial grids
- Multi-resolution grid
- Single-resolution grid
2. Load forecasts
- Multi-resolution forecast
- Single-resolution forecast
3. Load evaluation catalog
4. Apply Poissonian evaluations for both grid-based forecasts
5. Visualize evaluation results
"""
####################################################################################################################################
# Load required libraries
# -----------------------
#
# Most of the core functionality can be imported from the top-level :mod:`csep` package. Utilities are available from the
# :mod:`csep.utils` subpackage.
import numpy
import pandas
from csep.core import poisson_evaluations as poisson
from csep.utils import time_utils, plots
from csep.core.regions import QuadtreeGrid2D
from csep.core.forecasts import GriddedForecast
from csep.utils.time_utils import decimal_year_to_utc_epoch
from csep.core.catalogs import CSEPCatalog
####################################################################################################################################
# Load Training Catalog for Multi-resolution grid
# ----------------------------------------------
#
# We define a multi-resolution quadtree using earthquake catalog. We load a training catalog in CSEP and use that catalog to create a multi-resolution grid.
# Sometimes, we do not the catalog in exact format as requried by pyCSEP. So we can read a catalog using Pandas and convert it
# into the format accepable by PyCSEP. Then we instantiate an object of class CSEPCatalog by calling function :func:`csep.core.regions.CSEPCatalog.from_dataframe`
dfcat = pandas.read_csv('cat_train_2013.csv')
column_name_mapper = {
'lon': 'longitude',
'lat': 'latitude',
'mag': 'magnitude',
'index': 'id'
}
# maps the column names to the dtype expected by the catalog class
dfcat = dfcat.reset_index().rename(columns=column_name_mapper)
# create the origin_times from decimal years
dfcat['origin_time'] = dfcat.apply(lambda row: decimal_year_to_utc_epoch(row.year), axis=1)
# create catalog from dataframe
catalog_train = CSEPCatalog.from_dataframe(dfcat)
print(catalog_train)
####################################################################################################################################
# Define Multi-resolution Gridded Region
# ------------------------------------------------
# Now use define a threshold for maximum number of earthquake allowed per cell, i.e. Nmax
# and call :func:`csep.core.regions.QuadtreeGrid_from_catalog` to create a multi-resolution grid.
# For simplicity we assume only single magnitude bin, i.e. all the earthquakes greater than and equal to 5.95
mbins = numpy.array([5.95])
Nmax = 25
r_multi = QuadtreeGrid2D.from_catalog(catalog_train, Nmax, magnitudes=mbins)
print('Number of cells in Multi-resolution grid :', r_multi.num_nodes)
####################################################################################################################################
# Define Single-resolution Gridded Region
# ----------------------------------------
#
# Here as an example we define a single resolution grid at zoom-level L=6. For this purpose
# we call :func:`csep.core.regions.QuadtreeGrid2D_from_single_resolution` to create a single resolution grid.
# For simplicity of example, we assume only single magnitude bin,
# i.e. all the earthquakes greater than and equal to 5.95
mbins = numpy.array([5.95])
r_single = QuadtreeGrid2D.from_single_resolution(6, magnitudes=mbins)
print('Number of cells in Single-Resolution grid :', r_single.num_nodes)
####################################################################################################################################
# Load forecast of multi-resolution grid
# ---------------------------------
# An example time-independent forecast had been created for this grid and provided the example forecast data set along with the main repository.
# We load the time-independent global forecast which has time horizon of 1 year.
# The filepath is relative to the root directory of the package. You can specify any file location for your forecasts.
forecast_data = numpy.loadtxt('example_rate_zoom=EQ10L11.csv')
#Reshape forecast as Nx1 array
forecast_data = forecast_data.reshape(-1,1)
forecast_multi_grid = GriddedForecast(data = forecast_data, region = r_multi, magnitudes = mbins, name = 'Example Multi-res Forecast')
#The loaded forecast is for 1 year. The test catalog we will use to evaluate is for 6 years. So we can rescale the forecast.
print(f"expected event count before scaling: {forecast_multi_grid.event_count}")
forecast_multi_grid.scale(6)
print(f"expected event count after scaling: {forecast_multi_grid.event_count}")
####################################################################################################################################
# Load forecast of single-resolution grid
# -------------------------------------
# We have already created a time-independent global forecast with time horizon of 1 year and provided with the reporsitory.
# The filepath is relative to the root directory of the package. You can specify any file location for your forecasts.
forecast_data = numpy.loadtxt('example_rate_zoom=6.csv')
#Reshape forecast as Nx1 array
forecast_data = forecast_data.reshape(-1,1)
forecast_single_grid = GriddedForecast(data = forecast_data, region = r_single,
magnitudes = mbins, name = 'Example Single-res Forecast')
# The loaded forecast is for 1 year. The test catalog we will use is for 6 years. So we can rescale the forecast.
print(f"expected event count before scaling: {forecast_single_grid.event_count}")
forecast_single_grid.scale(6)
print(f"expected event count after scaling: {forecast_single_grid.event_count}")
####################################################################################################################################
# Load evaluation catalog
# -----------------------
#
# We have a test catalog stored here. We can read the test catalog as a pandas frame and convert it into a format that is acceptable to PyCSEP
# Then we instantiate an object of catalog
dfcat = pandas.read_csv('cat_test.csv')
column_name_mapper = {
'lon': 'longitude',
'lat': 'latitude',
'mag': 'magnitude'
}
# maps the column names to the dtype expected by the catalog class
dfcat = dfcat.reset_index().rename(columns=column_name_mapper)
# create the origin_times from decimal years
dfcat['origin_time'] = dfcat.apply(lambda row: decimal_year_to_utc_epoch(row.year), axis=1)
# create catalog from dataframe
catalog = CSEPCatalog.from_dataframe(dfcat)
print(catalog)
####################################################################################################################################
# Compute Poisson spatial test and Number test
# ------------------------------------------------------
#
# Simply call the :func:`csep.core.poisson_evaluations.spatial_test` and :func:`csep.core.poisson_evaluations.number_test` functions to evaluate the forecast using the specified
# evaluation catalog. The spatial test requires simulating from the Poisson forecast to provide uncertainty. The verbose
# option prints the status of the simulations to the standard output.
#
# Note: But before we use evaluation catalog, we need to link gridded region with observed catalog.
# Since we have two different grids here, so we do it separately for both grids.
#For Multi-resolution grid, linking region to catalog.
catalog.region = forecast_multi_grid.region
spatial_test_multi_res_result = poisson.spatial_test(forecast_multi_grid, catalog)
number_test_multi_res_result = poisson.number_test(forecast_multi_grid, catalog)
#For Single-resolution grid, linking region to catalog.
catalog.region = forecast_single_grid.region
spatial_test_single_res_result = poisson.spatial_test(forecast_single_grid, catalog)
number_test_single_res_result = poisson.number_test(forecast_single_grid, catalog)
####################################################################################################################################
# Plot spatial test results
# -------------------------
#
# We provide the function :func:`csep.utils.plotting.plot_poisson_consistency_test` to visualize the evaluation results from
# consistency tests.
stest_result = [spatial_test_single_res_result, spatial_test_multi_res_result]
ax_spatial = plots.plot_poisson_consistency_test(stest_result,
plot_args={'xlabel': 'Spatial likelihood'})
ntest_result = [number_test_single_res_result, number_test_multi_res_result]
ax_number = plots.plot_poisson_consistency_test(ntest_result,
plot_args={'xlabel': 'Number of Earthquakes'})
| [
"csep.core.catalogs.CSEPCatalog.from_dataframe",
"pandas.read_csv",
"csep.core.regions.QuadtreeGrid2D.from_catalog",
"csep.utils.time_utils.decimal_year_to_utc_epoch",
"csep.core.forecasts.GriddedForecast",
"numpy.array",
"csep.core.regions.QuadtreeGrid2D.from_single_resolution",
"csep.core.poisson_ev... | [((2674, 2711), 'pandas.read_csv', 'pandas.read_csv', (['"""cat_train_2013.csv"""'], {}), "('cat_train_2013.csv')\n", (2689, 2711), False, 'import pandas\n'), ((3148, 3181), 'csep.core.catalogs.CSEPCatalog.from_dataframe', 'CSEPCatalog.from_dataframe', (['dfcat'], {}), '(dfcat)\n', (3174, 3181), False, 'from csep.core.catalogs import CSEPCatalog\n'), ((3736, 3755), 'numpy.array', 'numpy.array', (['[5.95]'], {}), '([5.95])\n', (3747, 3755), False, 'import numpy\n'), ((3776, 3842), 'csep.core.regions.QuadtreeGrid2D.from_catalog', 'QuadtreeGrid2D.from_catalog', (['catalog_train', 'Nmax'], {'magnitudes': 'mbins'}), '(catalog_train, Nmax, magnitudes=mbins)\n', (3803, 3842), False, 'from csep.core.regions import QuadtreeGrid2D\n'), ((4474, 4493), 'numpy.array', 'numpy.array', (['[5.95]'], {}), '([5.95])\n', (4485, 4493), False, 'import numpy\n'), ((4505, 4563), 'csep.core.regions.QuadtreeGrid2D.from_single_resolution', 'QuadtreeGrid2D.from_single_resolution', (['(6)'], {'magnitudes': 'mbins'}), '(6, magnitudes=mbins)\n', (4542, 4563), False, 'from csep.core.regions import QuadtreeGrid2D\n'), ((5214, 5260), 'numpy.loadtxt', 'numpy.loadtxt', (['"""example_rate_zoom=EQ10L11.csv"""'], {}), "('example_rate_zoom=EQ10L11.csv')\n", (5227, 5260), False, 'import numpy\n'), ((5359, 5468), 'csep.core.forecasts.GriddedForecast', 'GriddedForecast', ([], {'data': 'forecast_data', 'region': 'r_multi', 'magnitudes': 'mbins', 'name': '"""Example Multi-res Forecast"""'}), "(data=forecast_data, region=r_multi, magnitudes=mbins, name=\n 'Example Multi-res Forecast')\n", (5374, 5468), False, 'from csep.core.forecasts import GriddedForecast\n'), ((6273, 6313), 'numpy.loadtxt', 'numpy.loadtxt', (['"""example_rate_zoom=6.csv"""'], {}), "('example_rate_zoom=6.csv')\n", (6286, 6313), False, 'import numpy\n'), ((6413, 6524), 'csep.core.forecasts.GriddedForecast', 'GriddedForecast', ([], {'data': 'forecast_data', 'region': 'r_single', 'magnitudes': 'mbins', 'name': '"""Example Single-res Forecast"""'}), "(data=forecast_data, region=r_single, magnitudes=mbins, name\n ='Example Single-res Forecast')\n", (6428, 6524), False, 'from csep.core.forecasts import GriddedForecast\n'), ((7257, 7288), 'pandas.read_csv', 'pandas.read_csv', (['"""cat_test.csv"""'], {}), "('cat_test.csv')\n", (7272, 7288), False, 'import pandas\n'), ((7700, 7733), 'csep.core.catalogs.CSEPCatalog.from_dataframe', 'CSEPCatalog.from_dataframe', (['dfcat'], {}), '(dfcat)\n', (7726, 7733), False, 'from csep.core.catalogs import CSEPCatalog\n'), ((8675, 8725), 'csep.core.poisson_evaluations.spatial_test', 'poisson.spatial_test', (['forecast_multi_grid', 'catalog'], {}), '(forecast_multi_grid, catalog)\n', (8695, 8725), True, 'from csep.core import poisson_evaluations as poisson\n'), ((8757, 8806), 'csep.core.poisson_evaluations.number_test', 'poisson.number_test', (['forecast_multi_grid', 'catalog'], {}), '(forecast_multi_grid, catalog)\n', (8776, 8806), True, 'from csep.core import poisson_evaluations as poisson\n'), ((8943, 8994), 'csep.core.poisson_evaluations.spatial_test', 'poisson.spatial_test', (['forecast_single_grid', 'catalog'], {}), '(forecast_single_grid, catalog)\n', (8963, 8994), True, 'from csep.core import poisson_evaluations as poisson\n'), ((9027, 9077), 'csep.core.poisson_evaluations.number_test', 'poisson.number_test', (['forecast_single_grid', 'catalog'], {}), '(forecast_single_grid, catalog)\n', (9046, 9077), True, 'from csep.core import poisson_evaluations as poisson\n'), ((9511, 9608), 'csep.utils.plots.plot_poisson_consistency_test', 'plots.plot_poisson_consistency_test', (['stest_result'], {'plot_args': "{'xlabel': 'Spatial likelihood'}"}), "(stest_result, plot_args={'xlabel':\n 'Spatial likelihood'})\n", (9546, 9608), False, 'from csep.utils import time_utils, plots\n'), ((9735, 9835), 'csep.utils.plots.plot_poisson_consistency_test', 'plots.plot_poisson_consistency_test', (['ntest_result'], {'plot_args': "{'xlabel': 'Number of Earthquakes'}"}), "(ntest_result, plot_args={'xlabel':\n 'Number of Earthquakes'})\n", (9770, 9835), False, 'from csep.utils import time_utils, plots\n'), ((3054, 3089), 'csep.utils.time_utils.decimal_year_to_utc_epoch', 'decimal_year_to_utc_epoch', (['row.year'], {}), '(row.year)\n', (3079, 3089), False, 'from csep.utils.time_utils import decimal_year_to_utc_epoch\n'), ((7612, 7647), 'csep.utils.time_utils.decimal_year_to_utc_epoch', 'decimal_year_to_utc_epoch', (['row.year'], {}), '(row.year)\n', (7637, 7647), False, 'from csep.utils.time_utils import decimal_year_to_utc_epoch\n')] |
import numpy as np
import tensorflow as tf
## TensorFlow helper functions
WEIGHT_DECAY_KEY = 'WEIGHT_DECAY'
def _relu(x, leakness=0.0, name=None):
if leakness > 0.0:
name = 'lrelu' if name is None else name
return tf.maximum(x, x*leakness, name='lrelu')
else:
name = 'relu' if name is None else name
return tf.nn.relu(x, name='relu')
def _conv(x, filter_size, out_channel, strides, pad='SAME', input_q=None, output_q=None, name='conv'):
if (input_q == None)^(output_q == None):
raise ValueError('Input/Output splits are not correctly given.')
in_shape = x.get_shape()
with tf.variable_scope(name):
# Main operation: conv2d
with tf.device('/CPU:0'):
kernel = tf.get_variable('kernel', [filter_size, in_shape[2], out_channel],
tf.float32, initializer=tf.random_normal_initializer(
stddev=np.sqrt(2.0/filter_size/out_channel)))
if kernel not in tf.get_collection(WEIGHT_DECAY_KEY):
tf.add_to_collection(WEIGHT_DECAY_KEY, kernel)
# print('\tadded to WEIGHT_DECAY_KEY: %s(%s)' % (kernel.name, str(kernel.get_shape().as_list())))
conv = tf.nn.conv1d(x, kernel, strides, pad)
# Split and split loss
if (input_q is not None) and (output_q is not None):
# w = tf.reduce_mean(kernel, axis=[0, 1])
# w = tf.sqrt(tf.reduce_mean(tf.square(kernel), [0, 1]))
_add_split_loss(kernel, input_q, output_q)
return conv
def _fc(x, out_dim, input_q=None, output_q=None, name='fc'):
if (input_q == None)^(output_q == None):
raise ValueError('Input/Output splits are not correctly given.')
with tf.variable_scope(name):
# Main operation: fc
with tf.device('/CPU:0'):
w = tf.get_variable('weights', [x.get_shape()[1], out_dim],
tf.float32, initializer=tf.random_normal_initializer(
stddev=np.sqrt(1.0/out_dim)))
b = tf.get_variable('biases', [out_dim], tf.float32,
initializer=tf.constant_initializer(0.0))
if w not in tf.get_collection(WEIGHT_DECAY_KEY):
tf.add_to_collection(WEIGHT_DECAY_KEY, w)
# print('\tadded to WEIGHT_DECAY_KEY: %s(%s)' % (w.name, str(w.get_shape().as_list())))
fc = tf.nn.bias_add(tf.matmul(x, w), b)
# Split loss
if (input_q is not None) and (output_q is not None):
_add_split_loss(w, input_q, output_q)
return fc
def _get_split_q(ngroups, dim, name='split', l2_loss=False):
with tf.variable_scope(name):
# alpha = tf.get_variable('alpha', shape=[ngroups, dim], dtype=tf.float32,
# initializer=tf.random_normal_initializer(stddev=0.1))
# q = tf.nn.softmax(alpha, dim=0, name='q')
std_dev = 0.01
init_val = np.random.normal(0, std_dev, (ngroups, dim))
init_val = init_val - np.average(init_val, axis=0) + 1.0/ngroups
with tf.device('/CPU:0'):
q = tf.get_variable('q', shape=[ngroups, dim], dtype=tf.float32,
# initializer=tf.constant_initializer(1.0/ngroups))
initializer=tf.constant_initializer(init_val))
if l2_loss:
if q not in tf.get_collection(WEIGHT_DECAY_KEY):
tf.add_to_collection(WEIGHT_DECAY_KEY, q*2.236)
return q
def _merge_split_q(q, merge_idxs, name='merge'):
assert len(q.get_shape()) == 2
ngroups, dim = q.get_shape().as_list()
assert ngroups == len(merge_idxs)
with tf.variable_scope(name):
max_idx = np.max(merge_idxs)
temp_list = []
for i in range(max_idx + 1):
temp = []
for j in range(ngroups):
if merge_idxs[j] == i:
temp.append(tf.slice(q, [j, 0], [1, dim]))
temp_list.append(tf.add_n(temp))
ret = tf.concat(0, temp_list)
return ret
def _get_even_merge_idxs(N, split):
assert N >= split
num_elems = [(N + split - i - 1)/split for i in range(split)]
expand_split = [[i] * n for i, n in enumerate(num_elems)]
return [t for l in expand_split for t in l]
def _add_split_loss(w, input_q, output_q):
# Check input tensors' measurements
assert len(w.get_shape()) == 2 or len(w.get_shape()) == 4
in_dim, out_dim = w.get_shape().as_list()[-2:]
assert len(input_q.get_shape()) == 2
assert len(output_q.get_shape()) == 2
assert in_dim == input_q.get_shape().as_list()[1]
assert out_dim == output_q.get_shape().as_list()[1]
assert input_q.get_shape().as_list()[0] == output_q.get_shape().as_list()[0] # ngroups
ngroups = input_q.get_shape().as_list()[0]
assert ngroups > 1
# Add split losses to collections
T_list = []
U_list = []
if input_q not in tf.get_collection('OVERLAP_LOSS_WEIGHTS'):
tf.add_to_collection('OVERLAP_LOSS_WEIGHTS', input_q)
print('\t\tAdd overlap & split loss for %s' % input_q.name)
for i in range(ngroups):
for j in range(ngroups):
if i == j:
continue
T_list.append(tf.reduce_sum(input_q[i,:] * input_q[j,:]))
U_list.append(tf.square(tf.reduce_sum(input_q[i,:])))
if output_q not in tf.get_collection('OVERLAP_LOSS_WEIGHTS'):
print('\t\tAdd overlap & split loss for %s' % output_q.name)
tf.add_to_collection('OVERLAP_LOSS_WEIGHTS', output_q)
for i in range(ngroups):
for j in range(ngroups):
if i == j:
continue
T_list.append(tf.reduce_sum(output_q[i,:] * output_q[j,:]))
U_list.append(tf.square(tf.reduce_sum(output_q[i,:])))
if T_list:
tf.add_to_collection('OVERLAP_LOSS', tf.add_n(T_list))
if U_list:
tf.add_to_collection('UNIFORM_LOSS', tf.add_n(U_list))
S_list = []
for i in range(ngroups):
if len(w.get_shape()) == 4:
w_reduce = tf.reduce_mean(tf.square(w), [0, 1])
wg_row = tf.matmul(tf.matmul(tf.diag(tf.square(1 - input_q[i,:])), w_reduce), tf.diag(tf.square(output_q[i,:])))
wg_row_l2 = tf.reduce_sum(tf.sqrt(tf.reduce_sum(wg_row, 1)))
wg_col = tf.matmul(tf.matmul(tf.diag(tf.square(input_q[i,:])), w_reduce), tf.diag(tf.square(1 - output_q[i,:])))
wg_col_l2 = tf.reduce_sum(tf.sqrt(tf.reduce_sum(wg_col, 0)))
else: # len(w.get_shape()) == 2
wg_row = tf.matmul(tf.matmul(tf.diag(1 - input_q[i,:]), w), tf.diag(output_q[i,:]))
wg_row_l2 = tf.reduce_sum(tf.sqrt(tf.reduce_sum(wg_row * wg_row, 1)))
wg_col = tf.matmul(tf.matmul(tf.diag(input_q[i,:]), w), tf.diag(1 - output_q[i,:]))
wg_col_l2 = tf.reduce_sum(tf.sqrt(tf.reduce_sum(wg_col * wg_col, 0)))
S_list.append(wg_row_l2 + wg_col_l2)
S = tf.add_n(S_list)
tf.add_to_collection('WEIGHT_SPLIT', S)
# Add histogram for w if split losses are added
scope_name = tf.get_variable_scope().name
tf.histogram_summary("%s/weights" % scope_name, w)
print('\t\tAdd split loss for %s(%dx%d, %d groups)' \
% (tf.get_variable_scope().name, in_dim, out_dim, ngroups))
return
def _bn_back(x, is_train, global_step=None, moving_average_decay = 0.9, name='bn'):
# moving_average_decay = 0.99
# moving_average_decay_init = 0.99
with tf.variable_scope(name):
decay = moving_average_decay
bn = tf.contrib.layers.batch_norm(inputs=x, decay=decay,
updates_collections=[tf.GraphKeys.UPDATE_OPS], center=True,
scale=True, epsilon=1e-5, is_training=is_train,
trainable=True)
return bn
# def _bn(x, is_train, global_step=None, moving_average_decay = 0.9, name='bn'):
# # moving_average_decay = 0.99
# # moving_average_decay_init = 0.99
# with tf.variable_scope(name):
# decay = moving_average_decay
# batch_mean, batch_var = tf.nn.moments(x, [0, 1, 2])
# with tf.device('/CPU:0'):
# moving_mean = tf.get_variable('mu', batch_mean.get_shape(), tf.float32,
# initializer=tf.zeros_initializer(), trainable=False)
# moving_variance = tf.get_variable('sigma', batch_var.get_shape(), tf.float32,
# initializer=tf.ones_initializer(), trainable=False)
# beta = tf.get_variable('beta', batch_mean.get_shape(), tf.float32,
# initializer=tf.zeros_initializer())
# gamma = tf.get_variable('gamma', batch_var.get_shape(), tf.float32,
# initializer=tf.ones_initializer())
# # BN when training
# update = 1.0 - decay
# if is_train:
# update_moving_mean = moving_mean.assign_sub(update * (moving_mean - batch_mean))
# update_moving_variance = moving_variance.assign_sub(update * (moving_variance - batch_var))
# tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, update_moving_mean)
# tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, update_moving_variance)
#
# batch_mean, batch_var = tf.nn.moments(x,[0,1,2])
# # print(batch_mean.get_shape())
# train_mean = tf.assign(moving_mean, moving_mean * decay + batch_mean * (1-decay))
# train_var = tf.assign(moving_variance, moving_variance * decay + batch_var * (1-decay))
# with tf.control_dependencies([train_mean,train_var]):
# return tf.nn.batch_normalization(x, train_mean, train_var, beta, gamma, 1e-5)
# else:
# return tf.nn.batch_normalization(x, moving_mean, moving_variance, beta, gamma, 1e-5)
# def _bn(inputs, isTrain=True,global_step=None, moving_average_decay = 0.9, name='bn'):
# with tf.variable_scope(name):
#
# batch_size, feature_size,out_batch_size = inputs.get_shape()
# bn_size = 1
# pop_mean = tf.Variable(tf.zeros([bn_size]),trainable=False)
# pop_var = tf.Variable(tf.ones([bn_size]),trainable=False)
# scale = tf.Variable(tf.ones([bn_size]))
# shift = tf.Variable(tf.zeros([bn_size]))
# eps = 0.001
# decay = 0.999
# if isTrain:
# batch_mean, batch_var = tf.nn.moments(inputs,[0,1,2])
# # print(batch_mean.get_shape())
# train_mean = tf.assign(pop_mean, pop_mean * decay + batch_mean * (1-decay))
# train_var = tf.assign(pop_var, pop_var * decay + batch_var * (1-decay))
# with tf.control_dependencies([train_mean,train_var]):
# return tf.nn.batch_normalization(inputs,batch_mean,batch_var,shift,scale,eps)
# else:
# return tf.nn.batch_normalization(inputs,pop_mean,pop_var,shift,scale,eps)
def _bn(x, is_train, global_step=None, moving_average_decay = 0.9, name='bn'):
# moving_average_decay = 0.99
# moving_average_decay_init = 0.99
with tf.variable_scope(name):
decay = moving_average_decay
# if global_step is None:
# decay = moving_average_decay
# else:
# decay = tf.cond(tf.greater(global_step, 100)
# , lambda: tf.constant(moving_average_decay, tf.float32)
# , lambda: tf.constant(moving_average_decay_init, tf.float32))
batch_mean, batch_var = tf.nn.moments(x, [0, 1, 2])
with tf.device('/CPU:0'):
moving_mean = tf.get_variable('mu', batch_mean.get_shape(), tf.float32,
initializer=tf.zeros_initializer(), trainable=False)
moving_variance = tf.get_variable('sigma', batch_var.get_shape(), tf.float32,
initializer=tf.ones_initializer(), trainable=False)
beta = tf.get_variable('beta', batch_mean.get_shape(), tf.float32,
initializer=tf.zeros_initializer())
gamma = tf.get_variable('gamma', batch_var.get_shape(), tf.float32,
initializer=tf.ones_initializer())
# BN when training
update = 1.0 - decay
# with tf.control_dependencies([tf.Print(decay, [decay])]):
# update_moving_mean = moving_mean.assign_sub(update*(moving_mean - batch_mean))
update_moving_mean = moving_mean.assign_sub(update*(moving_mean - batch_mean))
update_moving_variance = moving_variance.assign_sub(update*(moving_variance - batch_var))
tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, update_moving_mean)
tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, update_moving_variance)
mean, var = tf.cond(is_train, lambda: (batch_mean, batch_var),
lambda: (moving_mean, moving_variance),name='bn_cond')
bn = tf.nn.batch_normalization(x, mean, var, beta, gamma, 1e-5)
# bn = tf.nn.batch_normalization(x, batch_mean, batch_var, beta, gamma, 1e-5)
# bn = tf.contrib.layers.batch_norm(inputs=x, decay=decay,
# updates_collections=[tf.GraphKeys.UPDATE_OPS], center=True,
# scale=True, epsilon=1e-5, is_training=is_train,
# trainable=True)
return bn
## Other helper functions
| [
"numpy.sqrt",
"tensorflow.reduce_sum",
"tensorflow.nn.conv1d",
"tensorflow.nn.moments",
"tensorflow.get_variable_scope",
"tensorflow.zeros_initializer",
"tensorflow.slice",
"tensorflow.diag",
"numpy.max",
"tensorflow.concat",
"tensorflow.histogram_summary",
"tensorflow.matmul",
"tensorflow.m... | [((6993, 7009), 'tensorflow.add_n', 'tf.add_n', (['S_list'], {}), '(S_list)\n', (7001, 7009), True, 'import tensorflow as tf\n'), ((7014, 7053), 'tensorflow.add_to_collection', 'tf.add_to_collection', (['"""WEIGHT_SPLIT"""', 'S'], {}), "('WEIGHT_SPLIT', S)\n", (7034, 7053), True, 'import tensorflow as tf\n'), ((7157, 7207), 'tensorflow.histogram_summary', 'tf.histogram_summary', (["('%s/weights' % scope_name)", 'w'], {}), "('%s/weights' % scope_name, w)\n", (7177, 7207), True, 'import tensorflow as tf\n'), ((237, 278), 'tensorflow.maximum', 'tf.maximum', (['x', '(x * leakness)'], {'name': '"""lrelu"""'}), "(x, x * leakness, name='lrelu')\n", (247, 278), True, 'import tensorflow as tf\n'), ((350, 376), 'tensorflow.nn.relu', 'tf.nn.relu', (['x'], {'name': '"""relu"""'}), "(x, name='relu')\n", (360, 376), True, 'import tensorflow as tf\n'), ((639, 662), 'tensorflow.variable_scope', 'tf.variable_scope', (['name'], {}), '(name)\n', (656, 662), True, 'import tensorflow as tf\n'), ((1225, 1262), 'tensorflow.nn.conv1d', 'tf.nn.conv1d', (['x', 'kernel', 'strides', 'pad'], {}), '(x, kernel, strides, pad)\n', (1237, 1262), True, 'import tensorflow as tf\n'), ((1742, 1765), 'tensorflow.variable_scope', 'tf.variable_scope', (['name'], {}), '(name)\n', (1759, 1765), True, 'import tensorflow as tf\n'), ((2664, 2687), 'tensorflow.variable_scope', 'tf.variable_scope', (['name'], {}), '(name)\n', (2681, 2687), True, 'import tensorflow as tf\n'), ((2952, 2996), 'numpy.random.normal', 'np.random.normal', (['(0)', 'std_dev', '(ngroups, dim)'], {}), '(0, std_dev, (ngroups, dim))\n', (2968, 2996), True, 'import numpy as np\n'), ((3679, 3702), 'tensorflow.variable_scope', 'tf.variable_scope', (['name'], {}), '(name)\n', (3696, 3702), True, 'import tensorflow as tf\n'), ((3722, 3740), 'numpy.max', 'np.max', (['merge_idxs'], {}), '(merge_idxs)\n', (3728, 3740), True, 'import numpy as np\n'), ((4021, 4044), 'tensorflow.concat', 'tf.concat', (['(0)', 'temp_list'], {}), '(0, temp_list)\n', (4030, 4044), True, 'import tensorflow as tf\n'), ((4943, 4984), 'tensorflow.get_collection', 'tf.get_collection', (['"""OVERLAP_LOSS_WEIGHTS"""'], {}), "('OVERLAP_LOSS_WEIGHTS')\n", (4960, 4984), True, 'import tensorflow as tf\n'), ((4994, 5047), 'tensorflow.add_to_collection', 'tf.add_to_collection', (['"""OVERLAP_LOSS_WEIGHTS"""', 'input_q'], {}), "('OVERLAP_LOSS_WEIGHTS', input_q)\n", (5014, 5047), True, 'import tensorflow as tf\n'), ((5405, 5446), 'tensorflow.get_collection', 'tf.get_collection', (['"""OVERLAP_LOSS_WEIGHTS"""'], {}), "('OVERLAP_LOSS_WEIGHTS')\n", (5422, 5446), True, 'import tensorflow as tf\n'), ((5525, 5579), 'tensorflow.add_to_collection', 'tf.add_to_collection', (['"""OVERLAP_LOSS_WEIGHTS"""', 'output_q'], {}), "('OVERLAP_LOSS_WEIGHTS', output_q)\n", (5545, 5579), True, 'import tensorflow as tf\n'), ((7124, 7147), 'tensorflow.get_variable_scope', 'tf.get_variable_scope', ([], {}), '()\n', (7145, 7147), True, 'import tensorflow as tf\n'), ((7518, 7541), 'tensorflow.variable_scope', 'tf.variable_scope', (['name'], {}), '(name)\n', (7535, 7541), True, 'import tensorflow as tf\n'), ((7593, 7778), 'tensorflow.contrib.layers.batch_norm', 'tf.contrib.layers.batch_norm', ([], {'inputs': 'x', 'decay': 'decay', 'updates_collections': '[tf.GraphKeys.UPDATE_OPS]', 'center': '(True)', 'scale': '(True)', 'epsilon': '(1e-05)', 'is_training': 'is_train', 'trainable': '(True)'}), '(inputs=x, decay=decay, updates_collections=[tf\n .GraphKeys.UPDATE_OPS], center=True, scale=True, epsilon=1e-05,\n is_training=is_train, trainable=True)\n', (7621, 7778), True, 'import tensorflow as tf\n'), ((11162, 11185), 'tensorflow.variable_scope', 'tf.variable_scope', (['name'], {}), '(name)\n', (11179, 11185), True, 'import tensorflow as tf\n'), ((11586, 11613), 'tensorflow.nn.moments', 'tf.nn.moments', (['x', '[0, 1, 2]'], {}), '(x, [0, 1, 2])\n', (11599, 11613), True, 'import tensorflow as tf\n'), ((12679, 12744), 'tensorflow.add_to_collection', 'tf.add_to_collection', (['tf.GraphKeys.UPDATE_OPS', 'update_moving_mean'], {}), '(tf.GraphKeys.UPDATE_OPS, update_moving_mean)\n', (12699, 12744), True, 'import tensorflow as tf\n'), ((12753, 12822), 'tensorflow.add_to_collection', 'tf.add_to_collection', (['tf.GraphKeys.UPDATE_OPS', 'update_moving_variance'], {}), '(tf.GraphKeys.UPDATE_OPS, update_moving_variance)\n', (12773, 12822), True, 'import tensorflow as tf\n'), ((12844, 12956), 'tensorflow.cond', 'tf.cond', (['is_train', '(lambda : (batch_mean, batch_var))', '(lambda : (moving_mean, moving_variance))'], {'name': '"""bn_cond"""'}), "(is_train, lambda : (batch_mean, batch_var), lambda : (moving_mean,\n moving_variance), name='bn_cond')\n", (12851, 12956), True, 'import tensorflow as tf\n'), ((12991, 13050), 'tensorflow.nn.batch_normalization', 'tf.nn.batch_normalization', (['x', 'mean', 'var', 'beta', 'gamma', '(1e-05)'], {}), '(x, mean, var, beta, gamma, 1e-05)\n', (13016, 13050), True, 'import tensorflow as tf\n'), ((710, 729), 'tensorflow.device', 'tf.device', (['"""/CPU:0"""'], {}), "('/CPU:0')\n", (719, 729), True, 'import tensorflow as tf\n'), ((1004, 1039), 'tensorflow.get_collection', 'tf.get_collection', (['WEIGHT_DECAY_KEY'], {}), '(WEIGHT_DECAY_KEY)\n', (1021, 1039), True, 'import tensorflow as tf\n'), ((1053, 1099), 'tensorflow.add_to_collection', 'tf.add_to_collection', (['WEIGHT_DECAY_KEY', 'kernel'], {}), '(WEIGHT_DECAY_KEY, kernel)\n', (1073, 1099), True, 'import tensorflow as tf\n'), ((1809, 1828), 'tensorflow.device', 'tf.device', (['"""/CPU:0"""'], {}), "('/CPU:0')\n", (1818, 1828), True, 'import tensorflow as tf\n'), ((2205, 2240), 'tensorflow.get_collection', 'tf.get_collection', (['WEIGHT_DECAY_KEY'], {}), '(WEIGHT_DECAY_KEY)\n', (2222, 2240), True, 'import tensorflow as tf\n'), ((2254, 2295), 'tensorflow.add_to_collection', 'tf.add_to_collection', (['WEIGHT_DECAY_KEY', 'w'], {}), '(WEIGHT_DECAY_KEY, w)\n', (2274, 2295), True, 'import tensorflow as tf\n'), ((2424, 2439), 'tensorflow.matmul', 'tf.matmul', (['x', 'w'], {}), '(x, w)\n', (2433, 2439), True, 'import tensorflow as tf\n'), ((3083, 3102), 'tensorflow.device', 'tf.device', (['"""/CPU:0"""'], {}), "('/CPU:0')\n", (3092, 3102), True, 'import tensorflow as tf\n'), ((5909, 5925), 'tensorflow.add_n', 'tf.add_n', (['T_list'], {}), '(T_list)\n', (5917, 5925), True, 'import tensorflow as tf\n'), ((5987, 6003), 'tensorflow.add_n', 'tf.add_n', (['U_list'], {}), '(U_list)\n', (5995, 6003), True, 'import tensorflow as tf\n'), ((11627, 11646), 'tensorflow.device', 'tf.device', (['"""/CPU:0"""'], {}), "('/CPU:0')\n", (11636, 11646), True, 'import tensorflow as tf\n'), ((3027, 3055), 'numpy.average', 'np.average', (['init_val'], {'axis': '(0)'}), '(init_val, axis=0)\n', (3037, 3055), True, 'import numpy as np\n'), ((3388, 3423), 'tensorflow.get_collection', 'tf.get_collection', (['WEIGHT_DECAY_KEY'], {}), '(WEIGHT_DECAY_KEY)\n', (3405, 3423), True, 'import tensorflow as tf\n'), ((3441, 3490), 'tensorflow.add_to_collection', 'tf.add_to_collection', (['WEIGHT_DECAY_KEY', '(q * 2.236)'], {}), '(WEIGHT_DECAY_KEY, q * 2.236)\n', (3461, 3490), True, 'import tensorflow as tf\n'), ((3991, 4005), 'tensorflow.add_n', 'tf.add_n', (['temp'], {}), '(temp)\n', (3999, 4005), True, 'import tensorflow as tf\n'), ((6125, 6137), 'tensorflow.square', 'tf.square', (['w'], {}), '(w)\n', (6134, 6137), True, 'import tensorflow as tf\n'), ((6656, 6679), 'tensorflow.diag', 'tf.diag', (['output_q[i, :]'], {}), '(output_q[i, :])\n', (6663, 6679), True, 'import tensorflow as tf\n'), ((6830, 6857), 'tensorflow.diag', 'tf.diag', (['(1 - output_q[i, :])'], {}), '(1 - output_q[i, :])\n', (6837, 6857), True, 'import tensorflow as tf\n'), ((2155, 2183), 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0.0)'], {}), '(0.0)\n', (2178, 2183), True, 'import tensorflow as tf\n'), ((3309, 3342), 'tensorflow.constant_initializer', 'tf.constant_initializer', (['init_val'], {}), '(init_val)\n', (3332, 3342), True, 'import tensorflow as tf\n'), ((5272, 5316), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['(input_q[i, :] * input_q[j, :])'], {}), '(input_q[i, :] * input_q[j, :])\n', (5285, 5316), True, 'import tensorflow as tf\n'), ((5352, 5380), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['input_q[i, :]'], {}), '(input_q[i, :])\n', (5365, 5380), True, 'import tensorflow as tf\n'), ((5736, 5782), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['(output_q[i, :] * output_q[j, :])'], {}), '(output_q[i, :] * output_q[j, :])\n', (5749, 5782), True, 'import tensorflow as tf\n'), ((5818, 5847), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['output_q[i, :]'], {}), '(output_q[i, :])\n', (5831, 5847), True, 'import tensorflow as tf\n'), ((6245, 6270), 'tensorflow.square', 'tf.square', (['output_q[i, :]'], {}), '(output_q[i, :])\n', (6254, 6270), True, 'import tensorflow as tf\n'), ((6318, 6342), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['wg_row', '(1)'], {}), '(wg_row, 1)\n', (6331, 6342), True, 'import tensorflow as tf\n'), ((6439, 6468), 'tensorflow.square', 'tf.square', (['(1 - output_q[i, :])'], {}), '(1 - output_q[i, :])\n', (6448, 6468), True, 'import tensorflow as tf\n'), ((6516, 6540), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['wg_col', '(0)'], {}), '(wg_col, 0)\n', (6529, 6540), True, 'import tensorflow as tf\n'), ((6625, 6651), 'tensorflow.diag', 'tf.diag', (['(1 - input_q[i, :])'], {}), '(1 - input_q[i, :])\n', (6632, 6651), True, 'import tensorflow as tf\n'), ((6726, 6759), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['(wg_row * wg_row)', '(1)'], {}), '(wg_row * wg_row, 1)\n', (6739, 6759), True, 'import tensorflow as tf\n'), ((6803, 6825), 'tensorflow.diag', 'tf.diag', (['input_q[i, :]'], {}), '(input_q[i, :])\n', (6810, 6825), True, 'import tensorflow as tf\n'), ((6904, 6937), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['(wg_col * wg_col)', '(0)'], {}), '(wg_col * wg_col, 0)\n', (6917, 6937), True, 'import tensorflow as tf\n'), ((7279, 7302), 'tensorflow.get_variable_scope', 'tf.get_variable_scope', ([], {}), '()\n', (7300, 7302), True, 'import tensorflow as tf\n'), ((11772, 11794), 'tensorflow.zeros_initializer', 'tf.zeros_initializer', ([], {}), '()\n', (11792, 11794), True, 'import tensorflow as tf\n'), ((11943, 11964), 'tensorflow.ones_initializer', 'tf.ones_initializer', ([], {}), '()\n', (11962, 11964), True, 'import tensorflow as tf\n'), ((12102, 12124), 'tensorflow.zeros_initializer', 'tf.zeros_initializer', ([], {}), '()\n', (12122, 12124), True, 'import tensorflow as tf\n'), ((12246, 12267), 'tensorflow.ones_initializer', 'tf.ones_initializer', ([], {}), '()\n', (12265, 12267), True, 'import tensorflow as tf\n'), ((3931, 3960), 'tensorflow.slice', 'tf.slice', (['q', '[j, 0]', '[1, dim]'], {}), '(q, [j, 0], [1, dim])\n', (3939, 3960), True, 'import tensorflow as tf\n'), ((6196, 6224), 'tensorflow.square', 'tf.square', (['(1 - input_q[i, :])'], {}), '(1 - input_q[i, :])\n', (6205, 6224), True, 'import tensorflow as tf\n'), ((6394, 6418), 'tensorflow.square', 'tf.square', (['input_q[i, :]'], {}), '(input_q[i, :])\n', (6403, 6418), True, 'import tensorflow as tf\n'), ((940, 980), 'numpy.sqrt', 'np.sqrt', (['(2.0 / filter_size / out_channel)'], {}), '(2.0 / filter_size / out_channel)\n', (947, 980), True, 'import numpy as np\n'), ((2023, 2045), 'numpy.sqrt', 'np.sqrt', (['(1.0 / out_dim)'], {}), '(1.0 / out_dim)\n', (2030, 2045), True, 'import numpy as np\n')] |
# Electron ID [DEEP TRAINING] steering code
#
# <NAME>, 2020
# <EMAIL>
# icenet system paths
import _icepaths_
import uproot
import math
import numpy as np
import torch
import argparse
import pprint
import os
import datetime
import json
import pickle
import sys
import yaml
import copy
#import graphviz
import torch_geometric
from termcolor import cprint
# matplotlib
from matplotlib import pyplot as plt
# scikit
from sklearn import metrics
from sklearn.metrics import accuracy_score
# icenet
from icenet.tools import io
from icenet.tools import aux
from icenet.tools import plots
from icenet.tools import prints
# deep learning
from icenet.deep import train
import icenet.deep as deep
# iceid
from iceid import common
from iceid import graphio
def get_model(X, Y, VARS, features, args, param):
# ---------------------------------------------------------------
# Read test graph data to get dimensions
gdata = {}
gdata['trn'] = graphio.parse_graph_data(X=X[0:100], Y=Y[0:100], VARS=VARS,
features=features, global_on=args['graph_param']['global_on'], coord=args['graph_param']['coord'])
# =========================================================================
# INITIALIZE GRAPH MODEL
num_classes = 2
num_node_features = gdata['trn'][0].x.size(-1)
num_edge_features = gdata['trn'][0].edge_attr.size(-1)
num_global_features = len(gdata['trn'][0].u)
conv_type = param['conv_type']
netparam = {
'C' : num_classes,
'D' : num_node_features,
'E' : num_edge_features,
'G' : num_global_features,
'conv_aggr' : param['conv_aggr'],
'global_pool': param['global_pool'],
'task' : 'graph'
}
if conv_type == 'GAT':
model = deep.graph.GATNet(**netparam)
elif conv_type == 'DEC':
model = deep.graph.DECNet(**netparam)
elif conv_type == 'EC':
model = deep.graph.ECNet(**netparam)
elif conv_type == 'SUP':
model = deep.graph.SUPNet(**netparam)
elif conv_type == 'SG':
model = deep.graph.SGNet(**netparam)
elif conv_type == 'SAGE':
model = deep.graph.SAGENet(**netparam)
elif conv_type == 'NN':
model = deep.graph.NNNet(**netparam)
elif conv_type == 'GINE':
model = deep.graph.GINENet(**netparam)
elif conv_type == 'spline':
model = deep.graph.SplineNet(**netparam)
else:
raise Except(name__ + f'.graph_train: Unknown network convolution model "conv_type" = {conv_type}')
# CPU or GPU
model, device = deep.dopt.model_to_cuda(model=model, device_type=param['device'])
# Count the number of parameters
model_parameters = filter(lambda p: p.requires_grad, model.parameters())
params = sum([np.prod(p.size()) for p in model_parameters])
cprint(__name__ + f'.graph_train: Number of free parameters = {params}', 'yellow')
# Create optimizer
optimizer = torch.optim.Adam(model.parameters(), lr=param['learning_rate'], weight_decay=param['weight_decay'])
scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=param['step_size'], gamma=param['gamma'])
return model, device, optimizer, scheduler
# Main function
#
def main():
### Get input
args, cli, features = common.read_config()
### Load data (ONLY ONE FILE SUPPORTED FOR NOW)
root_path = cli.datapath + '/output_' + str(cli.datasets[0]) + '.root'
file = uproot.open(root_path)
EVENTS = file["ntuplizer"]["tree"].numentries
file.close()
# =========================================================================
# LOAD DATA
X,Y,VARS = common.load_root_file_new(root_path, entrystart=0, entrystop=args['reweight_param']['maxevents'], args=args)
### Compute differential re-weighting 2D-PDFs
PT = X[:, VARS.index('trk_pt')]
ETA = X[:, VARS.index('trk_eta')]
bins_pt = args['reweight_param']['bins_pt']
bins_eta = args['reweight_param']['bins_eta']
pt_binedges = np.linspace(bins_pt[0], bins_pt[1], bins_pt[2])
eta_binedges = np.linspace(bins_eta[0], bins_eta[1], bins_eta[2])
print(__name__ + f".compute_reweights: reference_class: <{args['reweight_param']['reference_class']}>")
### Compute 2D-pdfs for each class
N_class = 2
pdf = {}
for c in range(N_class):
pdf[c] = aux.pdf_2D_hist(X_A=PT[Y==c], X_B=ETA[Y==c], binedges_A=pt_binedges, binedges_B=eta_binedges)
pdf['binedges_A'] = pt_binedges
pdf['binedges_B'] = eta_binedges
# ----------------------------------------------------------
### Initialize all models
model = {}
device = {}
optimizer = {}
scheduler = {}
param = {}
for i in range(len(args['active_models'])):
ID = args['active_models'][i]
param[ID] = args[f'{ID}_param']
print(f'Training <{ID}> | {param[ID]} \n')
model[ID], device[ID], optimizer[ID], scheduler[ID] = \
get_model(X=X,Y=Y,VARS=VARS,features=features,args=args,param=param[ID])
# ----------------------------------------------------------
### EPOCH LOOP HERE
block_size = args['blocksize']
N_blocks = int(np.ceil(EVENTS / args['blocksize']))
block_ind = aux.split_start_end(range(EVENTS), N_blocks)
# Over blocks of data
for block in range(N_blocks):
entrystart = block_ind[block][0]
entrystop = block_ind[block][-1]
print(__name__ + f'.block {block+1} / {N_blocks} \n\n\n\n')
# =========================================================================
# LOAD DATA
X,Y,VARS = common.load_root_file_new(root_path, entrystart=entrystart, entrystop=entrystop, args=args)
trn, val, tst = io.split_data(X=X, Y=Y, frac=args['frac'], rngseed=args['rngseed'])
# =========================================================================
# COMPUTE RE-WEIGHTS
# Re-weighting variables
PT = trn.x[:, VARS.index('trk_pt')]
ETA = trn.x[:, VARS.index('trk_eta')]
# Compute event-by-event weights
if args['reweight_param']['reference_class'] != -1:
trn_weights = aux.reweightcoeff2D(
X_A = PT, X_B = ETA, pdf = pdf, y = trn.y, N_class=N_class,
equal_frac = args['reweight_param']['equal_frac'],
reference_class = args['reweight_param']['reference_class'],
max_reg = args['reweight_param']['max_reg'])
else:
# No re-weighting
weights_doublet = np.zeros((trn.x.shape[0], N_class))
for c in range(N_class):
weights_doublet[trn.y == c, c] = 1
trn_weights = np.sum(weights_doublet, axis=1)
# Compute the sum of weights per class for the output print
frac = np.zeros(N_class)
sums = np.zeros(N_class)
for c in range(N_class):
frac[c] = np.sum(trn.y == c)
sums[c] = np.sum(trn_weights[trn.y == c])
print(__name__ + f'.compute_reweights: sum(Y==c): {frac}')
print(__name__ + f'.compute_reweights: sum(trn_weights[Y==c]): {sums}')
print(__name__ + f'.compute_reweights: [done]\n')
# =========================================================================
### Parse data into graphs
gdata = {}
gdata['trn'] = graphio.parse_graph_data(X=trn.x, Y=trn.y, VARS=VARS,
features=features, global_on=args['graph_param']['global_on'], coord=args['graph_param']['coord'])
gdata['val'] = graphio.parse_graph_data(X=val.x, Y=val.y, VARS=VARS,
features=features, global_on=args['graph_param']['global_on'], coord=args['graph_param']['coord'])
# =========================================================================
### Train all model over this block of data
for ID in model.keys():
print(__name__ + f' Training model <{ID}>')
train_loader = torch_geometric.data.DataLoader(gdata['trn'], batch_size=param[ID]['batch_size'], shuffle=True)
test_loader = torch_geometric.data.DataLoader(gdata['val'], batch_size=512, shuffle=False)
for epoch in range(param[ID]['epochs']):
loss = deep.graph.train(model=model[ID], loader=train_loader, optimizer=optimizer[ID], device=device[ID])
validate_acc, validate_AUC = deep.graph.test( model=model[ID], loader=test_loader, optimizer=optimizer[ID], device=device[ID])
scheduler[ID].step()
print(f'block {block+1:03d} [epoch: {epoch:03d}] train loss: {loss:.4f} | validate: {validate_acc:.4f} (acc), {validate_AUC:.4f} (AUC) | learning_rate = {scheduler[ID].get_last_lr()}')
## Save
args["modeldir"] = f'./checkpoint/eid/{args["config"]}/'; os.makedirs(args["modeldir"], exist_ok = True)
checkpoint = {'model': model[ID], 'state_dict': model[ID].state_dict()}
torch.save(checkpoint, args['modeldir'] + f'/{param[ID]["label"]}_checkpoint' + '.pth')
if __name__ == '__main__' :
main()
| [
"iceid.common.read_config",
"icenet.deep.dopt.model_to_cuda",
"icenet.deep.graph.GINENet",
"icenet.tools.aux.pdf_2D_hist",
"numpy.linspace",
"uproot.open",
"icenet.deep.graph.DECNet",
"numpy.ceil",
"icenet.deep.graph.ECNet",
"icenet.deep.graph.SUPNet",
"icenet.deep.graph.SAGENet",
"icenet.deep... | [((967, 1135), 'iceid.graphio.parse_graph_data', 'graphio.parse_graph_data', ([], {'X': 'X[0:100]', 'Y': 'Y[0:100]', 'VARS': 'VARS', 'features': 'features', 'global_on': "args['graph_param']['global_on']", 'coord': "args['graph_param']['coord']"}), "(X=X[0:100], Y=Y[0:100], VARS=VARS, features=\n features, global_on=args['graph_param']['global_on'], coord=args[\n 'graph_param']['coord'])\n", (991, 1135), False, 'from iceid import graphio\n'), ((2626, 2691), 'icenet.deep.dopt.model_to_cuda', 'deep.dopt.model_to_cuda', ([], {'model': 'model', 'device_type': "param['device']"}), "(model=model, device_type=param['device'])\n", (2649, 2691), True, 'import icenet.deep as deep\n'), ((2875, 2961), 'termcolor.cprint', 'cprint', (["(__name__ + f'.graph_train: Number of free parameters = {params}')", '"""yellow"""'], {}), "(__name__ + f'.graph_train: Number of free parameters = {params}',\n 'yellow')\n", (2881, 2961), False, 'from termcolor import cprint\n'), ((3118, 3216), 'torch.optim.lr_scheduler.StepLR', 'torch.optim.lr_scheduler.StepLR', (['optimizer'], {'step_size': "param['step_size']", 'gamma': "param['gamma']"}), "(optimizer, step_size=param['step_size'],\n gamma=param['gamma'])\n", (3149, 3216), False, 'import torch\n'), ((3338, 3358), 'iceid.common.read_config', 'common.read_config', ([], {}), '()\n', (3356, 3358), False, 'from iceid import common\n'), ((3501, 3523), 'uproot.open', 'uproot.open', (['root_path'], {}), '(root_path)\n', (3512, 3523), False, 'import uproot\n'), ((3712, 3825), 'iceid.common.load_root_file_new', 'common.load_root_file_new', (['root_path'], {'entrystart': '(0)', 'entrystop': "args['reweight_param']['maxevents']", 'args': 'args'}), "(root_path, entrystart=0, entrystop=args[\n 'reweight_param']['maxevents'], args=args)\n", (3737, 3825), False, 'from iceid import common\n'), ((4093, 4140), 'numpy.linspace', 'np.linspace', (['bins_pt[0]', 'bins_pt[1]', 'bins_pt[2]'], {}), '(bins_pt[0], bins_pt[1], bins_pt[2])\n', (4104, 4140), True, 'import numpy as np\n'), ((4160, 4210), 'numpy.linspace', 'np.linspace', (['bins_eta[0]', 'bins_eta[1]', 'bins_eta[2]'], {}), '(bins_eta[0], bins_eta[1], bins_eta[2])\n', (4171, 4210), True, 'import numpy as np\n'), ((1836, 1865), 'icenet.deep.graph.GATNet', 'deep.graph.GATNet', ([], {}), '(**netparam)\n', (1853, 1865), True, 'import icenet.deep as deep\n'), ((4443, 4544), 'icenet.tools.aux.pdf_2D_hist', 'aux.pdf_2D_hist', ([], {'X_A': 'PT[Y == c]', 'X_B': 'ETA[Y == c]', 'binedges_A': 'pt_binedges', 'binedges_B': 'eta_binedges'}), '(X_A=PT[Y == c], X_B=ETA[Y == c], binedges_A=pt_binedges,\n binedges_B=eta_binedges)\n', (4458, 4544), False, 'from icenet.tools import aux\n'), ((5283, 5318), 'numpy.ceil', 'np.ceil', (["(EVENTS / args['blocksize'])"], {}), "(EVENTS / args['blocksize'])\n", (5290, 5318), True, 'import numpy as np\n'), ((5746, 5842), 'iceid.common.load_root_file_new', 'common.load_root_file_new', (['root_path'], {'entrystart': 'entrystart', 'entrystop': 'entrystop', 'args': 'args'}), '(root_path, entrystart=entrystart, entrystop=\n entrystop, args=args)\n', (5771, 5842), False, 'from iceid import common\n'), ((5862, 5929), 'icenet.tools.io.split_data', 'io.split_data', ([], {'X': 'X', 'Y': 'Y', 'frac': "args['frac']", 'rngseed': "args['rngseed']"}), "(X=X, Y=Y, frac=args['frac'], rngseed=args['rngseed'])\n", (5875, 5929), False, 'from icenet.tools import io\n'), ((6976, 6993), 'numpy.zeros', 'np.zeros', (['N_class'], {}), '(N_class)\n', (6984, 6993), True, 'import numpy as np\n'), ((7009, 7026), 'numpy.zeros', 'np.zeros', (['N_class'], {}), '(N_class)\n', (7017, 7026), True, 'import numpy as np\n'), ((7532, 7693), 'iceid.graphio.parse_graph_data', 'graphio.parse_graph_data', ([], {'X': 'trn.x', 'Y': 'trn.y', 'VARS': 'VARS', 'features': 'features', 'global_on': "args['graph_param']['global_on']", 'coord': "args['graph_param']['coord']"}), "(X=trn.x, Y=trn.y, VARS=VARS, features=features,\n global_on=args['graph_param']['global_on'], coord=args['graph_param'][\n 'coord'])\n", (7556, 7693), False, 'from iceid import graphio\n'), ((7721, 7882), 'iceid.graphio.parse_graph_data', 'graphio.parse_graph_data', ([], {'X': 'val.x', 'Y': 'val.y', 'VARS': 'VARS', 'features': 'features', 'global_on': "args['graph_param']['global_on']", 'coord': "args['graph_param']['coord']"}), "(X=val.x, Y=val.y, VARS=VARS, features=features,\n global_on=args['graph_param']['global_on'], coord=args['graph_param'][\n 'coord'])\n", (7745, 7882), False, 'from iceid import graphio\n'), ((1911, 1940), 'icenet.deep.graph.DECNet', 'deep.graph.DECNet', ([], {}), '(**netparam)\n', (1928, 1940), True, 'import icenet.deep as deep\n'), ((6314, 6550), 'icenet.tools.aux.reweightcoeff2D', 'aux.reweightcoeff2D', ([], {'X_A': 'PT', 'X_B': 'ETA', 'pdf': 'pdf', 'y': 'trn.y', 'N_class': 'N_class', 'equal_frac': "args['reweight_param']['equal_frac']", 'reference_class': "args['reweight_param']['reference_class']", 'max_reg': "args['reweight_param']['max_reg']"}), "(X_A=PT, X_B=ETA, pdf=pdf, y=trn.y, N_class=N_class,\n equal_frac=args['reweight_param']['equal_frac'], reference_class=args[\n 'reweight_param']['reference_class'], max_reg=args['reweight_param'][\n 'max_reg'])\n", (6333, 6550), False, 'from icenet.tools import aux\n'), ((6706, 6741), 'numpy.zeros', 'np.zeros', (['(trn.x.shape[0], N_class)'], {}), '((trn.x.shape[0], N_class))\n', (6714, 6741), True, 'import numpy as np\n'), ((6860, 6891), 'numpy.sum', 'np.sum', (['weights_doublet'], {'axis': '(1)'}), '(weights_doublet, axis=1)\n', (6866, 6891), True, 'import numpy as np\n'), ((7082, 7100), 'numpy.sum', 'np.sum', (['(trn.y == c)'], {}), '(trn.y == c)\n', (7088, 7100), True, 'import numpy as np\n'), ((7123, 7154), 'numpy.sum', 'np.sum', (['trn_weights[trn.y == c]'], {}), '(trn_weights[trn.y == c])\n', (7129, 7154), True, 'import numpy as np\n'), ((8139, 8239), 'torch_geometric.data.DataLoader', 'torch_geometric.data.DataLoader', (["gdata['trn']"], {'batch_size': "param[ID]['batch_size']", 'shuffle': '(True)'}), "(gdata['trn'], batch_size=param[ID][\n 'batch_size'], shuffle=True)\n", (8170, 8239), False, 'import torch_geometric\n'), ((8262, 8338), 'torch_geometric.data.DataLoader', 'torch_geometric.data.DataLoader', (["gdata['val']"], {'batch_size': '(512)', 'shuffle': '(False)'}), "(gdata['val'], batch_size=512, shuffle=False)\n", (8293, 8338), False, 'import torch_geometric\n'), ((9041, 9085), 'os.makedirs', 'os.makedirs', (["args['modeldir']"], {'exist_ok': '(True)'}), "(args['modeldir'], exist_ok=True)\n", (9052, 9085), False, 'import os\n'), ((9184, 9275), 'torch.save', 'torch.save', (['checkpoint', '(args[\'modeldir\'] + f"/{param[ID][\'label\']}_checkpoint" + \'.pth\')'], {}), '(checkpoint, args[\'modeldir\'] +\n f"/{param[ID][\'label\']}_checkpoint" + \'.pth\')\n', (9194, 9275), False, 'import torch\n'), ((1985, 2013), 'icenet.deep.graph.ECNet', 'deep.graph.ECNet', ([], {}), '(**netparam)\n', (2001, 2013), True, 'import icenet.deep as deep\n'), ((8439, 8542), 'icenet.deep.graph.train', 'deep.graph.train', ([], {'model': 'model[ID]', 'loader': 'train_loader', 'optimizer': 'optimizer[ID]', 'device': 'device[ID]'}), '(model=model[ID], loader=train_loader, optimizer=optimizer[\n ID], device=device[ID])\n', (8455, 8542), True, 'import icenet.deep as deep\n'), ((8583, 8684), 'icenet.deep.graph.test', 'deep.graph.test', ([], {'model': 'model[ID]', 'loader': 'test_loader', 'optimizer': 'optimizer[ID]', 'device': 'device[ID]'}), '(model=model[ID], loader=test_loader, optimizer=optimizer[ID\n ], device=device[ID])\n', (8598, 8684), True, 'import icenet.deep as deep\n'), ((2059, 2088), 'icenet.deep.graph.SUPNet', 'deep.graph.SUPNet', ([], {}), '(**netparam)\n', (2076, 2088), True, 'import icenet.deep as deep\n'), ((2133, 2161), 'icenet.deep.graph.SGNet', 'deep.graph.SGNet', ([], {}), '(**netparam)\n', (2149, 2161), True, 'import icenet.deep as deep\n'), ((2208, 2238), 'icenet.deep.graph.SAGENet', 'deep.graph.SAGENet', ([], {}), '(**netparam)\n', (2226, 2238), True, 'import icenet.deep as deep\n'), ((2283, 2311), 'icenet.deep.graph.NNNet', 'deep.graph.NNNet', ([], {}), '(**netparam)\n', (2299, 2311), True, 'import icenet.deep as deep\n'), ((2358, 2388), 'icenet.deep.graph.GINENet', 'deep.graph.GINENet', ([], {}), '(**netparam)\n', (2376, 2388), True, 'import icenet.deep as deep\n'), ((2437, 2469), 'icenet.deep.graph.SplineNet', 'deep.graph.SplineNet', ([], {}), '(**netparam)\n', (2457, 2469), True, 'import icenet.deep as deep\n')] |
import numpy as np
def parse_res(res):
min = -1
avg = -1
if res != "":
if "," not in res:
min = int(res)
avg = int(res)
else:
all = np.array([int(r) for r in res.split(",")])
min = np.min(all)
avg = np.mean(all)
return min,avg
def get_static_final(projects, ver, result_list):
final_result = []
true_ver = []
venn_result = []
for index in range(0,len(projects)): #each project
results_by_proj = result_list[index]
tops = np.zeros(3)
ranks = np.zeros(2)
ranks_min = list() #first
ranks_avg = list() #all
actual_ver = 0
for res in results_by_proj: #result of each version
if res == "":
venn_result.append(0)
else:
#if res != "":
min,avg = parse_res(res)
if min == 1:
venn_result.append(1)
else:
venn_result.append(0)
if min == -1:
continue
if min <= 1:
tops[0]+=1
if min <= 3:
tops[1]+=1
if min <= 5:
tops[2]+=1
ranks[0]+=min
ranks[1]+=avg
ranks_min.append(min)
ranks_avg.append(avg)
actual_ver+=1
true_ver.append(actual_ver)
if actual_ver == 0:
ranks = [0,0]
else:
ranks = ranks/actual_ver
result = (int(tops[0]), int(tops[1]),int(tops[2]), round(float(ranks[0]),2), round(float(ranks[1]),2),)
result = np.array(result, dtype=object)
final_result.append(result)
#print(true_ver)
final_result = np.array(final_result)
return final_result,true_ver
def get_final(final_result,true_ver):
np_topn = final_result[:,0:3]
np_mean = final_result[:,3:5]
np_top = np.sum(np_topn,0)
np_mean = np_mean * np.transpose(true_ver).reshape(len(true_ver),1)
np_mean = np.sum(np_mean,0)/np.sum(true_ver)
final_result = np.concatenate((np_top,np_mean))
return final_result | [
"numpy.mean",
"numpy.array",
"numpy.zeros",
"numpy.sum",
"numpy.concatenate",
"numpy.min",
"numpy.transpose"
] | [((1822, 1844), 'numpy.array', 'np.array', (['final_result'], {}), '(final_result)\n', (1830, 1844), True, 'import numpy as np\n'), ((1997, 2015), 'numpy.sum', 'np.sum', (['np_topn', '(0)'], {}), '(np_topn, 0)\n', (2003, 2015), True, 'import numpy as np\n'), ((2155, 2188), 'numpy.concatenate', 'np.concatenate', (['(np_top, np_mean)'], {}), '((np_top, np_mean))\n', (2169, 2188), True, 'import numpy as np\n'), ((559, 570), 'numpy.zeros', 'np.zeros', (['(3)'], {}), '(3)\n', (567, 570), True, 'import numpy as np\n'), ((587, 598), 'numpy.zeros', 'np.zeros', (['(2)'], {}), '(2)\n', (595, 598), True, 'import numpy as np\n'), ((1715, 1745), 'numpy.array', 'np.array', (['result'], {'dtype': 'object'}), '(result, dtype=object)\n', (1723, 1745), True, 'import numpy as np\n'), ((2101, 2119), 'numpy.sum', 'np.sum', (['np_mean', '(0)'], {}), '(np_mean, 0)\n', (2107, 2119), True, 'import numpy as np\n'), ((2119, 2135), 'numpy.sum', 'np.sum', (['true_ver'], {}), '(true_ver)\n', (2125, 2135), True, 'import numpy as np\n'), ((257, 268), 'numpy.min', 'np.min', (['all'], {}), '(all)\n', (263, 268), True, 'import numpy as np\n'), ((287, 299), 'numpy.mean', 'np.mean', (['all'], {}), '(all)\n', (294, 299), True, 'import numpy as np\n'), ((2039, 2061), 'numpy.transpose', 'np.transpose', (['true_ver'], {}), '(true_ver)\n', (2051, 2061), True, 'import numpy as np\n')] |
# APPARENT MAG -> ABSOLUTE MAG WITH DISTANCE INFO.
#============================================================
import glob
import numpy as np
import matplotlib.pyplot as plt
from astropy.io import ascii, fits
from astropy.table import Table, vstack
from astropy import units as u
def app2abs(m, mer, d, der):
M = m -5 * np.log10(d) + 5
Mer = np.sqrt( (mer)**2 + ((-5*der)/(d*np.log(10)))**2 )
return M, Mer
path_table = '/home/sonic/Research/gppy/table/phot_gw170817_Drout.dat'
path_save = '/home/sonic/Research/gppy/table'
photbl = ascii.read(path_table)
dist, dister = 37.7 * u.Mpc, 8.7 * u.Mpc
d, der = dist.to(u.pc).value, dister.to(u.pc).value
m, mer = photbl['mag'], photbl['magerr']
M = m -5 * np.log10(d) + 5
Mer = np.sqrt( (mer)**2 + ((-5*der)/(d*np.log(10)))**2 )
photbl['mag_abs'] = M
photbl['mager_abs'] = Mer
photbl.write('{}/phot_gw170817_Drout.abs.dat'.format(path_save), format='ascii.tab', overwrite=True) | [
"numpy.log",
"numpy.log10",
"astropy.io.ascii.read"
] | [((547, 569), 'astropy.io.ascii.read', 'ascii.read', (['path_table'], {}), '(path_table)\n', (557, 569), False, 'from astropy.io import ascii, fits\n'), ((717, 728), 'numpy.log10', 'np.log10', (['d'], {}), '(d)\n', (725, 728), True, 'import numpy as np\n'), ((324, 335), 'numpy.log10', 'np.log10', (['d'], {}), '(d)\n', (332, 335), True, 'import numpy as np\n'), ((772, 782), 'numpy.log', 'np.log', (['(10)'], {}), '(10)\n', (778, 782), True, 'import numpy as np\n'), ((380, 390), 'numpy.log', 'np.log', (['(10)'], {}), '(10)\n', (386, 390), True, 'import numpy as np\n')] |
import numpy as np
import uncertainties.unumpy as unumpy
from uncertainties import ufloat
from scipy.stats import sem
print('Wellenlaenge')
dd1, za = np.genfromtxt('python/wellenlaenge.txt', unpack=True)
dd = (dd1*10**(-3))/5.017
lam = 2 * dd / za
mlam = np.mean(lam)
slam = sem(lam)
rlam = ufloat(mlam, slam)
np.savetxt('build/wellenlaenge.txt', np.column_stack([dd1, dd, za, lam]), header='dd1, dd, za, lam')
print('Vakuum')
dp, zb = np.genfromtxt('python/vakuum.txt', unpack=True)
dn = zb * 650*10**(-9) / (2 * 0.05)
mdn = np.mean(dn)
sdn = sem(dn)
rdn = ufloat(mdn, sdn)
n = 1 + rdn * 295.15 * 1.0132 / (273.15*0.8)
print('rlam =',rlam)
print('rdn =',rdn)
print('n =',n)
np.savetxt('build/vakuum.txt', np.column_stack([dp, zb, dn]), header='dp, zb, delta n')
| [
"numpy.mean",
"numpy.column_stack",
"scipy.stats.sem",
"uncertainties.ufloat",
"numpy.genfromtxt"
] | [((151, 204), 'numpy.genfromtxt', 'np.genfromtxt', (['"""python/wellenlaenge.txt"""'], {'unpack': '(True)'}), "('python/wellenlaenge.txt', unpack=True)\n", (164, 204), True, 'import numpy as np\n'), ((256, 268), 'numpy.mean', 'np.mean', (['lam'], {}), '(lam)\n', (263, 268), True, 'import numpy as np\n'), ((276, 284), 'scipy.stats.sem', 'sem', (['lam'], {}), '(lam)\n', (279, 284), False, 'from scipy.stats import sem\n'), ((292, 310), 'uncertainties.ufloat', 'ufloat', (['mlam', 'slam'], {}), '(mlam, slam)\n', (298, 310), False, 'from uncertainties import ufloat\n'), ((438, 485), 'numpy.genfromtxt', 'np.genfromtxt', (['"""python/vakuum.txt"""'], {'unpack': '(True)'}), "('python/vakuum.txt', unpack=True)\n", (451, 485), True, 'import numpy as np\n'), ((528, 539), 'numpy.mean', 'np.mean', (['dn'], {}), '(dn)\n', (535, 539), True, 'import numpy as np\n'), ((546, 553), 'scipy.stats.sem', 'sem', (['dn'], {}), '(dn)\n', (549, 553), False, 'from scipy.stats import sem\n'), ((560, 576), 'uncertainties.ufloat', 'ufloat', (['mdn', 'sdn'], {}), '(mdn, sdn)\n', (566, 576), False, 'from uncertainties import ufloat\n'), ((348, 383), 'numpy.column_stack', 'np.column_stack', (['[dd1, dd, za, lam]'], {}), '([dd1, dd, za, lam])\n', (363, 383), True, 'import numpy as np\n'), ((708, 737), 'numpy.column_stack', 'np.column_stack', (['[dp, zb, dn]'], {}), '([dp, zb, dn])\n', (723, 737), True, 'import numpy as np\n')] |
"""This module implements an microphone interface"""
from time import time
import numpy as np
try:
IMPORT_ERROR = False
import sounddevice as sd
except Exception as e:
IMPORT_ERROR = True
print(e)
from scipy.fft import rfft
class Microphone:
"""
This class provides a simple interface to the Microphone
Attributes
----------
sample_rate:int
the amount of samples per second
running:bool
indicator if the stream is running
"""
def __init__(self, HOP_LENGTH=512, N_FFT=2048, SAMPLE_RATE=44100,
BLOCK_SIZE=1024, DURATION=3, THRESHOLD=0.1) -> None:
self.hop_length = HOP_LENGTH
self.n_fft = N_FFT
self.sample_rate = SAMPLE_RATE
self.block_size = BLOCK_SIZE
self.duration = DURATION
self.threshold = THRESHOLD
self.list = []
self.running = True
self.start = None
@staticmethod
def create_hann_window(size=50):
"""
Create a Hann window of the given size
Parameters
----------
size : int
specifies the size of the returned array
Returns
-------
arr : np.array[float]
object with floating point numbers ranging between 0 and 1, and a size of `size`
Example
-------
>>> create_Hann_window(size=3)
array([0., 1., 0.])
>>> create_Hann_window(size=5)
array([0., 0.5, 1., 0.5, 0.])
>>> create_Hann_window(size=10)
array([0., 0.11697778, 0.41317591, 0.75, 0.96984631, 0.96984631,
0.75, 0.41317591, 0.11697778, 0.])
"""
arr = np.sin(np.linspace(-.5*np.pi, 1.5*np.pi, num=size))
arr += 1
arr /= 2
return arr
def sound_with_window(self, sound, window=None):
"""
return the sound when it's transformed with a hann window
[Note: Performance]
To optimise the performance as much as possible,
it is recommended to always give window into the function.
this prevents calculating the window over and over.
Parameters
----------
size : int
specifies the size of the returned array
Returns
-------
arr : np.array[float]
object with floating point numbers ranging between 0 and 1, and a size of `size`
Example
-------
>>> sound_with_window(size=3)
array([0., 1., 0.])
>>> sound_with_window(size=5)
array([0., 0.5, 1., 0.5, 0.])
>>> sound_with_window(size=10)
array([0., 0.11697778, 0.41317591, 0.75, 0.96984631,
0.96984631, 0.75, 0.41317591, 0.11697778, 0.])
"""
if not window:
window = Microphone.create_hann_window(size=len(sound))
return sound * window
def audio_to_fft(self, sound_array, samplerate=None, duration=None):
"""
This function converts the audio data to FFT format
Parameters
----------
sound_array: np.array[float]
a array with the sound signal, in Amplitude over time
samplerate: int
a integer indicating the speed with which samples were taken
duration: int
a integer indicating the duration, in seconds, for howlong samples were taken.
Returns
-------
ret_arr : np.array[float]
a array with the MFCC output of the FFT input
Example
-------
>>> audio_to_fft(sound_array)
array([])
"""
if samplerate is None:
samplerate = self.sample_rate
if duration is None:
duration = self.duration
real_y = np.abs(rfft(sound_array))
real_x = np.linspace(start=0, stop=samplerate//2,
num=(samplerate*duration)//2)
if len(real_y) == max(len(real_x), len(real_y)):
real_y = real_y[:len(real_x)]
else:
real_x = real_x[:len(real_y)]
return real_y, real_x
def callback_function(self, inputdata, _outdata, _frames, _time, status):
"""
This function will be called when the stream has received data
Parameters
----------
inputdate: list
the sound sample
status:string
a error message from the stream
"""
if status:
print(status)
new_l = []
for i in inputdata:
new_l.append(i[0])
if len(self.list) < 4000:
self.list += [0 for x in range(len(new_l))]
else:
self.list += new_l[::1]
if max(new_l) > self.threshold:
# TODO: if sound is above threshold -> analyse
pass
def stream(self, callback_function=None):
"""
This function will receive data from the audio device
Parameters
----------
callback_function: function
this function will be called with every frame
"""
if callback_function is None:
callback_function = self.callback_function
self.start = time()
if not IMPORT_ERROR:
stream = sd.Stream(samplerate=self.sample_rate, channels=1,
callback=callback_function, blocksize=self.block_size)
with stream:
while self.running:
if time() - self.start > self.duration:
self.running = False
pass
# Main
if __name__ == "__main__":
mic = Microphone()
print("Starting Stream")
mic.stream()
print("Stop Stream")
| [
"sounddevice.Stream",
"numpy.linspace",
"time.time",
"scipy.fft.rfft"
] | [((3769, 3843), 'numpy.linspace', 'np.linspace', ([], {'start': '(0)', 'stop': '(samplerate // 2)', 'num': '(samplerate * duration // 2)'}), '(start=0, stop=samplerate // 2, num=samplerate * duration // 2)\n', (3780, 3843), True, 'import numpy as np\n'), ((5145, 5151), 'time.time', 'time', ([], {}), '()\n', (5149, 5151), False, 'from time import time\n'), ((1669, 1717), 'numpy.linspace', 'np.linspace', (['(-0.5 * np.pi)', '(1.5 * np.pi)'], {'num': 'size'}), '(-0.5 * np.pi, 1.5 * np.pi, num=size)\n', (1680, 1717), True, 'import numpy as np\n'), ((3733, 3750), 'scipy.fft.rfft', 'rfft', (['sound_array'], {}), '(sound_array)\n', (3737, 3750), False, 'from scipy.fft import rfft\n'), ((5202, 5312), 'sounddevice.Stream', 'sd.Stream', ([], {'samplerate': 'self.sample_rate', 'channels': '(1)', 'callback': 'callback_function', 'blocksize': 'self.block_size'}), '(samplerate=self.sample_rate, channels=1, callback=\n callback_function, blocksize=self.block_size)\n', (5211, 5312), True, 'import sounddevice as sd\n'), ((5423, 5429), 'time.time', 'time', ([], {}), '()\n', (5427, 5429), False, 'from time import time\n')] |
# BSD 3-Clause License; see https://github.com/scikit-hep/awkward-1.0/blob/main/LICENSE
import pytest # noqa: F401
import numpy as np # noqa: F401
import awkward as ak # noqa: F401
jax = pytest.importorskip("jax")
jax.config.update("jax_enable_x64", True)
def test_from_jax():
jax_array_1d = jax.numpy.arange(10)
jax_array_2d = jax.numpy.array([[1.1, 2.2], [3.3, 4.4], [5.5, 6.6], [7.7, 8.8]])
ak_jax_array_1d = ak._v2.from_jax(jax_array_1d)
ak_jax_array_2d = ak._v2.from_jax(jax_array_2d)
for i in range(10):
assert ak_jax_array_1d[i] == jax_array_1d[i]
for i in range(4):
for j in range(2):
assert ak_jax_array_2d[i][j] == jax_array_2d[i][j]
def test_from_jax_tolist():
jax_array_1d = jax.numpy.array([9, 8, 7, 6, 5, 4, 3, 2, 1, 0])
ak_jax_array_1d = ak._v2.from_jax(jax_array_1d)
assert ak._v2.to_list(ak_jax_array_1d.layout) == [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
def test_NumpyArray_constructor():
assert ak._v2.backend(ak._v2.contents.NumpyArray(np.array([1, 2, 3]))) == "cpu"
assert (
ak._v2.backend(ak._v2.contents.NumpyArray(jax.numpy.array([1, 2, 3]))) == "jax"
)
def test_add_2():
one = ak._v2.Array([[1.1, 2.2, 3.3], [], [4.4, 5.5]], backend="jax")
two = 100
assert ak._v2.backend(one) == "jax"
three = one + two
assert ak._v2.to_list(three) == [[101.1, 102.2, 103.3], [], [104.4, 105.5]]
assert ak._v2.backend(three) == "jax"
| [
"awkward._v2.backend",
"awkward._v2.from_jax",
"awkward._v2.Array",
"awkward._v2.to_list",
"numpy.array",
"pytest.importorskip"
] | [((192, 218), 'pytest.importorskip', 'pytest.importorskip', (['"""jax"""'], {}), "('jax')\n", (211, 218), False, 'import pytest\n'), ((433, 462), 'awkward._v2.from_jax', 'ak._v2.from_jax', (['jax_array_1d'], {}), '(jax_array_1d)\n', (448, 462), True, 'import awkward as ak\n'), ((485, 514), 'awkward._v2.from_jax', 'ak._v2.from_jax', (['jax_array_2d'], {}), '(jax_array_2d)\n', (500, 514), True, 'import awkward as ak\n'), ((827, 856), 'awkward._v2.from_jax', 'ak._v2.from_jax', (['jax_array_1d'], {}), '(jax_array_1d)\n', (842, 856), True, 'import awkward as ak\n'), ((1200, 1262), 'awkward._v2.Array', 'ak._v2.Array', (['[[1.1, 2.2, 3.3], [], [4.4, 5.5]]'], {'backend': '"""jax"""'}), "([[1.1, 2.2, 3.3], [], [4.4, 5.5]], backend='jax')\n", (1212, 1262), True, 'import awkward as ak\n'), ((869, 907), 'awkward._v2.to_list', 'ak._v2.to_list', (['ak_jax_array_1d.layout'], {}), '(ak_jax_array_1d.layout)\n', (883, 907), True, 'import awkward as ak\n'), ((1288, 1307), 'awkward._v2.backend', 'ak._v2.backend', (['one'], {}), '(one)\n', (1302, 1307), True, 'import awkward as ak\n'), ((1350, 1371), 'awkward._v2.to_list', 'ak._v2.to_list', (['three'], {}), '(three)\n', (1364, 1371), True, 'import awkward as ak\n'), ((1430, 1451), 'awkward._v2.backend', 'ak._v2.backend', (['three'], {}), '(three)\n', (1444, 1451), True, 'import awkward as ak\n'), ((1032, 1051), 'numpy.array', 'np.array', (['[1, 2, 3]'], {}), '([1, 2, 3])\n', (1040, 1051), True, 'import numpy as np\n')] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import platform
import multiprocessing.pool
from setuptools import setup, Extension
lib_name = 'duckdb'
extensions = ['parquet', 'icu', 'fts', 'tpch', 'tpcds', 'visualizer']
if platform.system() == 'Windows':
extensions = ['parquet', 'icu', 'fts','tpch']
unity_build = 0
if 'DUCKDB_BUILD_UNITY' in os.environ:
unity_build = 16
def parallel_cpp_compile(self, sources, output_dir=None, macros=None, include_dirs=None, debug=0,
extra_preargs=None, extra_postargs=None, depends=None):
# Copied from distutils.ccompiler.CCompiler
macros, objects, extra_postargs, pp_opts, build = self._setup_compile(
output_dir, macros, include_dirs, sources, depends, extra_postargs)
cc_args = self._get_cc_args(pp_opts, debug, extra_preargs)
def _single_compile(obj):
try:
src, ext = build[obj]
except KeyError:
return
self._compile(obj, src, ext, cc_args, extra_postargs, pp_opts)
list(multiprocessing.pool.ThreadPool(multiprocessing.cpu_count()).imap(_single_compile, objects))
return objects
# speed up compilation with: -j = cpu_number() on non Windows machines
if os.name != 'nt':
import distutils.ccompiler
distutils.ccompiler.CCompiler.compile = parallel_cpp_compile
def open_utf8(fpath, flags):
import sys
if sys.version_info[0] < 3:
return open(fpath, flags)
else:
return open(fpath, flags, encoding="utf8")
# make sure we are in the right directory
os.chdir(os.path.dirname(os.path.realpath(__file__)))
if os.name == 'nt':
# windows:
toolchain_args = ['/wd4244', '/wd4267', '/wd4200', '/wd26451', '/wd26495', '/D_CRT_SECURE_NO_WARNINGS']
else:
# macos/linux
toolchain_args = ['-std=c++11', '-g0']
if 'DUCKDEBUG' in os.environ:
toolchain_args = ['-std=c++11', '-Wall', '-O0', '-g']
if 'DUCKDB_INSTALL_USER' in os.environ and 'install' in sys.argv:
sys.argv.append('--user')
existing_duckdb_dir = ''
new_sys_args = []
libraries = []
for i in range(len(sys.argv)):
if sys.argv[i].startswith("--binary-dir="):
existing_duckdb_dir = sys.argv[i].split('=', 1)[1]
elif sys.argv[i].startswith('--package_name=') :
lib_name = sys.argv[i].split('=', 1)[1]
elif sys.argv[i].startswith("--compile-flags="):
toolchain_args = ['-std=c++11'] + [x.strip() for x in sys.argv[i].split('=', 1)[1].split(' ') if len(x.strip()) > 0]
elif sys.argv[i].startswith("--libs="):
libraries = [x.strip() for x in sys.argv[i].split('=', 1)[1].split(' ') if len(x.strip()) > 0]
else:
new_sys_args.append(sys.argv[i])
sys.argv = new_sys_args
toolchain_args.append('-DDUCKDB_PYTHON_LIB_NAME='+lib_name)
if platform.system() == 'Darwin':
toolchain_args.extend(['-stdlib=libc++', '-mmacosx-version-min=10.7'])
if platform.system() == 'Windows':
toolchain_args.extend(['-DDUCKDB_BUILD_LIBRARY','-DWIN32'])
for ext in extensions:
toolchain_args.extend(['-DBUILD_{}_EXTENSION'.format(ext.upper())])
class get_pybind_include(object):
def __init__(self, user=False):
self.user = user
def __str__(self):
import pybind11
return pybind11.get_include(self.user)
class get_numpy_include(object):
def __str__(self):
import numpy
return numpy.get_include()
if 'BUILD_HTTPFS' in os.environ:
libraries += ['crypto', 'ssl']
extensions += ['httpfs']
extra_files = []
header_files = []
script_path = os.path.dirname(os.path.abspath(__file__))
main_include_path = os.path.join(script_path, 'src', 'include')
main_source_path = os.path.join(script_path, 'src')
main_source_files = ['duckdb_python.cpp'] + [os.path.join('src', x) for x in os.listdir(main_source_path) if '.cpp' in x]
include_directories = [main_include_path, get_numpy_include(), get_pybind_include(), get_pybind_include(user=True)]
if len(existing_duckdb_dir) == 0:
# no existing library supplied: compile everything from source
source_files = main_source_files
# check if amalgamation exists
if os.path.isfile(os.path.join(script_path, '..', '..', 'scripts', 'amalgamation.py')):
# amalgamation exists: compiling from source directory
# copy all source files to the current directory
sys.path.append(os.path.join(script_path, '..', '..', 'scripts'))
import package_build
(source_list, include_list, original_sources) = package_build.build_package(os.path.join(script_path, 'duckdb'), extensions, False, unity_build)
duckdb_sources = [os.path.sep.join(package_build.get_relative_path(script_path, x).split('/')) for x in source_list]
duckdb_sources.sort()
original_sources = [os.path.join('duckdb', x) for x in original_sources]
duckdb_includes = [os.path.join('duckdb', x) for x in include_list]
duckdb_includes += ['duckdb']
# gather the include files
import amalgamation
header_files = amalgamation.list_includes_files(duckdb_includes)
# write the source list, include list and git hash to separate files
with open_utf8('sources.list', 'w+') as f:
for source_file in duckdb_sources:
f.write(source_file + "\n")
with open_utf8('includes.list', 'w+') as f:
for include_file in duckdb_includes:
f.write(include_file + '\n')
extra_files = ['sources.list', 'includes.list'] + original_sources
else:
# if amalgamation does not exist, we are in a package distribution
# read the include files, source list and include files from the supplied lists
with open_utf8('sources.list', 'r') as f:
duckdb_sources = [x for x in f.read().split('\n') if len(x) > 0]
with open_utf8('includes.list', 'r') as f:
duckdb_includes = [x for x in f.read().split('\n') if len(x) > 0]
source_files += duckdb_sources
include_directories = duckdb_includes + include_directories
libduckdb = Extension(lib_name,
include_dirs=include_directories,
sources=source_files,
extra_compile_args=toolchain_args,
extra_link_args=toolchain_args,
libraries=libraries,
language='c++')
else:
sys.path.append(os.path.join(script_path, '..', '..', 'scripts'))
import package_build
toolchain_args += ['-I' + x for x in package_build.includes(extensions)]
result_libraries = package_build.get_libraries(existing_duckdb_dir, libraries, extensions)
library_dirs = [x[0] for x in result_libraries if x[0] is not None]
libnames = [x[1] for x in result_libraries if x[1] is not None]
libduckdb = Extension(lib_name,
include_dirs=include_directories,
sources=main_source_files,
extra_compile_args=toolchain_args,
extra_link_args=toolchain_args,
libraries=libnames,
library_dirs=library_dirs,
language='c++')
# Only include pytest-runner in setup_requires if we're invoking tests
if {'pytest', 'test', 'ptr'}.intersection(sys.argv):
setup_requires = ['pytest-runner']
else:
setup_requires = []
setuptools_scm_conf = {"root": "../..", "relative_to": __file__}
if os.getenv('SETUPTOOLS_SCM_NO_LOCAL', 'no') != 'no':
setuptools_scm_conf['local_scheme'] = 'no-local-version'
# data files need to be formatted as [(directory, [files...]), (directory2, [files...])]
# no clue why the setup script can't do this automatically, but hey
def setup_data_files(data_files):
directory_map = {}
for data_file in data_files:
normalized_fpath = os.path.sep.join(data_file.split('/'))
splits = normalized_fpath.rsplit(os.path.sep, 1)
if len(splits) == 1:
# no directory specified
directory = ""
fname = normalized_fpath
else:
directory = splits[0]
fname = splits[1]
if directory not in directory_map:
directory_map[directory] = []
directory_map[directory].append(normalized_fpath)
new_data_files = []
for kv in directory_map.keys():
new_data_files.append((kv, directory_map[kv]))
return new_data_files
data_files = setup_data_files(extra_files + header_files)
setup(
name = lib_name,
description = 'DuckDB embedded database',
keywords = 'DuckDB Database SQL OLAP',
url="https://www.duckdb.org",
long_description = 'See here for an introduction: https://duckdb.org/docs/api/python',
license='MIT',
install_requires=[ # these version is still available for Python 2, newer ones aren't
'numpy>=1.14'
],
data_files = data_files,
packages=[
'duckdb_query_graph',
'duckdb-stubs'
],
include_package_data=True,
setup_requires=setup_requires + ["setuptools_scm"] + ['pybind11>=2.6.0'],
use_scm_version = setuptools_scm_conf,
tests_require=['pytest'],
classifiers = [
'Topic :: Database :: Database Engines/Servers',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
],
ext_modules = [libduckdb],
maintainer = "<NAME>",
maintainer_email = "<EMAIL>"
)
| [
"os.listdir",
"os.getenv",
"package_build.get_libraries",
"amalgamation.list_includes_files",
"sys.argv.append",
"os.path.join",
"setuptools.setup",
"package_build.get_relative_path",
"setuptools.Extension",
"os.path.realpath",
"platform.system",
"pybind11.get_include",
"numpy.get_include",
... | [((3608, 3651), 'os.path.join', 'os.path.join', (['script_path', '"""src"""', '"""include"""'], {}), "(script_path, 'src', 'include')\n", (3620, 3651), False, 'import os\n'), ((3671, 3703), 'os.path.join', 'os.path.join', (['script_path', '"""src"""'], {}), "(script_path, 'src')\n", (3683, 3703), False, 'import os\n'), ((8291, 9056), 'setuptools.setup', 'setup', ([], {'name': 'lib_name', 'description': '"""DuckDB embedded database"""', 'keywords': '"""DuckDB Database SQL OLAP"""', 'url': '"""https://www.duckdb.org"""', 'long_description': '"""See here for an introduction: https://duckdb.org/docs/api/python"""', 'license': '"""MIT"""', 'install_requires': "['numpy>=1.14']", 'data_files': 'data_files', 'packages': "['duckdb_query_graph', 'duckdb-stubs']", 'include_package_data': '(True)', 'setup_requires': "(setup_requires + ['setuptools_scm'] + ['pybind11>=2.6.0'])", 'use_scm_version': 'setuptools_scm_conf', 'tests_require': "['pytest']", 'classifiers': "['Topic :: Database :: Database Engines/Servers',\n 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License'\n ]", 'ext_modules': '[libduckdb]', 'maintainer': '"""<NAME>"""', 'maintainer_email': '"""<EMAIL>"""'}), "(name=lib_name, description='DuckDB embedded database', keywords=\n 'DuckDB Database SQL OLAP', url='https://www.duckdb.org',\n long_description=\n 'See here for an introduction: https://duckdb.org/docs/api/python',\n license='MIT', install_requires=['numpy>=1.14'], data_files=data_files,\n packages=['duckdb_query_graph', 'duckdb-stubs'], include_package_data=\n True, setup_requires=setup_requires + ['setuptools_scm'] + [\n 'pybind11>=2.6.0'], use_scm_version=setuptools_scm_conf, tests_require=\n ['pytest'], classifiers=[\n 'Topic :: Database :: Database Engines/Servers',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: MIT License'], ext_modules=[libduckdb],\n maintainer='<NAME>', maintainer_email='<EMAIL>')\n", (8296, 9056), False, 'from setuptools import setup, Extension\n'), ((249, 266), 'platform.system', 'platform.system', ([], {}), '()\n', (264, 266), False, 'import platform\n'), ((2001, 2026), 'sys.argv.append', 'sys.argv.append', (['"""--user"""'], {}), "('--user')\n", (2016, 2026), False, 'import sys\n'), ((2789, 2806), 'platform.system', 'platform.system', ([], {}), '()\n', (2804, 2806), False, 'import platform\n'), ((2899, 2916), 'platform.system', 'platform.system', ([], {}), '()\n', (2914, 2916), False, 'import platform\n'), ((3561, 3586), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (3576, 3586), False, 'import os\n'), ((6065, 6252), 'setuptools.Extension', 'Extension', (['lib_name'], {'include_dirs': 'include_directories', 'sources': 'source_files', 'extra_compile_args': 'toolchain_args', 'extra_link_args': 'toolchain_args', 'libraries': 'libraries', 'language': '"""c++"""'}), "(lib_name, include_dirs=include_directories, sources=source_files,\n extra_compile_args=toolchain_args, extra_link_args=toolchain_args,\n libraries=libraries, language='c++')\n", (6074, 6252), False, 'from setuptools import setup, Extension\n'), ((6496, 6567), 'package_build.get_libraries', 'package_build.get_libraries', (['existing_duckdb_dir', 'libraries', 'extensions'], {}), '(existing_duckdb_dir, libraries, extensions)\n', (6523, 6567), False, 'import package_build\n'), ((6725, 6950), 'setuptools.Extension', 'Extension', (['lib_name'], {'include_dirs': 'include_directories', 'sources': 'main_source_files', 'extra_compile_args': 'toolchain_args', 'extra_link_args': 'toolchain_args', 'libraries': 'libnames', 'library_dirs': 'library_dirs', 'language': '"""c++"""'}), "(lib_name, include_dirs=include_directories, sources=\n main_source_files, extra_compile_args=toolchain_args, extra_link_args=\n toolchain_args, libraries=libnames, library_dirs=library_dirs, language\n ='c++')\n", (6734, 6950), False, 'from setuptools import setup, Extension\n'), ((7255, 7297), 'os.getenv', 'os.getenv', (['"""SETUPTOOLS_SCM_NO_LOCAL"""', '"""no"""'], {}), "('SETUPTOOLS_SCM_NO_LOCAL', 'no')\n", (7264, 7297), False, 'import os\n'), ((1595, 1621), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (1611, 1621), False, 'import os\n'), ((3250, 3281), 'pybind11.get_include', 'pybind11.get_include', (['self.user'], {}), '(self.user)\n', (3270, 3281), False, 'import pybind11\n'), ((3375, 3394), 'numpy.get_include', 'numpy.get_include', ([], {}), '()\n', (3392, 3394), False, 'import numpy\n'), ((3749, 3771), 'os.path.join', 'os.path.join', (['"""src"""', 'x'], {}), "('src', x)\n", (3761, 3771), False, 'import os\n'), ((4138, 4205), 'os.path.join', 'os.path.join', (['script_path', '""".."""', '""".."""', '"""scripts"""', '"""amalgamation.py"""'], {}), "(script_path, '..', '..', 'scripts', 'amalgamation.py')\n", (4150, 4205), False, 'import os\n'), ((5025, 5074), 'amalgamation.list_includes_files', 'amalgamation.list_includes_files', (['duckdb_includes'], {}), '(duckdb_includes)\n', (5057, 5074), False, 'import amalgamation\n'), ((6319, 6367), 'os.path.join', 'os.path.join', (['script_path', '""".."""', '""".."""', '"""scripts"""'], {}), "(script_path, '..', '..', 'scripts')\n", (6331, 6367), False, 'import os\n'), ((3781, 3809), 'os.listdir', 'os.listdir', (['main_source_path'], {}), '(main_source_path)\n', (3791, 3809), False, 'import os\n'), ((4352, 4400), 'os.path.join', 'os.path.join', (['script_path', '""".."""', '""".."""', '"""scripts"""'], {}), "(script_path, '..', '..', 'scripts')\n", (4364, 4400), False, 'import os\n'), ((4516, 4551), 'os.path.join', 'os.path.join', (['script_path', '"""duckdb"""'], {}), "(script_path, 'duckdb')\n", (4528, 4551), False, 'import os\n'), ((4770, 4795), 'os.path.join', 'os.path.join', (['"""duckdb"""', 'x'], {}), "('duckdb', x)\n", (4782, 4795), False, 'import os\n'), ((4851, 4876), 'os.path.join', 'os.path.join', (['"""duckdb"""', 'x'], {}), "('duckdb', x)\n", (4863, 4876), False, 'import os\n'), ((6436, 6470), 'package_build.includes', 'package_build.includes', (['extensions'], {}), '(extensions)\n', (6458, 6470), False, 'import package_build\n'), ((4629, 4676), 'package_build.get_relative_path', 'package_build.get_relative_path', (['script_path', 'x'], {}), '(script_path, x)\n', (4660, 4676), False, 'import package_build\n')] |
# Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for XLNet classifier network."""
from absl.testing import parameterized
import numpy as np
import tensorflow as tf
from tensorflow.python.keras import keras_parameterized # pylint: disable=g-direct-tensorflow-import
from official.nlp.modeling import networks
from official.nlp.modeling.models import xlnet
def _get_xlnet_base() -> tf.keras.layers.Layer:
"""Returns a trivial base XLNet model."""
return networks.XLNetBase(
vocab_size=100,
num_layers=2,
hidden_size=4,
num_attention_heads=2,
head_size=2,
inner_size=2,
dropout_rate=0.,
attention_dropout_rate=0.,
attention_type='bi',
bi_data=True,
initializer=tf.keras.initializers.RandomNormal(stddev=0.1),
two_stream=False,
tie_attention_biases=True,
reuse_length=0,
inner_activation='relu')
# This decorator runs the test in V1, V2-Eager, and V2-Functional mode. It
# guarantees forward compatibility of this code for the V2 switchover.
@keras_parameterized.run_all_keras_modes
class XLNetClassifierTest(keras_parameterized.TestCase):
def test_xlnet_trainer(self):
"""Validate that the Keras object can be created."""
num_classes = 2
seq_length = 4
# Build a simple XLNet based network to use with the XLNet trainer.
xlnet_base = _get_xlnet_base()
# Create an XLNet trainer with the created network.
xlnet_trainer_model = xlnet.XLNetClassifier(
network=xlnet_base,
num_classes=num_classes,
initializer=tf.keras.initializers.RandomNormal(stddev=0.1),
summary_type='last',
dropout_rate=0.1)
inputs = dict(
input_word_ids=tf.keras.layers.Input(
shape=(seq_length,), dtype=tf.int32, name='input_word_ids'),
input_type_ids=tf.keras.layers.Input(
shape=(seq_length,), dtype=tf.int32, name='input_type_ids'),
input_mask=tf.keras.layers.Input(
shape=(seq_length,), dtype=tf.float32, name='input_mask'),
permutation_mask=tf.keras.layers.Input(
shape=(seq_length, seq_length,), dtype=tf.float32,
name='permutation_mask'),
masked_tokens=tf.keras.layers.Input(
shape=(seq_length,), dtype=tf.float32, name='masked_tokens'))
logits = xlnet_trainer_model(inputs)
expected_classification_shape = [None, num_classes]
self.assertAllEqual(expected_classification_shape, logits.shape.as_list())
@parameterized.parameters(1, 2)
def test_xlnet_tensor_call(self, num_classes):
"""Validates that the Keras object can be invoked."""
seq_length = 4
batch_size = 2
# Build a simple XLNet based network to use with the XLNet trainer.
xlnet_base = _get_xlnet_base()
# Create an XLNet trainer with the created network.
xlnet_trainer_model = xlnet.XLNetClassifier(
network=xlnet_base,
num_classes=num_classes,
initializer=tf.keras.initializers.RandomNormal(stddev=0.1),
summary_type='last',
dropout_rate=0.1)
sequence_shape = (batch_size, seq_length)
inputs = dict(
input_word_ids=np.random.randint(
10, size=sequence_shape, dtype='int32'),
input_type_ids=np.random.randint(2, size=sequence_shape, dtype='int32'),
input_mask=np.random.randint(2, size=sequence_shape).astype('float32'),
permutation_mask=np.random.randint(
2, size=(batch_size, seq_length, seq_length)).astype('float32'),
masked_tokens=tf.random.uniform(shape=sequence_shape))
xlnet_trainer_model(inputs)
def test_serialize_deserialize(self):
"""Validates that the XLNet trainer can be serialized and deserialized."""
# Build a simple XLNet based network to use with the XLNet trainer.
xlnet_base = _get_xlnet_base()
# Create an XLNet trainer with the created network.
xlnet_trainer_model = xlnet.XLNetClassifier(
network=xlnet_base,
num_classes=2,
initializer=tf.keras.initializers.RandomNormal(stddev=0.1),
summary_type='last',
dropout_rate=0.1)
# Create another XLNet trainer via serialization and deserialization.
config = xlnet_trainer_model.get_config()
new_xlnet_trainer_model = xlnet.XLNetClassifier.from_config(
config)
# Validate that the config can be forced to JSON.
_ = new_xlnet_trainer_model.to_json()
# If serialization was successful, then the new config should match the old.
self.assertAllEqual(xlnet_trainer_model.get_config(),
new_xlnet_trainer_model.get_config())
@keras_parameterized.run_all_keras_modes
class XLNetSpanLabelerTest(keras_parameterized.TestCase):
@parameterized.parameters(1, 2)
def test_xlnet_trainer(self, top_n):
"""Validate that the Keras object can be created."""
seq_length = 4
# Build a simple XLNet based network to use with the XLNet trainer.
xlnet_base = _get_xlnet_base()
# Create an XLNet trainer with the created network.
xlnet_trainer_model = xlnet.XLNetSpanLabeler(
network=xlnet_base,
start_n_top=top_n,
end_n_top=top_n,
initializer=tf.keras.initializers.RandomNormal(stddev=0.1),
span_labeling_activation='tanh',
dropout_rate=0.1)
inputs = dict(
input_ids=tf.keras.layers.Input(
shape=(seq_length,), dtype=tf.int32, name='input_word_ids'),
segment_ids=tf.keras.layers.Input(
shape=(seq_length,), dtype=tf.int32, name='segment_ids'),
input_mask=tf.keras.layers.Input(
shape=(seq_length,), dtype=tf.float32, name='input_mask'),
position_mask=tf.keras.layers.Input(
shape=(seq_length,), dtype=tf.float32, name='position_mask'),
class_index=tf.keras.layers.Input(
shape=(), dtype=tf.int32, name='class_index'),
start_positions=tf.keras.layers.Input(
shape=(), dtype=tf.int32, name='start_positions'))
outputs, _ = xlnet_trainer_model(inputs)
self.assertIsInstance(outputs, dict)
# Test tensor value calls for the created model.
batch_size = 2
sequence_shape = (batch_size, seq_length)
inputs = dict(
input_ids=np.random.randint(10, size=sequence_shape, dtype='int32'),
segment_ids=np.random.randint(2, size=sequence_shape, dtype='int32'),
input_mask=np.random.randint(2, size=sequence_shape).astype('float32'),
position_mask=np.random.randint(
1, size=(sequence_shape)).astype('float32'),
class_index=np.random.randint(1, size=(batch_size)).astype('uint8'),
start_positions=tf.random.uniform(
shape=(batch_size,), maxval=5, dtype=tf.int32))
outputs, _ = xlnet_trainer_model(inputs)
expected_inference_keys = {
'start_top_log_probs', 'end_top_log_probs', 'class_logits',
'start_top_index', 'end_top_index',
}
self.assertSetEqual(expected_inference_keys, set(outputs.keys()))
outputs, _ = xlnet_trainer_model(inputs, training=True)
self.assertIsInstance(outputs, dict)
expected_train_keys = {
'start_log_probs', 'end_log_probs', 'class_logits'
}
self.assertSetEqual(expected_train_keys, set(outputs.keys()))
self.assertIsInstance(outputs, dict)
def test_serialize_deserialize(self):
"""Validates that the XLNet trainer can be serialized and deserialized."""
# Build a simple XLNet based network to use with the XLNet trainer.
xlnet_base = _get_xlnet_base()
# Create an XLNet trainer with the created network.
xlnet_trainer_model = xlnet.XLNetSpanLabeler(
network=xlnet_base,
start_n_top=2,
end_n_top=2,
initializer=tf.keras.initializers.RandomNormal(stddev=0.1),
span_labeling_activation='tanh',
dropout_rate=0.1)
# Create another XLNet trainer via serialization and deserialization.
config = xlnet_trainer_model.get_config()
new_xlnet_trainer_model = xlnet.XLNetSpanLabeler.from_config(
config)
# Validate that the config can be forced to JSON.
_ = new_xlnet_trainer_model.to_json()
# If serialization was successful, then the new config should match the old.
self.assertAllEqual(xlnet_trainer_model.get_config(),
new_xlnet_trainer_model.get_config())
if __name__ == '__main__':
tf.test.main()
| [
"tensorflow.random.uniform",
"tensorflow.keras.layers.Input",
"tensorflow.keras.initializers.RandomNormal",
"official.nlp.modeling.models.xlnet.XLNetSpanLabeler.from_config",
"absl.testing.parameterized.parameters",
"tensorflow.test.main",
"numpy.random.randint",
"official.nlp.modeling.models.xlnet.XL... | [((3133, 3163), 'absl.testing.parameterized.parameters', 'parameterized.parameters', (['(1)', '(2)'], {}), '(1, 2)\n', (3157, 3163), False, 'from absl.testing import parameterized\n'), ((5357, 5387), 'absl.testing.parameterized.parameters', 'parameterized.parameters', (['(1)', '(2)'], {}), '(1, 2)\n', (5381, 5387), False, 'from absl.testing import parameterized\n'), ((9000, 9014), 'tensorflow.test.main', 'tf.test.main', ([], {}), '()\n', (9012, 9014), True, 'import tensorflow as tf\n'), ((4902, 4943), 'official.nlp.modeling.models.xlnet.XLNetClassifier.from_config', 'xlnet.XLNetClassifier.from_config', (['config'], {}), '(config)\n', (4935, 4943), False, 'from official.nlp.modeling.models import xlnet\n'), ((8618, 8660), 'official.nlp.modeling.models.xlnet.XLNetSpanLabeler.from_config', 'xlnet.XLNetSpanLabeler.from_config', (['config'], {}), '(config)\n', (8652, 8660), False, 'from official.nlp.modeling.models import xlnet\n'), ((1383, 1429), 'tensorflow.keras.initializers.RandomNormal', 'tf.keras.initializers.RandomNormal', ([], {'stddev': '(0.1)'}), '(stddev=0.1)\n', (1417, 1429), True, 'import tensorflow as tf\n'), ((2210, 2256), 'tensorflow.keras.initializers.RandomNormal', 'tf.keras.initializers.RandomNormal', ([], {'stddev': '(0.1)'}), '(stddev=0.1)\n', (2244, 2256), True, 'import tensorflow as tf\n'), ((2355, 2441), 'tensorflow.keras.layers.Input', 'tf.keras.layers.Input', ([], {'shape': '(seq_length,)', 'dtype': 'tf.int32', 'name': '"""input_word_ids"""'}), "(shape=(seq_length,), dtype=tf.int32, name=\n 'input_word_ids')\n", (2376, 2441), True, 'import tensorflow as tf\n'), ((2474, 2560), 'tensorflow.keras.layers.Input', 'tf.keras.layers.Input', ([], {'shape': '(seq_length,)', 'dtype': 'tf.int32', 'name': '"""input_type_ids"""'}), "(shape=(seq_length,), dtype=tf.int32, name=\n 'input_type_ids')\n", (2495, 2560), True, 'import tensorflow as tf\n'), ((2589, 2668), 'tensorflow.keras.layers.Input', 'tf.keras.layers.Input', ([], {'shape': '(seq_length,)', 'dtype': 'tf.float32', 'name': '"""input_mask"""'}), "(shape=(seq_length,), dtype=tf.float32, name='input_mask')\n", (2610, 2668), True, 'import tensorflow as tf\n'), ((2708, 2808), 'tensorflow.keras.layers.Input', 'tf.keras.layers.Input', ([], {'shape': '(seq_length, seq_length)', 'dtype': 'tf.float32', 'name': '"""permutation_mask"""'}), "(shape=(seq_length, seq_length), dtype=tf.float32,\n name='permutation_mask')\n", (2729, 2808), True, 'import tensorflow as tf\n'), ((2854, 2941), 'tensorflow.keras.layers.Input', 'tf.keras.layers.Input', ([], {'shape': '(seq_length,)', 'dtype': 'tf.float32', 'name': '"""masked_tokens"""'}), "(shape=(seq_length,), dtype=tf.float32, name=\n 'masked_tokens')\n", (2875, 2941), True, 'import tensorflow as tf\n'), ((3603, 3649), 'tensorflow.keras.initializers.RandomNormal', 'tf.keras.initializers.RandomNormal', ([], {'stddev': '(0.1)'}), '(stddev=0.1)\n', (3637, 3649), True, 'import tensorflow as tf\n'), ((3795, 3852), 'numpy.random.randint', 'np.random.randint', (['(10)'], {'size': 'sequence_shape', 'dtype': '"""int32"""'}), "(10, size=sequence_shape, dtype='int32')\n", (3812, 3852), True, 'import numpy as np\n'), ((3890, 3946), 'numpy.random.randint', 'np.random.randint', (['(2)'], {'size': 'sequence_shape', 'dtype': '"""int32"""'}), "(2, size=sequence_shape, dtype='int32')\n", (3907, 3946), True, 'import numpy as np\n'), ((4171, 4210), 'tensorflow.random.uniform', 'tf.random.uniform', ([], {'shape': 'sequence_shape'}), '(shape=sequence_shape)\n', (4188, 4210), True, 'import tensorflow as tf\n'), ((4648, 4694), 'tensorflow.keras.initializers.RandomNormal', 'tf.keras.initializers.RandomNormal', ([], {'stddev': '(0.1)'}), '(stddev=0.1)\n', (4682, 4694), True, 'import tensorflow as tf\n'), ((5817, 5863), 'tensorflow.keras.initializers.RandomNormal', 'tf.keras.initializers.RandomNormal', ([], {'stddev': '(0.1)'}), '(stddev=0.1)\n', (5851, 5863), True, 'import tensorflow as tf\n'), ((5969, 6055), 'tensorflow.keras.layers.Input', 'tf.keras.layers.Input', ([], {'shape': '(seq_length,)', 'dtype': 'tf.int32', 'name': '"""input_word_ids"""'}), "(shape=(seq_length,), dtype=tf.int32, name=\n 'input_word_ids')\n", (5990, 6055), True, 'import tensorflow as tf\n'), ((6085, 6163), 'tensorflow.keras.layers.Input', 'tf.keras.layers.Input', ([], {'shape': '(seq_length,)', 'dtype': 'tf.int32', 'name': '"""segment_ids"""'}), "(shape=(seq_length,), dtype=tf.int32, name='segment_ids')\n", (6106, 6163), True, 'import tensorflow as tf\n'), ((6197, 6276), 'tensorflow.keras.layers.Input', 'tf.keras.layers.Input', ([], {'shape': '(seq_length,)', 'dtype': 'tf.float32', 'name': '"""input_mask"""'}), "(shape=(seq_length,), dtype=tf.float32, name='input_mask')\n", (6218, 6276), True, 'import tensorflow as tf\n'), ((6313, 6400), 'tensorflow.keras.layers.Input', 'tf.keras.layers.Input', ([], {'shape': '(seq_length,)', 'dtype': 'tf.float32', 'name': '"""position_mask"""'}), "(shape=(seq_length,), dtype=tf.float32, name=\n 'position_mask')\n", (6334, 6400), True, 'import tensorflow as tf\n'), ((6430, 6497), 'tensorflow.keras.layers.Input', 'tf.keras.layers.Input', ([], {'shape': '()', 'dtype': 'tf.int32', 'name': '"""class_index"""'}), "(shape=(), dtype=tf.int32, name='class_index')\n", (6451, 6497), True, 'import tensorflow as tf\n'), ((6536, 6607), 'tensorflow.keras.layers.Input', 'tf.keras.layers.Input', ([], {'shape': '()', 'dtype': 'tf.int32', 'name': '"""start_positions"""'}), "(shape=(), dtype=tf.int32, name='start_positions')\n", (6557, 6607), True, 'import tensorflow as tf\n'), ((6864, 6921), 'numpy.random.randint', 'np.random.randint', (['(10)'], {'size': 'sequence_shape', 'dtype': '"""int32"""'}), "(10, size=sequence_shape, dtype='int32')\n", (6881, 6921), True, 'import numpy as np\n'), ((6943, 6999), 'numpy.random.randint', 'np.random.randint', (['(2)'], {'size': 'sequence_shape', 'dtype': '"""int32"""'}), "(2, size=sequence_shape, dtype='int32')\n", (6960, 6999), True, 'import numpy as np\n'), ((7280, 7344), 'tensorflow.random.uniform', 'tf.random.uniform', ([], {'shape': '(batch_size,)', 'maxval': '(5)', 'dtype': 'tf.int32'}), '(shape=(batch_size,), maxval=5, dtype=tf.int32)\n', (7297, 7344), True, 'import tensorflow as tf\n'), ((8352, 8398), 'tensorflow.keras.initializers.RandomNormal', 'tf.keras.initializers.RandomNormal', ([], {'stddev': '(0.1)'}), '(stddev=0.1)\n', (8386, 8398), True, 'import tensorflow as tf\n'), ((3967, 4008), 'numpy.random.randint', 'np.random.randint', (['(2)'], {'size': 'sequence_shape'}), '(2, size=sequence_shape)\n', (3984, 4008), True, 'import numpy as np\n'), ((4053, 4116), 'numpy.random.randint', 'np.random.randint', (['(2)'], {'size': '(batch_size, seq_length, seq_length)'}), '(2, size=(batch_size, seq_length, seq_length))\n', (4070, 4116), True, 'import numpy as np\n'), ((7020, 7061), 'numpy.random.randint', 'np.random.randint', (['(2)'], {'size': 'sequence_shape'}), '(2, size=sequence_shape)\n', (7037, 7061), True, 'import numpy as np\n'), ((7103, 7144), 'numpy.random.randint', 'np.random.randint', (['(1)'], {'size': 'sequence_shape'}), '(1, size=sequence_shape)\n', (7120, 7144), True, 'import numpy as np\n'), ((7199, 7236), 'numpy.random.randint', 'np.random.randint', (['(1)'], {'size': 'batch_size'}), '(1, size=batch_size)\n', (7216, 7236), True, 'import numpy as np\n')] |
# -*- coding: utf-8 -*-
# Copyright (c) 2016-2020 by University of Kassel and Fraunhofer Institute for Energy Economics
# and Energy System Technology (IEE), Kassel. All rights reserved.
import numpy as np
import pytest
import pandapower as pp
import pandapower.shortcircuit as sc
@pytest.fixture
def wind_park_example():
net = pp.create_empty_network()
b1 = pp.create_bus(net, vn_kv=110., index=1)
b2 = pp.create_bus(net, vn_kv=110., index=2)
b3 = pp.create_bus(net, vn_kv=110., index=3)
b4 = pp.create_bus(net, vn_kv=110., index=4)
pp.create_ext_grid(net, b1, s_sc_max_mva=20*110*np.sqrt(3), rx_max=0.1)
pp.create_line_from_parameters(net, from_bus=b1, to_bus=b2, length_km=100, r_ohm_per_km=0.120, x_ohm_per_km=0.393, c_nf_per_km=0, max_i_ka=10)
pp.create_line_from_parameters(net, from_bus=b1, to_bus=b3, length_km=50, r_ohm_per_km=0.120, x_ohm_per_km=0.393, c_nf_per_km=0, max_i_ka=10)
pp.create_line_from_parameters(net, from_bus=b2, to_bus=b3, length_km=50, r_ohm_per_km=0.120, x_ohm_per_km=0.393, c_nf_per_km=0, max_i_ka=10)
pp.create_line_from_parameters(net, from_bus=b3, to_bus=b4, length_km=25, r_ohm_per_km=0.120, x_ohm_per_km=0.393, c_nf_per_km=0, max_i_ka=10)
pp.create_sgen(net, b2, p_mw=0.1e3, sn_mva=100)
pp.create_sgen(net, b3, p_mw=0.050e3, sn_mva=50)
pp.create_sgen(net, b4, p_mw=0.050e3, sn_mva=50)
net.sgen["k"] = 1.2
return net
@pytest.fixture
def three_bus_example():
net = pp.create_empty_network()
b1 = pp.create_bus(net, 110)
b2 = pp.create_bus(net, 110)
b3 = pp.create_bus(net, 110)
pp.create_ext_grid(net, b1, s_sc_max_mva=100., s_sc_min_mva=80., rx_min=0.4, rx_max=0.4)
pp.create_line(net, b1, b2, std_type="305-AL1/39-ST1A 110.0" , length_km=20.)
pp.create_line(net, b2, b3, std_type="N2XS(FL)2Y 1x185 RM/35 64/110 kV" , length_km=15.)
net.line["endtemp_degree"] = 80
pp.create_sgen(net, b2, sn_mva=2, p_mw=0, k=1.2)
return net
def test_max_branch_results(three_bus_example):
net = three_bus_example
sc.calc_sc(net, case="max", ip=True, ith=True, branch_results=True)
assert np.allclose(net.res_bus_sc.ikss_ka.values, np.array([0.53746061, 0.50852707, 0.4988896]))
assert np.allclose(net.res_line_sc.ikss_ka.values, np.array([ 0.49593034, 0.4988896 ]))
assert np.allclose(net.res_line_sc.ip_ka.values, np.array([ 0.92787443, 0.9251165 ]))
assert np.allclose(net.res_line_sc.ith_ka.values, np.array([ 0.49811957, 0.50106881]))
def test_min_branch_results(three_bus_example):
net = three_bus_example
sc.calc_sc(net, case="min", ip=True, ith=True, branch_results=True)
assert np.allclose(net.res_bus_sc.ikss_ka.values, np.array([ 0.43248784, 0.41156533, 0.40431286]))
assert np.allclose(net.res_line_sc.ikss_ka.values, np.array([ 0.39171613, 0.40431286]))
assert np.allclose(net.res_line_sc.ip_ka.values, np.array([ 0.72795118, 0.74576565]))
assert np.allclose(net.res_line_sc.ith_ka.values, np.array([ 0.39340278, 0.40605375]))
def test_wind_park(wind_park_example):
net = wind_park_example
sc.calc_sc(net, ip=True)
assert np.isclose(net.res_bus_sc.ikss_ka.at[2], 3.9034, rtol=1e-4)
assert np.isclose(net.res_bus_sc.ip_ka.at[2], 7.3746, rtol=1e-4)
if __name__ == '__main__':
pytest.main(["test_sgen.py"])
| [
"pandapower.create_sgen",
"numpy.isclose",
"numpy.sqrt",
"pandapower.create_ext_grid",
"pandapower.create_empty_network",
"pandapower.create_line_from_parameters",
"pandapower.shortcircuit.calc_sc",
"pytest.main",
"numpy.array",
"pandapower.create_line",
"pandapower.create_bus"
] | [((351, 376), 'pandapower.create_empty_network', 'pp.create_empty_network', ([], {}), '()\n', (374, 376), True, 'import pandapower as pp\n'), ((387, 427), 'pandapower.create_bus', 'pp.create_bus', (['net'], {'vn_kv': '(110.0)', 'index': '(1)'}), '(net, vn_kv=110.0, index=1)\n', (400, 427), True, 'import pandapower as pp\n'), ((437, 477), 'pandapower.create_bus', 'pp.create_bus', (['net'], {'vn_kv': '(110.0)', 'index': '(2)'}), '(net, vn_kv=110.0, index=2)\n', (450, 477), True, 'import pandapower as pp\n'), ((487, 527), 'pandapower.create_bus', 'pp.create_bus', (['net'], {'vn_kv': '(110.0)', 'index': '(3)'}), '(net, vn_kv=110.0, index=3)\n', (500, 527), True, 'import pandapower as pp\n'), ((537, 577), 'pandapower.create_bus', 'pp.create_bus', (['net'], {'vn_kv': '(110.0)', 'index': '(4)'}), '(net, vn_kv=110.0, index=4)\n', (550, 577), True, 'import pandapower as pp\n'), ((661, 806), 'pandapower.create_line_from_parameters', 'pp.create_line_from_parameters', (['net'], {'from_bus': 'b1', 'to_bus': 'b2', 'length_km': '(100)', 'r_ohm_per_km': '(0.12)', 'x_ohm_per_km': '(0.393)', 'c_nf_per_km': '(0)', 'max_i_ka': '(10)'}), '(net, from_bus=b1, to_bus=b2, length_km=100,\n r_ohm_per_km=0.12, x_ohm_per_km=0.393, c_nf_per_km=0, max_i_ka=10)\n', (691, 806), True, 'import pandapower as pp\n'), ((809, 953), 'pandapower.create_line_from_parameters', 'pp.create_line_from_parameters', (['net'], {'from_bus': 'b1', 'to_bus': 'b3', 'length_km': '(50)', 'r_ohm_per_km': '(0.12)', 'x_ohm_per_km': '(0.393)', 'c_nf_per_km': '(0)', 'max_i_ka': '(10)'}), '(net, from_bus=b1, to_bus=b3, length_km=50,\n r_ohm_per_km=0.12, x_ohm_per_km=0.393, c_nf_per_km=0, max_i_ka=10)\n', (839, 953), True, 'import pandapower as pp\n'), ((956, 1100), 'pandapower.create_line_from_parameters', 'pp.create_line_from_parameters', (['net'], {'from_bus': 'b2', 'to_bus': 'b3', 'length_km': '(50)', 'r_ohm_per_km': '(0.12)', 'x_ohm_per_km': '(0.393)', 'c_nf_per_km': '(0)', 'max_i_ka': '(10)'}), '(net, from_bus=b2, to_bus=b3, length_km=50,\n r_ohm_per_km=0.12, x_ohm_per_km=0.393, c_nf_per_km=0, max_i_ka=10)\n', (986, 1100), True, 'import pandapower as pp\n'), ((1103, 1247), 'pandapower.create_line_from_parameters', 'pp.create_line_from_parameters', (['net'], {'from_bus': 'b3', 'to_bus': 'b4', 'length_km': '(25)', 'r_ohm_per_km': '(0.12)', 'x_ohm_per_km': '(0.393)', 'c_nf_per_km': '(0)', 'max_i_ka': '(10)'}), '(net, from_bus=b3, to_bus=b4, length_km=25,\n r_ohm_per_km=0.12, x_ohm_per_km=0.393, c_nf_per_km=0, max_i_ka=10)\n', (1133, 1247), True, 'import pandapower as pp\n'), ((1252, 1299), 'pandapower.create_sgen', 'pp.create_sgen', (['net', 'b2'], {'p_mw': '(100.0)', 'sn_mva': '(100)'}), '(net, b2, p_mw=100.0, sn_mva=100)\n', (1266, 1299), True, 'import pandapower as pp\n'), ((1305, 1350), 'pandapower.create_sgen', 'pp.create_sgen', (['net', 'b3'], {'p_mw': '(50.0)', 'sn_mva': '(50)'}), '(net, b3, p_mw=50.0, sn_mva=50)\n', (1319, 1350), True, 'import pandapower as pp\n'), ((1359, 1404), 'pandapower.create_sgen', 'pp.create_sgen', (['net', 'b4'], {'p_mw': '(50.0)', 'sn_mva': '(50)'}), '(net, b4, p_mw=50.0, sn_mva=50)\n', (1373, 1404), True, 'import pandapower as pp\n'), ((1505, 1530), 'pandapower.create_empty_network', 'pp.create_empty_network', ([], {}), '()\n', (1528, 1530), True, 'import pandapower as pp\n'), ((1541, 1564), 'pandapower.create_bus', 'pp.create_bus', (['net', '(110)'], {}), '(net, 110)\n', (1554, 1564), True, 'import pandapower as pp\n'), ((1575, 1598), 'pandapower.create_bus', 'pp.create_bus', (['net', '(110)'], {}), '(net, 110)\n', (1588, 1598), True, 'import pandapower as pp\n'), ((1609, 1632), 'pandapower.create_bus', 'pp.create_bus', (['net', '(110)'], {}), '(net, 110)\n', (1622, 1632), True, 'import pandapower as pp\n'), ((1640, 1735), 'pandapower.create_ext_grid', 'pp.create_ext_grid', (['net', 'b1'], {'s_sc_max_mva': '(100.0)', 's_sc_min_mva': '(80.0)', 'rx_min': '(0.4)', 'rx_max': '(0.4)'}), '(net, b1, s_sc_max_mva=100.0, s_sc_min_mva=80.0, rx_min=\n 0.4, rx_max=0.4)\n', (1658, 1735), True, 'import pandapower as pp\n'), ((1734, 1811), 'pandapower.create_line', 'pp.create_line', (['net', 'b1', 'b2'], {'std_type': '"""305-AL1/39-ST1A 110.0"""', 'length_km': '(20.0)'}), "(net, b1, b2, std_type='305-AL1/39-ST1A 110.0', length_km=20.0)\n", (1748, 1811), True, 'import pandapower as pp\n'), ((1817, 1909), 'pandapower.create_line', 'pp.create_line', (['net', 'b2', 'b3'], {'std_type': '"""N2XS(FL)2Y 1x185 RM/35 64/110 kV"""', 'length_km': '(15.0)'}), "(net, b2, b3, std_type='N2XS(FL)2Y 1x185 RM/35 64/110 kV',\n length_km=15.0)\n", (1831, 1909), True, 'import pandapower as pp\n'), ((1950, 1998), 'pandapower.create_sgen', 'pp.create_sgen', (['net', 'b2'], {'sn_mva': '(2)', 'p_mw': '(0)', 'k': '(1.2)'}), '(net, b2, sn_mva=2, p_mw=0, k=1.2)\n', (1964, 1998), True, 'import pandapower as pp\n'), ((2100, 2167), 'pandapower.shortcircuit.calc_sc', 'sc.calc_sc', (['net'], {'case': '"""max"""', 'ip': '(True)', 'ith': '(True)', 'branch_results': '(True)'}), "(net, case='max', ip=True, ith=True, branch_results=True)\n", (2110, 2167), True, 'import pandapower.shortcircuit as sc\n'), ((2634, 2701), 'pandapower.shortcircuit.calc_sc', 'sc.calc_sc', (['net'], {'case': '"""min"""', 'ip': '(True)', 'ith': '(True)', 'branch_results': '(True)'}), "(net, case='min', ip=True, ith=True, branch_results=True)\n", (2644, 2701), True, 'import pandapower.shortcircuit as sc\n'), ((3163, 3187), 'pandapower.shortcircuit.calc_sc', 'sc.calc_sc', (['net'], {'ip': '(True)'}), '(net, ip=True)\n', (3173, 3187), True, 'import pandapower.shortcircuit as sc\n'), ((3200, 3261), 'numpy.isclose', 'np.isclose', (['net.res_bus_sc.ikss_ka.at[2]', '(3.9034)'], {'rtol': '(0.0001)'}), '(net.res_bus_sc.ikss_ka.at[2], 3.9034, rtol=0.0001)\n', (3210, 3261), True, 'import numpy as np\n'), ((3272, 3331), 'numpy.isclose', 'np.isclose', (['net.res_bus_sc.ip_ka.at[2]', '(7.3746)'], {'rtol': '(0.0001)'}), '(net.res_bus_sc.ip_ka.at[2], 7.3746, rtol=0.0001)\n', (3282, 3331), True, 'import numpy as np\n'), ((3365, 3394), 'pytest.main', 'pytest.main', (["['test_sgen.py']"], {}), "(['test_sgen.py'])\n", (3376, 3394), False, 'import pytest\n'), ((2223, 2268), 'numpy.array', 'np.array', (['[0.53746061, 0.50852707, 0.4988896]'], {}), '([0.53746061, 0.50852707, 0.4988896])\n', (2231, 2268), True, 'import numpy as np\n'), ((2326, 2359), 'numpy.array', 'np.array', (['[0.49593034, 0.4988896]'], {}), '([0.49593034, 0.4988896])\n', (2334, 2359), True, 'import numpy as np\n'), ((2418, 2451), 'numpy.array', 'np.array', (['[0.92787443, 0.9251165]'], {}), '([0.92787443, 0.9251165])\n', (2426, 2451), True, 'import numpy as np\n'), ((2511, 2545), 'numpy.array', 'np.array', (['[0.49811957, 0.50106881]'], {}), '([0.49811957, 0.50106881])\n', (2519, 2545), True, 'import numpy as np\n'), ((2757, 2803), 'numpy.array', 'np.array', (['[0.43248784, 0.41156533, 0.40431286]'], {}), '([0.43248784, 0.41156533, 0.40431286])\n', (2765, 2803), True, 'import numpy as np\n'), ((2864, 2898), 'numpy.array', 'np.array', (['[0.39171613, 0.40431286]'], {}), '([0.39171613, 0.40431286])\n', (2872, 2898), True, 'import numpy as np\n'), ((2956, 2990), 'numpy.array', 'np.array', (['[0.72795118, 0.74576565]'], {}), '([0.72795118, 0.74576565])\n', (2964, 2990), True, 'import numpy as np\n'), ((3049, 3083), 'numpy.array', 'np.array', (['[0.39340278, 0.40605375]'], {}), '([0.39340278, 0.40605375])\n', (3057, 3083), True, 'import numpy as np\n'), ((630, 640), 'numpy.sqrt', 'np.sqrt', (['(3)'], {}), '(3)\n', (637, 640), True, 'import numpy as np\n')] |
import numpy as np
import os
from PIL import Image, ImageDraw
from tqdm import tqdm
from Detection.AdvancedEAST import cfg
from Detection.AdvancedEAST.preprocess import preprocess_single_image,preprocess_no_cfg
def point_inside_of_quad(px, py, quad_xy_list, p_min, p_max):
if (p_min[0] <= px <= p_max[0]) and (p_min[1] <= py <= p_max[1]):
xy_list = np.zeros((4, 2))
xy_list[:3, :] = quad_xy_list[1:4, :] - quad_xy_list[:3, :]
xy_list[3] = quad_xy_list[0, :] - quad_xy_list[3, :]
yx_list = np.zeros((4, 2))
yx_list[:, :] = quad_xy_list[:, -1:-3:-1]
a = xy_list * ([py, px] - yx_list)
b = a[:, 0] - a[:, 1]
if np.amin(b) >= 0 or np.amax(b) <= 0:
return True
else:
return False
else:
return False
def point_inside_of_nth_quad(px, py, xy_list, shrink_1, long_edge):
nth = -1
vs = [[[0, 0, 3, 3, 0], [1, 1, 2, 2, 1]],
[[0, 0, 1, 1, 0], [2, 2, 3, 3, 2]]]
for ith in range(2):
quad_xy_list = np.concatenate((
np.reshape(xy_list[vs[long_edge][ith][0]], (1, 2)),
np.reshape(shrink_1[vs[long_edge][ith][1]], (1, 2)),
np.reshape(shrink_1[vs[long_edge][ith][2]], (1, 2)),
np.reshape(xy_list[vs[long_edge][ith][3]], (1, 2))), axis=0)
p_min = np.amin(quad_xy_list, axis=0)
p_max = np.amax(quad_xy_list, axis=0)
if point_inside_of_quad(px, py, quad_xy_list, p_min, p_max):
if nth == -1:
nth = ith
else:
nth = -1
break
return nth
def shrink(xy_list, ratio=cfg.shrink_ratio):
if ratio == 0.0:
return xy_list, xy_list
diff_1to3 = xy_list[:3, :] - xy_list[1:4, :]
diff_4 = xy_list[3:4, :] - xy_list[0:1, :]
diff = np.concatenate((diff_1to3, diff_4), axis=0)
dis = np.sqrt(np.sum(np.square(diff), axis=-1))
# determine which are long or short edges
long_edge = int(np.argmax(np.sum(np.reshape(dis, (2, 2)), axis=0)))
short_edge = 1 - long_edge
# cal r length array
r = [np.minimum(dis[i], dis[(i + 1) % 4]) for i in range(4)]
# cal theta array
diff_abs = np.abs(diff)
diff_abs[:, 0] += cfg.epsilon
theta = np.arctan(diff_abs[:, 1] / diff_abs[:, 0])
# shrink two long edges
temp_new_xy_list = np.copy(xy_list)
shrink_edge(xy_list, temp_new_xy_list, long_edge, r, theta, ratio)
shrink_edge(xy_list, temp_new_xy_list, long_edge + 2, r, theta, ratio)
# shrink two short edges
new_xy_list = np.copy(temp_new_xy_list)
shrink_edge(temp_new_xy_list, new_xy_list, short_edge, r, theta, ratio)
shrink_edge(temp_new_xy_list, new_xy_list, short_edge + 2, r, theta, ratio)
return temp_new_xy_list, new_xy_list, long_edge
def shrink_edge(xy_list, new_xy_list, edge, r, theta, ratio=cfg.shrink_ratio):
if ratio == 0.0:
return
start_point = edge
end_point = (edge + 1) % 4
long_start_sign_x = np.sign(
xy_list[end_point, 0] - xy_list[start_point, 0])
new_xy_list[start_point, 0] = \
xy_list[start_point, 0] + \
long_start_sign_x * ratio * r[start_point] * np.cos(theta[start_point])
long_start_sign_y = np.sign(
xy_list[end_point, 1] - xy_list[start_point, 1])
new_xy_list[start_point, 1] = \
xy_list[start_point, 1] + \
long_start_sign_y * ratio * r[start_point] * np.sin(theta[start_point])
# long edge one, end point
long_end_sign_x = -1 * long_start_sign_x
new_xy_list[end_point, 0] = \
xy_list[end_point, 0] + \
long_end_sign_x * ratio * r[end_point] * np.cos(theta[start_point])
long_end_sign_y = -1 * long_start_sign_y
new_xy_list[end_point, 1] = \
xy_list[end_point, 1] + \
long_end_sign_y * ratio * r[end_point] * np.sin(theta[start_point])
def process_label(data_dir=cfg.data_dir):
with open(os.path.join(data_dir, cfg.val_fname), 'r') as f_val:
f_list = f_val.readlines()
with open(os.path.join(data_dir, cfg.train_fname), 'r') as f_train:
f_list.extend(f_train.readlines())
for line, _ in zip(f_list, tqdm(range(len(f_list)))):
line_cols = str(line).strip('\n').split(',')
img_name, width, height = \
line_cols[0].strip(), int(line_cols[1].strip()), \
int(line_cols[2].strip())
gt = np.zeros((height // cfg.pixel_size, width // cfg.pixel_size, 7))
train_label_dir = os.path.join(data_dir, cfg.train_label_dir_name)
xy_list_array = np.load(os.path.join(train_label_dir,
img_name.replace('.jpg','.npy')))
train_image_dir = os.path.join(data_dir, cfg.train_image_dir_name)
with Image.open(os.path.join(train_image_dir, img_name)) as im:
draw = ImageDraw.Draw(im)
for xy_list in xy_list_array:
_, shrink_xy_list, _ = shrink(xy_list, cfg.shrink_ratio)
shrink_1, _, long_edge = shrink(xy_list, cfg.shrink_side_ratio)
p_min = np.amin(shrink_xy_list, axis=0)
p_max = np.amax(shrink_xy_list, axis=0)
# floor of the float
ji_min = (p_min / cfg.pixel_size - 0.5).astype(int) - 1
# +1 for ceil of the float and +1 for include the end
ji_max = (p_max / cfg.pixel_size - 0.5).astype(int) + 3
imin = np.maximum(0, ji_min[1])
imax = np.minimum(height // cfg.pixel_size, ji_max[1])
jmin = np.maximum(0, ji_min[0])
jmax = np.minimum(width // cfg.pixel_size, ji_max[0])
for i in range(imin, imax):
for j in range(jmin, jmax):
px = (j + 0.5) * cfg.pixel_size
py = (i + 0.5) * cfg.pixel_size
if point_inside_of_quad(px, py,
shrink_xy_list, p_min, p_max):
gt[i, j, 0] = 1
line_width, line_color = 1, 'red'
ith = point_inside_of_nth_quad(px, py,
xy_list,
shrink_1,
long_edge)
vs = [[[3, 0], [1, 2]], [[0, 1], [2, 3]]]
if ith in range(2):
gt[i, j, 1] = 1
if ith == 0:
line_width, line_color = 2, 'yellow'
else:
line_width, line_color = 2, 'green'
gt[i, j, 2:3] = ith
gt[i, j, 3:5] = \
xy_list[vs[long_edge][ith][0]] - [px, py]
gt[i, j, 5:] = \
xy_list[vs[long_edge][ith][1]] - [px, py]
draw.line([(px - 0.5 * cfg.pixel_size,
py - 0.5 * cfg.pixel_size),
(px + 0.5 * cfg.pixel_size,
py - 0.5 * cfg.pixel_size),
(px + 0.5 * cfg.pixel_size,
py + 0.5 * cfg.pixel_size),
(px - 0.5 * cfg.pixel_size,
py + 0.5 * cfg.pixel_size),
(px - 0.5 * cfg.pixel_size,
py - 0.5 * cfg.pixel_size)],
width=line_width, fill=line_color)
act_image_dir = os.path.join(cfg.data_dir,
cfg.show_act_image_dir_name)
if cfg.draw_act_quad:
im.save(os.path.join(act_image_dir, img_name))
train_label_dir = os.path.join(data_dir, cfg.train_label_dir_name)
np.save(os.path.join(train_label_dir,
img_name.replace('.jpg', '_gt.npy')), gt)
def process_label_no_cfg(data_dir,shape):
print('start preprocessing......')
preprocess_no_cfg(data_dir,shape)
print('*'*100)
print('*' * 100)
print('start process labels......')
with open(os.path.join(data_dir, cfg.val_fname), 'r') as f_val:
f_list = f_val.readlines()
with open(os.path.join(data_dir, cfg.train_fname), 'r') as f_train:
f_list.extend(f_train.readlines())
for line, _ in zip(f_list, tqdm(range(len(f_list)))):
line_cols = str(line).strip('\n').split(',')
img_name, width, height = \
line_cols[0].strip(), shape, shape
gt = np.zeros((height // cfg.pixel_size, width // cfg.pixel_size, 7))
train_label_dir = os.path.join(data_dir, cfg.train_label_dir_name)
xy_list_array = np.load(os.path.join(train_label_dir,
img_name.replace('.jpg','.npy')))
train_image_dir = os.path.join(data_dir, cfg.train_image_dir_name)
with Image.open(os.path.join(train_image_dir, img_name)) as im:
draw = ImageDraw.Draw(im)
for xy_list in xy_list_array:
_, shrink_xy_list, _ = shrink(xy_list, cfg.shrink_ratio)
shrink_1, _, long_edge = shrink(xy_list, cfg.shrink_side_ratio)
p_min = np.amin(shrink_xy_list, axis=0)
p_max = np.amax(shrink_xy_list, axis=0)
# floor of the float
ji_min = (p_min / cfg.pixel_size - 0.5).astype(int) - 1
# +1 for ceil of the float and +1 for include the end
ji_max = (p_max / cfg.pixel_size - 0.5).astype(int) + 3
imin = np.maximum(0, ji_min[1])
imax = np.minimum(height // cfg.pixel_size, ji_max[1])
jmin = np.maximum(0, ji_min[0])
jmax = np.minimum(width // cfg.pixel_size, ji_max[0])
for i in range(imin, imax):
for j in range(jmin, jmax):
px = (j + 0.5) * cfg.pixel_size
py = (i + 0.5) * cfg.pixel_size
if point_inside_of_quad(px, py,
shrink_xy_list, p_min, p_max):
gt[i, j, 0] = 1
line_width, line_color = 1, 'red'
ith = point_inside_of_nth_quad(px, py,
xy_list,
shrink_1,
long_edge)
vs = [[[3, 0], [1, 2]], [[0, 1], [2, 3]]]
if ith in range(2):
gt[i, j, 1] = 1
if ith == 0:
line_width, line_color = 2, 'yellow'
else:
line_width, line_color = 2, 'green'
gt[i, j, 2:3] = ith
gt[i, j, 3:5] = \
xy_list[vs[long_edge][ith][0]] - [px, py]
gt[i, j, 5:] = \
xy_list[vs[long_edge][ith][1]] - [px, py]
draw.line([(px - 0.5 * cfg.pixel_size,
py - 0.5 * cfg.pixel_size),
(px + 0.5 * cfg.pixel_size,
py - 0.5 * cfg.pixel_size),
(px + 0.5 * cfg.pixel_size,
py + 0.5 * cfg.pixel_size),
(px - 0.5 * cfg.pixel_size,
py + 0.5 * cfg.pixel_size),
(px - 0.5 * cfg.pixel_size,
py - 0.5 * cfg.pixel_size)],
width=line_width, fill=line_color)
act_image_dir = os.path.join(cfg.data_dir,
cfg.show_act_image_dir_name)
if cfg.draw_act_quad:
im.save(os.path.join(act_image_dir, img_name))
train_label_dir = os.path.join(data_dir, cfg.train_label_dir_name)
np.save(os.path.join(train_label_dir,
img_name.replace('.jpg', '_gt.npy')), gt)
print(os.path.join(train_label_dir,
img_name.replace('.jpg', '_gt.npy'))+' Shape is{} Done!'.format(gt.shape))
def process_label_single_image(img_name,shape):
width,height=shape,shape
gt = np.zeros((height // cfg.pixel_size, width // cfg.pixel_size, 7))
resized_img,xy_list_array=preprocess_single_image(img_name)
for xy_list in xy_list_array:
_, shrink_xy_list, _ = shrink(xy_list, cfg.shrink_ratio)
shrink_1, _, long_edge = shrink(xy_list, cfg.shrink_side_ratio)
p_min = np.amin(shrink_xy_list, axis=0)
p_max = np.amax(shrink_xy_list, axis=0)
# floor of the float
ji_min = (p_min / cfg.pixel_size - 0.5).astype(int) - 1
# +1 for ceil of the float and +1 for include the end
ji_max = (p_max / cfg.pixel_size - 0.5).astype(int) + 3
imin = np.maximum(0, ji_min[1])
imax = np.minimum(height // cfg.pixel_size, ji_max[1])
jmin = np.maximum(0, ji_min[0])
jmax = np.minimum(width // cfg.pixel_size, ji_max[0])
for i in range(imin, imax):
for j in range(jmin, jmax):
px = (j + 0.5) * cfg.pixel_size
py = (i + 0.5) * cfg.pixel_size
if point_inside_of_quad(px, py,
shrink_xy_list, p_min, p_max):
gt[i, j, 0] = 1
line_width, line_color = 1, 'red'
ith = point_inside_of_nth_quad(px, py,
xy_list,
shrink_1,
long_edge)
vs = [[[3, 0], [1, 2]], [[0, 1], [2, 3]]]
if ith in range(2):
gt[i, j, 1] = 1
if ith == 0:
line_width, line_color = 2, 'yellow'
else:
line_width, line_color = 2, 'green'
gt[i, j, 2:3] = ith
gt[i, j, 3:5] = \
xy_list[vs[long_edge][ith][0]] - [px, py]
gt[i, j, 5:] = \
xy_list[vs[long_edge][ith][1]] - [px, py]
return resized_img,gt
if __name__ == '__main__':
process_label_no_cfg('E:\py_projects\data_new\data_new\data',256)
| [
"numpy.abs",
"numpy.copy",
"numpy.reshape",
"numpy.amin",
"numpy.minimum",
"numpy.sin",
"os.path.join",
"numpy.square",
"numpy.zeros",
"PIL.ImageDraw.Draw",
"numpy.sign",
"numpy.concatenate",
"numpy.cos",
"numpy.maximum",
"Detection.AdvancedEAST.preprocess.preprocess_no_cfg",
"numpy.am... | [((1814, 1857), 'numpy.concatenate', 'np.concatenate', (['(diff_1to3, diff_4)'], {'axis': '(0)'}), '((diff_1to3, diff_4), axis=0)\n', (1828, 1857), True, 'import numpy as np\n'), ((2186, 2198), 'numpy.abs', 'np.abs', (['diff'], {}), '(diff)\n', (2192, 2198), True, 'import numpy as np\n'), ((2245, 2287), 'numpy.arctan', 'np.arctan', (['(diff_abs[:, 1] / diff_abs[:, 0])'], {}), '(diff_abs[:, 1] / diff_abs[:, 0])\n', (2254, 2287), True, 'import numpy as np\n'), ((2339, 2355), 'numpy.copy', 'np.copy', (['xy_list'], {}), '(xy_list)\n', (2346, 2355), True, 'import numpy as np\n'), ((2549, 2574), 'numpy.copy', 'np.copy', (['temp_new_xy_list'], {}), '(temp_new_xy_list)\n', (2556, 2574), True, 'import numpy as np\n'), ((2978, 3034), 'numpy.sign', 'np.sign', (['(xy_list[end_point, 0] - xy_list[start_point, 0])'], {}), '(xy_list[end_point, 0] - xy_list[start_point, 0])\n', (2985, 3034), True, 'import numpy as np\n'), ((3220, 3276), 'numpy.sign', 'np.sign', (['(xy_list[end_point, 1] - xy_list[start_point, 1])'], {}), '(xy_list[end_point, 1] - xy_list[start_point, 1])\n', (3227, 3276), True, 'import numpy as np\n'), ((8300, 8334), 'Detection.AdvancedEAST.preprocess.preprocess_no_cfg', 'preprocess_no_cfg', (['data_dir', 'shape'], {}), '(data_dir, shape)\n', (8317, 8334), False, 'from Detection.AdvancedEAST.preprocess import preprocess_single_image, preprocess_no_cfg\n'), ((12918, 12982), 'numpy.zeros', 'np.zeros', (['(height // cfg.pixel_size, width // cfg.pixel_size, 7)'], {}), '((height // cfg.pixel_size, width // cfg.pixel_size, 7))\n', (12926, 12982), True, 'import numpy as np\n'), ((13013, 13046), 'Detection.AdvancedEAST.preprocess.preprocess_single_image', 'preprocess_single_image', (['img_name'], {}), '(img_name)\n', (13036, 13046), False, 'from Detection.AdvancedEAST.preprocess import preprocess_single_image, preprocess_no_cfg\n'), ((362, 378), 'numpy.zeros', 'np.zeros', (['(4, 2)'], {}), '((4, 2))\n', (370, 378), True, 'import numpy as np\n'), ((526, 542), 'numpy.zeros', 'np.zeros', (['(4, 2)'], {}), '((4, 2))\n', (534, 542), True, 'import numpy as np\n'), ((1330, 1359), 'numpy.amin', 'np.amin', (['quad_xy_list'], {'axis': '(0)'}), '(quad_xy_list, axis=0)\n', (1337, 1359), True, 'import numpy as np\n'), ((1376, 1405), 'numpy.amax', 'np.amax', (['quad_xy_list'], {'axis': '(0)'}), '(quad_xy_list, axis=0)\n', (1383, 1405), True, 'import numpy as np\n'), ((2093, 2129), 'numpy.minimum', 'np.minimum', (['dis[i]', 'dis[(i + 1) % 4]'], {}), '(dis[i], dis[(i + 1) % 4])\n', (2103, 2129), True, 'import numpy as np\n'), ((4370, 4434), 'numpy.zeros', 'np.zeros', (['(height // cfg.pixel_size, width // cfg.pixel_size, 7)'], {}), '((height // cfg.pixel_size, width // cfg.pixel_size, 7))\n', (4378, 4434), True, 'import numpy as np\n'), ((4461, 4509), 'os.path.join', 'os.path.join', (['data_dir', 'cfg.train_label_dir_name'], {}), '(data_dir, cfg.train_label_dir_name)\n', (4473, 4509), False, 'import os\n'), ((4677, 4725), 'os.path.join', 'os.path.join', (['data_dir', 'cfg.train_image_dir_name'], {}), '(data_dir, cfg.train_image_dir_name)\n', (4689, 4725), False, 'import os\n'), ((8048, 8096), 'os.path.join', 'os.path.join', (['data_dir', 'cfg.train_label_dir_name'], {}), '(data_dir, cfg.train_label_dir_name)\n', (8060, 8096), False, 'import os\n'), ((8839, 8903), 'numpy.zeros', 'np.zeros', (['(height // cfg.pixel_size, width // cfg.pixel_size, 7)'], {}), '((height // cfg.pixel_size, width // cfg.pixel_size, 7))\n', (8847, 8903), True, 'import numpy as np\n'), ((8930, 8978), 'os.path.join', 'os.path.join', (['data_dir', 'cfg.train_label_dir_name'], {}), '(data_dir, cfg.train_label_dir_name)\n', (8942, 8978), False, 'import os\n'), ((9146, 9194), 'os.path.join', 'os.path.join', (['data_dir', 'cfg.train_image_dir_name'], {}), '(data_dir, cfg.train_image_dir_name)\n', (9158, 9194), False, 'import os\n'), ((12517, 12565), 'os.path.join', 'os.path.join', (['data_dir', 'cfg.train_label_dir_name'], {}), '(data_dir, cfg.train_label_dir_name)\n', (12529, 12565), False, 'import os\n'), ((13234, 13265), 'numpy.amin', 'np.amin', (['shrink_xy_list'], {'axis': '(0)'}), '(shrink_xy_list, axis=0)\n', (13241, 13265), True, 'import numpy as np\n'), ((13282, 13313), 'numpy.amax', 'np.amax', (['shrink_xy_list'], {'axis': '(0)'}), '(shrink_xy_list, axis=0)\n', (13289, 13313), True, 'import numpy as np\n'), ((13548, 13572), 'numpy.maximum', 'np.maximum', (['(0)', 'ji_min[1]'], {}), '(0, ji_min[1])\n', (13558, 13572), True, 'import numpy as np\n'), ((13588, 13635), 'numpy.minimum', 'np.minimum', (['(height // cfg.pixel_size)', 'ji_max[1]'], {}), '(height // cfg.pixel_size, ji_max[1])\n', (13598, 13635), True, 'import numpy as np\n'), ((13651, 13675), 'numpy.maximum', 'np.maximum', (['(0)', 'ji_min[0]'], {}), '(0, ji_min[0])\n', (13661, 13675), True, 'import numpy as np\n'), ((13691, 13737), 'numpy.minimum', 'np.minimum', (['(width // cfg.pixel_size)', 'ji_max[0]'], {}), '(width // cfg.pixel_size, ji_max[0])\n', (13701, 13737), True, 'import numpy as np\n'), ((1883, 1898), 'numpy.square', 'np.square', (['diff'], {}), '(diff)\n', (1892, 1898), True, 'import numpy as np\n'), ((3169, 3195), 'numpy.cos', 'np.cos', (['theta[start_point]'], {}), '(theta[start_point])\n', (3175, 3195), True, 'import numpy as np\n'), ((3411, 3437), 'numpy.sin', 'np.sin', (['theta[start_point]'], {}), '(theta[start_point])\n', (3417, 3437), True, 'import numpy as np\n'), ((3631, 3657), 'numpy.cos', 'np.cos', (['theta[start_point]'], {}), '(theta[start_point])\n', (3637, 3657), True, 'import numpy as np\n'), ((3820, 3846), 'numpy.sin', 'np.sin', (['theta[start_point]'], {}), '(theta[start_point])\n', (3826, 3846), True, 'import numpy as np\n'), ((3905, 3942), 'os.path.join', 'os.path.join', (['data_dir', 'cfg.val_fname'], {}), '(data_dir, cfg.val_fname)\n', (3917, 3942), False, 'import os\n'), ((4008, 4047), 'os.path.join', 'os.path.join', (['data_dir', 'cfg.train_fname'], {}), '(data_dir, cfg.train_fname)\n', (4020, 4047), False, 'import os\n'), ((4817, 4835), 'PIL.ImageDraw.Draw', 'ImageDraw.Draw', (['im'], {}), '(im)\n', (4831, 4835), False, 'from PIL import Image, ImageDraw\n'), ((7828, 7883), 'os.path.join', 'os.path.join', (['cfg.data_dir', 'cfg.show_act_image_dir_name'], {}), '(cfg.data_dir, cfg.show_act_image_dir_name)\n', (7840, 7883), False, 'import os\n'), ((8428, 8465), 'os.path.join', 'os.path.join', (['data_dir', 'cfg.val_fname'], {}), '(data_dir, cfg.val_fname)\n', (8440, 8465), False, 'import os\n'), ((8531, 8570), 'os.path.join', 'os.path.join', (['data_dir', 'cfg.train_fname'], {}), '(data_dir, cfg.train_fname)\n', (8543, 8570), False, 'import os\n'), ((9286, 9304), 'PIL.ImageDraw.Draw', 'ImageDraw.Draw', (['im'], {}), '(im)\n', (9300, 9304), False, 'from PIL import Image, ImageDraw\n'), ((12297, 12352), 'os.path.join', 'os.path.join', (['cfg.data_dir', 'cfg.show_act_image_dir_name'], {}), '(cfg.data_dir, cfg.show_act_image_dir_name)\n', (12309, 12352), False, 'import os\n'), ((677, 687), 'numpy.amin', 'np.amin', (['b'], {}), '(b)\n', (684, 687), True, 'import numpy as np\n'), ((696, 706), 'numpy.amax', 'np.amax', (['b'], {}), '(b)\n', (703, 706), True, 'import numpy as np\n'), ((1059, 1109), 'numpy.reshape', 'np.reshape', (['xy_list[vs[long_edge][ith][0]]', '(1, 2)'], {}), '(xy_list[vs[long_edge][ith][0]], (1, 2))\n', (1069, 1109), True, 'import numpy as np\n'), ((1123, 1174), 'numpy.reshape', 'np.reshape', (['shrink_1[vs[long_edge][ith][1]]', '(1, 2)'], {}), '(shrink_1[vs[long_edge][ith][1]], (1, 2))\n', (1133, 1174), True, 'import numpy as np\n'), ((1188, 1239), 'numpy.reshape', 'np.reshape', (['shrink_1[vs[long_edge][ith][2]]', '(1, 2)'], {}), '(shrink_1[vs[long_edge][ith][2]], (1, 2))\n', (1198, 1239), True, 'import numpy as np\n'), ((1253, 1303), 'numpy.reshape', 'np.reshape', (['xy_list[vs[long_edge][ith][3]]', '(1, 2)'], {}), '(xy_list[vs[long_edge][ith][3]], (1, 2))\n', (1263, 1303), True, 'import numpy as np\n'), ((1993, 2016), 'numpy.reshape', 'np.reshape', (['dis', '(2, 2)'], {}), '(dis, (2, 2))\n', (2003, 2016), True, 'import numpy as np\n'), ((4750, 4789), 'os.path.join', 'os.path.join', (['train_image_dir', 'img_name'], {}), '(train_image_dir, img_name)\n', (4762, 4789), False, 'import os\n'), ((5055, 5086), 'numpy.amin', 'np.amin', (['shrink_xy_list'], {'axis': '(0)'}), '(shrink_xy_list, axis=0)\n', (5062, 5086), True, 'import numpy as np\n'), ((5111, 5142), 'numpy.amax', 'np.amax', (['shrink_xy_list'], {'axis': '(0)'}), '(shrink_xy_list, axis=0)\n', (5118, 5142), True, 'import numpy as np\n'), ((5417, 5441), 'numpy.maximum', 'np.maximum', (['(0)', 'ji_min[1]'], {}), '(0, ji_min[1])\n', (5427, 5441), True, 'import numpy as np\n'), ((5465, 5512), 'numpy.minimum', 'np.minimum', (['(height // cfg.pixel_size)', 'ji_max[1]'], {}), '(height // cfg.pixel_size, ji_max[1])\n', (5475, 5512), True, 'import numpy as np\n'), ((5536, 5560), 'numpy.maximum', 'np.maximum', (['(0)', 'ji_min[0]'], {}), '(0, ji_min[0])\n', (5546, 5560), True, 'import numpy as np\n'), ((5584, 5630), 'numpy.minimum', 'np.minimum', (['(width // cfg.pixel_size)', 'ji_max[0]'], {}), '(width // cfg.pixel_size, ji_max[0])\n', (5594, 5630), True, 'import numpy as np\n'), ((9219, 9258), 'os.path.join', 'os.path.join', (['train_image_dir', 'img_name'], {}), '(train_image_dir, img_name)\n', (9231, 9258), False, 'import os\n'), ((9524, 9555), 'numpy.amin', 'np.amin', (['shrink_xy_list'], {'axis': '(0)'}), '(shrink_xy_list, axis=0)\n', (9531, 9555), True, 'import numpy as np\n'), ((9580, 9611), 'numpy.amax', 'np.amax', (['shrink_xy_list'], {'axis': '(0)'}), '(shrink_xy_list, axis=0)\n', (9587, 9611), True, 'import numpy as np\n'), ((9886, 9910), 'numpy.maximum', 'np.maximum', (['(0)', 'ji_min[1]'], {}), '(0, ji_min[1])\n', (9896, 9910), True, 'import numpy as np\n'), ((9934, 9981), 'numpy.minimum', 'np.minimum', (['(height // cfg.pixel_size)', 'ji_max[1]'], {}), '(height // cfg.pixel_size, ji_max[1])\n', (9944, 9981), True, 'import numpy as np\n'), ((10005, 10029), 'numpy.maximum', 'np.maximum', (['(0)', 'ji_min[0]'], {}), '(0, ji_min[0])\n', (10015, 10029), True, 'import numpy as np\n'), ((10053, 10099), 'numpy.minimum', 'np.minimum', (['(width // cfg.pixel_size)', 'ji_max[0]'], {}), '(width // cfg.pixel_size, ji_max[0])\n', (10063, 10099), True, 'import numpy as np\n'), ((7983, 8020), 'os.path.join', 'os.path.join', (['act_image_dir', 'img_name'], {}), '(act_image_dir, img_name)\n', (7995, 8020), False, 'import os\n'), ((12452, 12489), 'os.path.join', 'os.path.join', (['act_image_dir', 'img_name'], {}), '(act_image_dir, img_name)\n', (12464, 12489), False, 'import os\n')] |
'''custom colormaps for use with matplotlib scatter and imshow'''
import matplotlib.colors as co
import numpy as np
def name2color(name):
'''
Return the 3-element RGB array of a given color name.
'''
return co.hex2color(co.cnames[name])
def one2another(bottom='white', top='red', alphabottom=1.0, alphatop=1.0, N=256):
'''
Create a cmap that goes smoothly (linearly in RGBA) from "bottom" to "top".
'''
rgb_bottom, rgb_top = name2color(bottom), name2color(top)
r = np.linspace(rgb_bottom[0],rgb_top[0],N)
g = np.linspace(rgb_bottom[1],rgb_top[1],N)
b = np.linspace(rgb_bottom[2],rgb_top[2],N)
a = np.linspace(alphabottom, alphatop,N)
colors = np.transpose(np.vstack([r,g,b,a]))
cmap = co.ListedColormap(colors, name='{bottom}2{top}'.format(**locals()))
return cmap
if __name__ == '__main__':
import matplotlib.pyplot as plt
print("This is a test of colormaps with one2another().")
fascinating = one2another('seagreen', 'indigo')
x = np.arange(100)
y = x + np.random.normal(0, 1, 100)
plt.scatter(x, y, s=100, c=x, cmap=fascinating, vmin=0, vmax=100)
plt.colorbar()
plt.show()
| [
"numpy.random.normal",
"matplotlib.pyplot.colorbar",
"numpy.linspace",
"numpy.vstack",
"matplotlib.pyplot.scatter",
"matplotlib.colors.hex2color",
"numpy.arange",
"matplotlib.pyplot.show"
] | [((212, 241), 'matplotlib.colors.hex2color', 'co.hex2color', (['co.cnames[name]'], {}), '(co.cnames[name])\n', (224, 241), True, 'import matplotlib.colors as co\n'), ((476, 517), 'numpy.linspace', 'np.linspace', (['rgb_bottom[0]', 'rgb_top[0]', 'N'], {}), '(rgb_bottom[0], rgb_top[0], N)\n', (487, 517), True, 'import numpy as np\n'), ((521, 562), 'numpy.linspace', 'np.linspace', (['rgb_bottom[1]', 'rgb_top[1]', 'N'], {}), '(rgb_bottom[1], rgb_top[1], N)\n', (532, 562), True, 'import numpy as np\n'), ((566, 607), 'numpy.linspace', 'np.linspace', (['rgb_bottom[2]', 'rgb_top[2]', 'N'], {}), '(rgb_bottom[2], rgb_top[2], N)\n', (577, 607), True, 'import numpy as np\n'), ((611, 648), 'numpy.linspace', 'np.linspace', (['alphabottom', 'alphatop', 'N'], {}), '(alphabottom, alphatop, N)\n', (622, 648), True, 'import numpy as np\n'), ((955, 969), 'numpy.arange', 'np.arange', (['(100)'], {}), '(100)\n', (964, 969), True, 'import numpy as np\n'), ((1008, 1073), 'matplotlib.pyplot.scatter', 'plt.scatter', (['x', 'y'], {'s': '(100)', 'c': 'x', 'cmap': 'fascinating', 'vmin': '(0)', 'vmax': '(100)'}), '(x, y, s=100, c=x, cmap=fascinating, vmin=0, vmax=100)\n', (1019, 1073), True, 'import matplotlib.pyplot as plt\n'), ((1075, 1089), 'matplotlib.pyplot.colorbar', 'plt.colorbar', ([], {}), '()\n', (1087, 1089), True, 'import matplotlib.pyplot as plt\n'), ((1091, 1101), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1099, 1101), True, 'import matplotlib.pyplot as plt\n'), ((671, 694), 'numpy.vstack', 'np.vstack', (['[r, g, b, a]'], {}), '([r, g, b, a])\n', (680, 694), True, 'import numpy as np\n'), ((979, 1006), 'numpy.random.normal', 'np.random.normal', (['(0)', '(1)', '(100)'], {}), '(0, 1, 100)\n', (995, 1006), True, 'import numpy as np\n')] |
from os.path import join
import argparse
import numpy as np
import torch
import torch.nn.functional as F
from torch.autograd import Variable
from pt.common.settings import results_path, TRAIN, VAL
from pt.common.utils import (
safe_makedirs, append_log, setup_log)
from pt.common.optimizers import get_optimizer, SGD
from pt.recog.data.factory import (
get_data_loader, MNIST, DEFAULT, NORMALIZE)
from pt.recog.models.factory import make_model
from pt.recog.models.mini import MINI
from pt.recog.tasks.utils import add_common_args
TRAIN_MODEL = 'train_model'
def load_weights(namespace):
train_model_path = join(results_path, namespace, TRAIN_MODEL)
best_model_path = join(train_model_path, 'best_model')
return torch.load(best_model_path)
def load_log(namespace):
train_model_path = join(results_path, namespace, TRAIN_MODEL)
log_path = join(train_model_path, 'log.csv')
return np.genfromtxt(log_path, delimiter=',', skip_header=1)
def train_epoch(epoch, train_loader, model, optimizer, cuda, log_interval,
nsamples):
model.train()
if nsamples is None:
nsamples = len(train_loader.dataset)
sample_count = 0
for batch_idx, (x, y) in enumerate(train_loader, start=1):
if cuda:
x, y = x.cuda(), y.cuda()
x, y = Variable(x), Variable(y)
if sample_count + len(x) > nsamples:
extra_samples = sample_count - nsamples
samples_to_keep = len(x) - extra_samples
x = x.narrow(0, 0, samples_to_keep)
y = y.narrow(0, 0, samples_to_keep)
optimizer.zero_grad()
output = model(x)
loss = F.nll_loss(output, y)
loss.backward()
optimizer.step()
sample_count += len(x)
percent_sample_count = 100. * sample_count / nsamples
if batch_idx % log_interval == 0:
print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
epoch, sample_count, nsamples, percent_sample_count,
loss.data[0]))
if nsamples is not None and sample_count >= nsamples:
break
def val_epoch(epoch, val_loader, model, optimizer, cuda, log_interval,
nsamples):
model.eval()
if nsamples is None:
nsamples = len(val_loader.dataset)
val_loss = 0
val_acc = 0
correct = 0
sample_count = 0
for batch_idx, (x, y) in enumerate(val_loader, start=1):
if cuda:
x, y = x.cuda(), y.cuda()
x, y = Variable(x, volatile=True), Variable(y)
if sample_count + len(x) > nsamples:
extra_samples = sample_count - nsamples
samples_to_keep = len(x) - extra_samples
x = x.narrow(0, 0, samples_to_keep)
y = y.narrow(0, 0, samples_to_keep)
output = model(x)
val_loss += F.nll_loss(output, y).data[0]
# get the index of the max log-probability
pred = output.data.max(1)[1]
correct += pred.eq(y.data).cpu().sum()
sample_count += len(x)
if (nsamples is not None and
sample_count >= nsamples):
break
# loss function already averages over batch size
val_loss /= nsamples
val_acc = 100. * correct / nsamples
display_str = '\nTest set: Average loss: ' + \
'{:.4f}, Accuracy: {}/{} ({:.0f}%)\n'
print(display_str.format(
val_loss, correct, nsamples, val_acc))
return val_loss, val_acc
def train_model(args):
task_path = join(results_path, args.namespace, TRAIN_MODEL)
safe_makedirs(task_path)
model_path = join(task_path, 'model')
best_model_path = join(task_path, 'best_model')
train_loader = get_data_loader(
args.dataset, loader_name=args.loader,
batch_size=args.batch_size, shuffle=True, split=TRAIN,
transform_names=args.transforms, cuda=args.cuda)
val_loader = get_data_loader(
args.dataset, loader_name=args.loader,
batch_size=args.val_batch_size, shuffle=False, split=VAL,
transform_names=args.transforms, cuda=args.cuda)
model = make_model(args.model_name, args.input_shape)
if args.cuda:
model.cuda()
optimizer = get_optimizer(
args.optimizer_name, model.parameters(), lr=args.lr,
momentum=args.momentum)
log_path = join(task_path, 'log.csv')
first_epoch = setup_log(log_path)
if first_epoch > 1:
model.load_state_dict(load_weights(args.namespace))
min_val_loss = np.inf
for epoch in range(first_epoch, args.epochs + 1):
train_epoch(epoch, train_loader, model, optimizer, args.cuda,
args.log_interval, args.samples_per_epoch)
val_loss, val_acc = val_epoch(
epoch, val_loader, model, optimizer, args.cuda, args.log_interval,
args.val_samples_per_epoch)
append_log(log_path, (epoch, val_loss, val_acc))
torch.save(model.state_dict(), model_path)
if val_loss < min_val_loss:
torch.save(model.state_dict(), best_model_path)
min_val_loss = val_loss
def parse_args():
parser = argparse.ArgumentParser(description='Train recognition model')
add_common_args(parser)
parser.add_argument('--dataset', type=str, default=MNIST,
help='name of the dataset')
parser.add_argument('--loader', type=str, default=DEFAULT,
help='name of the dataset loader')
parser.add_argument('--transforms', type=str, nargs='*',
default=[NORMALIZE],
help='list of transform')
parser.add_argument('--model-name', type=str, default=MINI,
help='name of the model')
parser.add_argument('--input-shape', type=int, nargs='*',
default=None,
help='shape of input data')
parser.add_argument('--optimizer-name', type=str, default=SGD,
help='name of the optimizer')
parser.add_argument('--lr', type=float, default=0.01, metavar='LR',
help='learning rate (default: 0.01)')
parser.add_argument('--momentum', type=float, default=0.5, metavar='M',
help='SGD momentum (default: 0.5)')
parser.add_argument('--batch-size', type=int, default=64, metavar='N',
help='input batch size for training (default: 64)')
parser.add_argument('--val-batch-size', type=int, default=1000,
metavar='N',
help='input batch size for validation (default: 1000)')
parser.add_argument('--epochs', type=int, default=10, metavar='N',
help='number of epochs to train (default: 10)')
parser.add_argument('--samples-per-epoch', type=int, default=None)
parser.add_argument('--val-samples-per-epoch', type=int, default=None)
parser.add_argument('--log-interval', type=int, default=10, metavar='N',
help='how many batches to wait before' +
'logging training status')
args = parser.parse_args()
args.samples_per_epoch = None if args.samples_per_epoch == -1 \
else args.samples_per_epoch
args.val_samples_per_epoch = None if args.val_samples_per_epoch == -1 \
else args.val_samples_per_epoch
args.cuda = not args.no_cuda and torch.cuda.is_available()
return args
if __name__ == '__main__':
train_model(parse_args())
| [
"pt.common.utils.safe_makedirs",
"torch.autograd.Variable",
"argparse.ArgumentParser",
"torch.nn.functional.nll_loss",
"torch.load",
"os.path.join",
"pt.recog.data.factory.get_data_loader",
"torch.cuda.is_available",
"pt.common.utils.setup_log",
"pt.common.utils.append_log",
"numpy.genfromtxt",
... | [((625, 667), 'os.path.join', 'join', (['results_path', 'namespace', 'TRAIN_MODEL'], {}), '(results_path, namespace, TRAIN_MODEL)\n', (629, 667), False, 'from os.path import join\n'), ((690, 726), 'os.path.join', 'join', (['train_model_path', '"""best_model"""'], {}), "(train_model_path, 'best_model')\n", (694, 726), False, 'from os.path import join\n'), ((738, 765), 'torch.load', 'torch.load', (['best_model_path'], {}), '(best_model_path)\n', (748, 765), False, 'import torch\n'), ((816, 858), 'os.path.join', 'join', (['results_path', 'namespace', 'TRAIN_MODEL'], {}), '(results_path, namespace, TRAIN_MODEL)\n', (820, 858), False, 'from os.path import join\n'), ((874, 907), 'os.path.join', 'join', (['train_model_path', '"""log.csv"""'], {}), "(train_model_path, 'log.csv')\n", (878, 907), False, 'from os.path import join\n'), ((919, 972), 'numpy.genfromtxt', 'np.genfromtxt', (['log_path'], {'delimiter': '""","""', 'skip_header': '(1)'}), "(log_path, delimiter=',', skip_header=1)\n", (932, 972), True, 'import numpy as np\n'), ((3517, 3564), 'os.path.join', 'join', (['results_path', 'args.namespace', 'TRAIN_MODEL'], {}), '(results_path, args.namespace, TRAIN_MODEL)\n', (3521, 3564), False, 'from os.path import join\n'), ((3569, 3593), 'pt.common.utils.safe_makedirs', 'safe_makedirs', (['task_path'], {}), '(task_path)\n', (3582, 3593), False, 'from pt.common.utils import safe_makedirs, append_log, setup_log\n'), ((3611, 3635), 'os.path.join', 'join', (['task_path', '"""model"""'], {}), "(task_path, 'model')\n", (3615, 3635), False, 'from os.path import join\n'), ((3658, 3687), 'os.path.join', 'join', (['task_path', '"""best_model"""'], {}), "(task_path, 'best_model')\n", (3662, 3687), False, 'from os.path import join\n'), ((3708, 3875), 'pt.recog.data.factory.get_data_loader', 'get_data_loader', (['args.dataset'], {'loader_name': 'args.loader', 'batch_size': 'args.batch_size', 'shuffle': '(True)', 'split': 'TRAIN', 'transform_names': 'args.transforms', 'cuda': 'args.cuda'}), '(args.dataset, loader_name=args.loader, batch_size=args.\n batch_size, shuffle=True, split=TRAIN, transform_names=args.transforms,\n cuda=args.cuda)\n', (3723, 3875), False, 'from pt.recog.data.factory import get_data_loader, MNIST, DEFAULT, NORMALIZE\n'), ((3910, 4081), 'pt.recog.data.factory.get_data_loader', 'get_data_loader', (['args.dataset'], {'loader_name': 'args.loader', 'batch_size': 'args.val_batch_size', 'shuffle': '(False)', 'split': 'VAL', 'transform_names': 'args.transforms', 'cuda': 'args.cuda'}), '(args.dataset, loader_name=args.loader, batch_size=args.\n val_batch_size, shuffle=False, split=VAL, transform_names=args.\n transforms, cuda=args.cuda)\n', (3925, 4081), False, 'from pt.recog.data.factory import get_data_loader, MNIST, DEFAULT, NORMALIZE\n'), ((4110, 4155), 'pt.recog.models.factory.make_model', 'make_model', (['args.model_name', 'args.input_shape'], {}), '(args.model_name, args.input_shape)\n', (4120, 4155), False, 'from pt.recog.models.factory import make_model\n'), ((4336, 4362), 'os.path.join', 'join', (['task_path', '"""log.csv"""'], {}), "(task_path, 'log.csv')\n", (4340, 4362), False, 'from os.path import join\n'), ((4381, 4400), 'pt.common.utils.setup_log', 'setup_log', (['log_path'], {}), '(log_path)\n', (4390, 4400), False, 'from pt.common.utils import safe_makedirs, append_log, setup_log\n'), ((5132, 5194), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Train recognition model"""'}), "(description='Train recognition model')\n", (5155, 5194), False, 'import argparse\n'), ((5199, 5222), 'pt.recog.tasks.utils.add_common_args', 'add_common_args', (['parser'], {}), '(parser)\n', (5214, 5222), False, 'from pt.recog.tasks.utils import add_common_args\n'), ((1664, 1685), 'torch.nn.functional.nll_loss', 'F.nll_loss', (['output', 'y'], {}), '(output, y)\n', (1674, 1685), True, 'import torch.nn.functional as F\n'), ((4867, 4915), 'pt.common.utils.append_log', 'append_log', (['log_path', '(epoch, val_loss, val_acc)'], {}), '(log_path, (epoch, val_loss, val_acc))\n', (4877, 4915), False, 'from pt.common.utils import safe_makedirs, append_log, setup_log\n'), ((7387, 7412), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (7410, 7412), False, 'import torch\n'), ((1320, 1331), 'torch.autograd.Variable', 'Variable', (['x'], {}), '(x)\n', (1328, 1331), False, 'from torch.autograd import Variable\n'), ((1333, 1344), 'torch.autograd.Variable', 'Variable', (['y'], {}), '(y)\n', (1341, 1344), False, 'from torch.autograd import Variable\n'), ((2513, 2539), 'torch.autograd.Variable', 'Variable', (['x'], {'volatile': '(True)'}), '(x, volatile=True)\n', (2521, 2539), False, 'from torch.autograd import Variable\n'), ((2541, 2552), 'torch.autograd.Variable', 'Variable', (['y'], {}), '(y)\n', (2549, 2552), False, 'from torch.autograd import Variable\n'), ((2847, 2868), 'torch.nn.functional.nll_loss', 'F.nll_loss', (['output', 'y'], {}), '(output, y)\n', (2857, 2868), True, 'import torch.nn.functional as F\n')] |
"""
SYS-611: Buffon's Needle Experiment Example with Antithetic Variables.
This example performs a Monte Carlo simulation of Buffon's Needle Experiment
to estimate the probability of a needle of certain length crossing lines
on a floor with certain spacing. This probability is proportional to the
mathematical constant pi.
@author: <NAME> <<EMAIL>>
"""
# import the python3 behavior for importing, division, and printing in python2
from __future__ import absolute_import, division, print_function
# import the matplotlib pyplot package and refer to it as `plt`
# see http://matplotlib.org/api/pyplot_api.html for documentation
import matplotlib.pyplot as plt
# import the scipy stats package and refer to it as `stats`
# see http://docs.scipy.org/doc/scipy/reference/stats.html for documentation
import scipy.stats as stats
# import the numpy package and refer to it as `np`
# see http://docs.scipy.org/doc/numpy/reference/ for documentation
import numpy as np
# define the line width and needle length for buffon's experiment
line_width = 3.0
needle_length = 2.5
# define a process generator for the event if a needle crosses a line
def drop_needle():
r_1 = np.random.rand()
r_2 = np.random.rand()
# generate distance between needle centroid and nearest line from uniform
# distribution between 0 and line_width/2
d_1 = r_1*line_width/2
d_2 = (1-r_1)*line_width/2
# generate acute angle between needle and line from uniform distribution
# between 0 and pi/2 radians
theta_1 = r_2*np.pi/2
theta_2 = (1-r_2)*np.pi/2
# for each antithetic variable, record 1 if d < needle_length/2*sin(theta)
# otherwise record 0
x_1 = 1 if d_1 < needle_length/2*np.sin(theta_1) else 0
x_2 = 1 if d_2 < needle_length/2*np.sin(theta_2) else 0
# return the average of the two antithetic variables
return (x_1+x_2)/2.
# set the random number generator seed to 0
np.random.seed(0)
# generate 850 samples
samples = [drop_needle() for i in range(850)]
# compute the lower and upper-bounds using a 95% confidence interval
confidence_level = 0.05
z_crit = stats.norm.ppf(1-confidence_level/2)
print('P(X) = {:.3f} +/- {:.3f} (95% CI)'.format(
np.average(samples),
z_crit*stats.sem(samples)
))
# compute the exact solution, as solved by calculus
solution = 2*needle_length/(line_width*np.pi)
# compute running statistics for mean and confidence interval
mean_estimate = np.array([np.average(samples[0:i]) for i in range(len(samples))])
confidence_int = z_crit*np.array([stats.sem(samples[0:i]) for i in range(len(samples))])
# create a plot to show the mean estimate with 95% confidence interval bounds
plt.figure()
plt.plot(range(len(samples)), mean_estimate,
'b', label='Mean Estimate')
plt.plot(range(len(samples)), mean_estimate-confidence_int,
'g', label='95% CI Lower Bound')
plt.plot(range(len(samples)), mean_estimate+confidence_int,
'r', label='95% CI Upper Bound')
plt.plot([0, len(samples)], [solution, solution],
'-k', label='Analytical Solution')
plt.xlabel('Sample')
plt.ylabel('Estimate of $P(x)$')
plt.legend(loc='best')
#%%
# transform the mean estimate to estimate pi using the solution form
pi_estimate = 2*needle_length/(line_width*mean_estimate)
pi_lower_bound = 2*needle_length/(line_width*(mean_estimate+confidence_int))
pi_upper_bound = 2*needle_length/(line_width*(mean_estimate-confidence_int))
print('pi = {:.3f} +/- {:.3f} (95% CI)'.format(
pi_estimate[-1],
pi_upper_bound[-1] - pi_estimate[-1]
))
# create a plot to show the pi estimate with 95% confidence interval bounds
plt.figure()
plt.plot(range(len(samples)), pi_estimate,
'b', label='Mean Estimate')
plt.plot(range(len(samples)), pi_lower_bound,
'g', label='95% CI Lower Bound')
plt.plot(range(len(samples)), pi_upper_bound,
'r', label='95% CI Upper Bound')
plt.plot([0, len(samples)], [np.pi, np.pi],
'-k', label='Analytical Solution')
plt.xlabel('Sample')
plt.ylabel('Estimate of $\pi$')
plt.legend(loc='best') | [
"numpy.random.rand",
"matplotlib.pyplot.ylabel",
"numpy.average",
"matplotlib.pyplot.xlabel",
"scipy.stats.norm.ppf",
"matplotlib.pyplot.figure",
"numpy.random.seed",
"scipy.stats.sem",
"numpy.sin",
"matplotlib.pyplot.legend"
] | [((1920, 1937), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (1934, 1937), True, 'import numpy as np\n'), ((2111, 2151), 'scipy.stats.norm.ppf', 'stats.norm.ppf', (['(1 - confidence_level / 2)'], {}), '(1 - confidence_level / 2)\n', (2125, 2151), True, 'import scipy.stats as stats\n'), ((2681, 2693), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (2691, 2693), True, 'import matplotlib.pyplot as plt\n'), ((3079, 3099), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Sample"""'], {}), "('Sample')\n", (3089, 3099), True, 'import matplotlib.pyplot as plt\n'), ((3100, 3132), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Estimate of $P(x)$"""'], {}), "('Estimate of $P(x)$')\n", (3110, 3132), True, 'import matplotlib.pyplot as plt\n'), ((3133, 3155), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""best"""'}), "(loc='best')\n", (3143, 3155), True, 'import matplotlib.pyplot as plt\n'), ((3645, 3657), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (3655, 3657), True, 'import matplotlib.pyplot as plt\n'), ((4006, 4026), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Sample"""'], {}), "('Sample')\n", (4016, 4026), True, 'import matplotlib.pyplot as plt\n'), ((4027, 4059), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Estimate of $\\\\pi$"""'], {}), "('Estimate of $\\\\pi$')\n", (4037, 4059), True, 'import matplotlib.pyplot as plt\n'), ((4059, 4081), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""best"""'}), "(loc='best')\n", (4069, 4081), True, 'import matplotlib.pyplot as plt\n'), ((1172, 1188), 'numpy.random.rand', 'np.random.rand', ([], {}), '()\n', (1186, 1188), True, 'import numpy as np\n'), ((1199, 1215), 'numpy.random.rand', 'np.random.rand', ([], {}), '()\n', (1213, 1215), True, 'import numpy as np\n'), ((2207, 2226), 'numpy.average', 'np.average', (['samples'], {}), '(samples)\n', (2217, 2226), True, 'import numpy as np\n'), ((2457, 2481), 'numpy.average', 'np.average', (['samples[0:i]'], {}), '(samples[0:i])\n', (2467, 2481), True, 'import numpy as np\n'), ((2243, 2261), 'scipy.stats.sem', 'stats.sem', (['samples'], {}), '(samples)\n', (2252, 2261), True, 'import scipy.stats as stats\n'), ((2547, 2570), 'scipy.stats.sem', 'stats.sem', (['samples[0:i]'], {}), '(samples[0:i])\n', (2556, 2570), True, 'import scipy.stats as stats\n'), ((1711, 1726), 'numpy.sin', 'np.sin', (['theta_1'], {}), '(theta_1)\n', (1717, 1726), True, 'import numpy as np\n'), ((1771, 1786), 'numpy.sin', 'np.sin', (['theta_2'], {}), '(theta_2)\n', (1777, 1786), True, 'import numpy as np\n')] |
import numpy as np
import scipy.spatial.transform
from moveit_commander.conversions import list_to_pose_stamped
class Rotation(scipy.spatial.transform.Rotation):
@classmethod
def identity(cls):
return cls.from_quat([0.0, 0.0, 0.0, 1.0])
class Transform(object):
def __init__(self, rotation, translation):
self.rotation = rotation
self.translation = np.asarray(translation, np.double)
@classmethod
def from_matrix(cls, m):
rotation = Rotation.from_dcm(m[:3, :3])
translation = m[:3, 3]
return cls(rotation, translation)
@classmethod
def from_list(cls, l):
return cls(Rotation.from_quat(l[:4]), l[4:])
def as_matrix(self):
return np.vstack(
(np.c_[self.rotation.as_dcm(), self.translation], [0.0, 0.0, 0.0, 1.0])
)
def to_list(self):
return self.translation.tolist() + self.rotation.as_quat().tolist()
def __mul__(self, other):
rotation = self.rotation * other.rotation
translation = self.rotation.apply(other.translation) + self.translation
return self.__class__(rotation, translation)
def inverse(self):
rotation = self.rotation.inv()
translation = -rotation.apply(self.translation)
return self.__class__(rotation, translation)
@classmethod
def identity(cls):
rotation = Rotation.from_quat([0.0, 0.0, 0.0, 1.0])
translation = np.array([0.0, 0.0, 0.0])
return cls(rotation, translation)
@classmethod
def translation(cls, translation):
rotation = Rotation.identity()
return cls(rotation, translation)
@classmethod
def rotation(cls, rotation):
translation = np.zeros(3)
return cls(rotation, translation)
| [
"numpy.array",
"numpy.zeros",
"numpy.asarray"
] | [((389, 423), 'numpy.asarray', 'np.asarray', (['translation', 'np.double'], {}), '(translation, np.double)\n', (399, 423), True, 'import numpy as np\n'), ((1445, 1470), 'numpy.array', 'np.array', (['[0.0, 0.0, 0.0]'], {}), '([0.0, 0.0, 0.0])\n', (1453, 1470), True, 'import numpy as np\n'), ((1724, 1735), 'numpy.zeros', 'np.zeros', (['(3)'], {}), '(3)\n', (1732, 1735), True, 'import numpy as np\n')] |
#!/usr/bin/env python3
# load needed modules
import numpy as np
from keras.models import Sequential
from keras.layers import Dense, Activation, Flatten, Dropout, GRU , BatchNormalization
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import StandardScaler
# load feature data
X = np.load('X_egemaps.npy')
y = np.load('y_egemaps.npy')
# z-score normalization
ori_aud_features = X
norm_aud_features = []
for aud_original in ori_aud_features:
aud_original_np = np.asarray(aud_original)
z_norm_aud = (aud_original_np - aud_original_np.mean()) / aud_original_np.std()
norm_aud_features.append(np.around(z_norm_aud, 6))
X = np.array(norm_aud_features)
train_x, test_x, train_y, test_y = train_test_split(X, y, test_size=0.33, random_state=42)
# DNN layer units
n_dim = np.array(train_x).shape[2]
n_classes = np.array(train_y).shape[1]
## normalize data
#mean = train_x.reshape(504172, 23).mean(axis=0)
#train_x -= mean
#std = train_x.reshape(504172, 23).std(axis=0)
#train_x /= std
#test_x -= mean
#test_x /= std
## function to define model
#def create_model():
# model = Sequential()
# # layer 1
# model.add(BatchNormalization(axis=-1, input_shape=(523, 23)))
# model.add(GRU(n_dim, activation='relu', #input_shape=(523, 23),
# dropout=0.2, recurrent_dropout=0.2, return_sequences=True))
# model.add(GRU(100, activation='relu', return_sequences=True,
# dropout=0.2, recurrent_dropout=0.2))
# model.add(GRU(100, activation='relu', dropout=0.2, recurrent_dropout=0.2))
# #model.add(Dense(128, activation='relu'))
# model.add(Dense(n_classes, activation='softmax'))
# # model compilation
# model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])
# return model
def dense_model(activation_function='relu', init_type='normal', optimiser='adam', dropout_rate=0.2):
model = Sequential()
# layer 1
model.add(BatchNormalization(axis=-1, input_shape=(523, 23)))
model.add(Flatten())
model.add(Dense(100, kernel_initializer=init_type, activation=activation_function)) #, input_shape=(523, 23)))
# layer 2
model.add(Dense(200, kernel_initializer=init_type, activation=activation_function))
model.add(Dropout(dropout_rate))
# layer 3
model.add(Dense(100, kernel_initializer=init_type, activation=activation_function))
model.add(Dropout(dropout_rate))
#layer4
#model.add(Dense(50, kernel_initializer=init_type, activation=activation_function))
#model.add(Dropout(dropout_rate))
#model.add(Flatten())
# output layer
model.add(Dense(n_classes, kernel_initializer=init_type, activation='softmax'))
# model compilation
model.compile(loss='categorical_crossentropy', optimizer=optimiser, metrics=['accuracy'])
return model
# create the model
model = dense_model()
print(model.summary())
# train the model
hist = model.fit(train_x, train_y, epochs=300, validation_data=[test_x, test_y], batch_size=32)
# evaluate model, test data may differ from validation data
evaluate = model.evaluate(test_x, test_y, batch_size=32)
print(evaluate)
| [
"keras.layers.Flatten",
"sklearn.model_selection.train_test_split",
"numpy.asarray",
"keras.models.Sequential",
"numpy.array",
"numpy.around",
"keras.layers.Dense",
"keras.layers.BatchNormalization",
"numpy.load",
"keras.layers.Dropout"
] | [((423, 447), 'numpy.load', 'np.load', (['"""X_egemaps.npy"""'], {}), "('X_egemaps.npy')\n", (430, 447), True, 'import numpy as np\n'), ((452, 476), 'numpy.load', 'np.load', (['"""y_egemaps.npy"""'], {}), "('y_egemaps.npy')\n", (459, 476), True, 'import numpy as np\n'), ((777, 804), 'numpy.array', 'np.array', (['norm_aud_features'], {}), '(norm_aud_features)\n', (785, 804), True, 'import numpy as np\n'), ((841, 896), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X', 'y'], {'test_size': '(0.33)', 'random_state': '(42)'}), '(X, y, test_size=0.33, random_state=42)\n', (857, 896), False, 'from sklearn.model_selection import train_test_split\n'), ((608, 632), 'numpy.asarray', 'np.asarray', (['aud_original'], {}), '(aud_original)\n', (618, 632), True, 'import numpy as np\n'), ((2048, 2060), 'keras.models.Sequential', 'Sequential', ([], {}), '()\n', (2058, 2060), False, 'from keras.models import Sequential\n'), ((746, 770), 'numpy.around', 'np.around', (['z_norm_aud', '(6)'], {}), '(z_norm_aud, 6)\n', (755, 770), True, 'import numpy as np\n'), ((924, 941), 'numpy.array', 'np.array', (['train_x'], {}), '(train_x)\n', (932, 941), True, 'import numpy as np\n'), ((965, 982), 'numpy.array', 'np.array', (['train_y'], {}), '(train_y)\n', (973, 982), True, 'import numpy as np\n'), ((2094, 2144), 'keras.layers.BatchNormalization', 'BatchNormalization', ([], {'axis': '(-1)', 'input_shape': '(523, 23)'}), '(axis=-1, input_shape=(523, 23))\n', (2112, 2144), False, 'from keras.layers import Dense, Activation, Flatten, Dropout, GRU, BatchNormalization\n'), ((2160, 2169), 'keras.layers.Flatten', 'Flatten', ([], {}), '()\n', (2167, 2169), False, 'from keras.layers import Dense, Activation, Flatten, Dropout, GRU, BatchNormalization\n'), ((2185, 2257), 'keras.layers.Dense', 'Dense', (['(100)'], {'kernel_initializer': 'init_type', 'activation': 'activation_function'}), '(100, kernel_initializer=init_type, activation=activation_function)\n', (2190, 2257), False, 'from keras.layers import Dense, Activation, Flatten, Dropout, GRU, BatchNormalization\n'), ((2318, 2390), 'keras.layers.Dense', 'Dense', (['(200)'], {'kernel_initializer': 'init_type', 'activation': 'activation_function'}), '(200, kernel_initializer=init_type, activation=activation_function)\n', (2323, 2390), False, 'from keras.layers import Dense, Activation, Flatten, Dropout, GRU, BatchNormalization\n'), ((2408, 2429), 'keras.layers.Dropout', 'Dropout', (['dropout_rate'], {}), '(dropout_rate)\n', (2415, 2429), False, 'from keras.layers import Dense, Activation, Flatten, Dropout, GRU, BatchNormalization\n'), ((2463, 2535), 'keras.layers.Dense', 'Dense', (['(100)'], {'kernel_initializer': 'init_type', 'activation': 'activation_function'}), '(100, kernel_initializer=init_type, activation=activation_function)\n', (2468, 2535), False, 'from keras.layers import Dense, Activation, Flatten, Dropout, GRU, BatchNormalization\n'), ((2553, 2574), 'keras.layers.Dropout', 'Dropout', (['dropout_rate'], {}), '(dropout_rate)\n', (2560, 2574), False, 'from keras.layers import Dense, Activation, Flatten, Dropout, GRU, BatchNormalization\n'), ((2781, 2849), 'keras.layers.Dense', 'Dense', (['n_classes'], {'kernel_initializer': 'init_type', 'activation': '"""softmax"""'}), "(n_classes, kernel_initializer=init_type, activation='softmax')\n", (2786, 2849), False, 'from keras.layers import Dense, Activation, Flatten, Dropout, GRU, BatchNormalization\n')] |
# --------------
# Importing header files
import numpy as np
# Path of the file has been stored in variable called 'path'
data_file='path' # path for the file
data = np.genfromtxt(path, delimiter=",", skip_header=1,dtype=str)
print("\nData: \n\n", data)
print("\nType of data: \n\n", type(data))
#New record
new_record = [[50, 9,4, 1, 0, 0, 40, 0]]
print(new_record)
#Code starts here
census = np.concatenate((new_record, data), axis=0)
print(census)
# --------------
#Code starts here
import numpy as np
#age = census[:,0]
#age = census[:,0:1]
#age=np.array(census[:,0])
age = np.asarray(census[:,0]).astype(np.float32)
max_age= np.max(age)
min_age = np.min(age)
age_mean = round(np.mean(age),2)+0
age_std = round(np.std(age),2)+0
print('The max age is: ',max_age)
print('The min age is: ',min_age)
print('The mean of age is: ',age_mean)
print('The std de of age is: ',age_std)
# --------------
#Code starts here
race_0=census[census[:,2]==0]
race_1=census[census[:,2]==1]
race_2=census[census[:,2]==2]
race_3=census[census[:,2]==3]
race_4=census[census[:,2]==4]
len_0 = len(race_0)
print(len_0)
len_1 = len(race_1)
print(len_1)
len_2 = len(race_2)
print(len_2)
len_3 = len(race_3)
print(len_3)
len_4 = len(race_4)
print(len_4)
race_list = [len_0,len_1,len_2,len_3,len_4]
minority_race = race_list.index(min(race_list))
print(minority_race)
# --------------
#Code starts here
import numpy as np
senior_citizens = census[census[:,0].astype(int) > 60]
print(senior_citizens)
working_hours_sum = np.sum(senior_citizens[:,6].astype(int))
print(working_hours_sum)
senior_citizens_len = len(senior_citizens)
print(senior_citizens_len)
avg_working_hours = working_hours_sum/senior_citizens_len
print(avg_working_hours)
# --------------
#Code starts here
high=census[census[:,1].astype(int) >10]
print(high)
low=census[census[:,1].astype(int) <=10]
print(low)
avg_pay_high = np.mean(high[:,7].astype(int))
avg_pay_low = np.mean(low[:,7].astype(int))
print(avg_pay_high.round(2))
print(avg_pay_low.round(2))
| [
"numpy.mean",
"numpy.std",
"numpy.asarray",
"numpy.max",
"numpy.concatenate",
"numpy.min",
"numpy.genfromtxt"
] | [((174, 234), 'numpy.genfromtxt', 'np.genfromtxt', (['path'], {'delimiter': '""","""', 'skip_header': '(1)', 'dtype': 'str'}), "(path, delimiter=',', skip_header=1, dtype=str)\n", (187, 234), True, 'import numpy as np\n'), ((418, 460), 'numpy.concatenate', 'np.concatenate', (['(new_record, data)'], {'axis': '(0)'}), '((new_record, data), axis=0)\n', (432, 460), True, 'import numpy as np\n'), ((669, 680), 'numpy.max', 'np.max', (['age'], {}), '(age)\n', (675, 680), True, 'import numpy as np\n'), ((694, 705), 'numpy.min', 'np.min', (['age'], {}), '(age)\n', (700, 705), True, 'import numpy as np\n'), ((614, 638), 'numpy.asarray', 'np.asarray', (['census[:, 0]'], {}), '(census[:, 0])\n', (624, 638), True, 'import numpy as np\n'), ((726, 738), 'numpy.mean', 'np.mean', (['age'], {}), '(age)\n', (733, 738), True, 'import numpy as np\n'), ((763, 774), 'numpy.std', 'np.std', (['age'], {}), '(age)\n', (769, 774), True, 'import numpy as np\n')] |
# Walking engine for Starkit Kondo OpenMV
# Copyright STARKIT Soccer team of MIPT
import math
import sys
import time
import numpy as np
class Alpha(object):
def compute_alpha_v3(self, xt,yt,zt,x,y,z,w, sizes, limAlpha):
from math import sqrt,cos,sin,asin,fabs,tan,atan
#t1_start =time.perf_counter_ns()
a5, b5, c5, a6, a7, a8, a9, a10, b10, c10 = sizes
limAlpha5, limAlpha6, limAlpha7, limAlpha8, limAlpha9, limAlpha10 = limAlpha
alpha5 = w
cos5 = math.cos(alpha5)
sin5 = math.sin(alpha5)
nor = math.sqrt(x*x+y*y+z*z)
x = x/nor
y = y/nor
z = z/nor
xtp = xt * cos5 + (yt + a5) * sin5
ytp = (yt + a5) * cos5 - xt * sin5
ztp = zt
xp = x * cos5 + y * sin5
yp = y * cos5 - x * sin5
zp = z
var = [-1,1]
angles = []
lim1a= limAlpha6[0]*0.00058909
lim2a = limAlpha6[1]*0.00058909
ind = 1
step1 = (lim2a-lim1a)/10
testalpha6 =[]
for i in range (11):
alpha6 = lim1a+i*step1
cos= math.cos(alpha6)
sin= math.sin(alpha6)
testalpha6.append( ((ytp+b5)*cos+ztp*sin -c10)*((yp*cos+zp*sin)**2-
(zp*cos-yp*sin)**2 -xp*xp)-a10-b10*(yp*cos+zp*sin)/math.sqrt((zp*cos-yp*sin)**2+xp*xp))
points = []
for i in range(10):
if (testalpha6[i]>0 and testalpha6[i+1]<0)or(testalpha6[i]<0 and testalpha6[i+1]>0): points.append(i)
k=0
if len(points)==0:
for i in range(11):
if (math.fabs(testalpha6[i]) < math.fabs(testalpha6[k])): k=i
if k==10: points.append(9)
else:
if (math.fabs(testalpha6[k-1]) < math.fabs(testalpha6[k+1])): points.append(k-1)
else: points.append(k)
alpha6m = []
for j in range(len(points)):
lim1=lim1a+points[j]*step1
lim2=lim1+step1
while (True):
step = (lim2-lim1)/10
testalpha6 =[]
for i in range (11):
alpha6 = lim1+i*step
cos= math.cos(alpha6)
sin= math.sin(alpha6)
testalpha6.append( ((ytp+b5)*cos+ztp*sin-c10)*((yp*cos+zp*sin)**2-
(zp*cos-yp*sin)**2 -xp*xp)-a10-b10*(yp*cos+zp*sin)/math.sqrt((zp*cos-yp*sin)**2+xp*xp))
k=0
for i in range(11):
if (math.fabs(testalpha6[i]) < math.fabs(testalpha6[k])): k = i
if k==0: k2=1
elif k==10: k2 = 9
else:
if (math.fabs(testalpha6[k-1]) < math.fabs(testalpha6[k+1])): k2=k-1
else: k2=k+1
alpha6 = lim1+k*step
if k>k2:
lim1 = lim1+k2*step
lim2 = lim1+ step
else:
lim1 = lim1+k*step
lim2 = lim1+ step
if (lim2-lim1 < 0.00025): break
ind = ind + 1
if ind> (limAlpha6[1]- limAlpha6[0]): break
alpha6m.append(alpha6)
alpha10m =[]
kk=0
for i in range (len(alpha6m)):
tan6 = math.tan(alpha6m[i-kk])
alpha10 = math.atan((-yp-zp*tan6)/math.sqrt((zp-yp*tan6)**2+xp*xp*(1+tan6*tan6)))
if limAlpha10[0] < alpha10*1698 and alpha10*1698<limAlpha10[1]: alpha10m.append(alpha10)
else:
alpha6m.pop(i-kk)
kk=kk+1
kk=0
for ii in range (len(alpha6m)):
cos6 = math.cos(alpha6m[ii-kk])
sin6 = math.sin(alpha6m[ii-kk])
alpha987 = math.atan(-xp/(zp*cos6- yp*sin6))
sin987 = math.sin(alpha987)
cos987 = math.cos(alpha987)
K1 = a6*sin987+xtp*cos987+(ztp*cos6-(ytp+b5)*sin6)*sin987
K2 = a9+a6*cos987+(ztp*cos6-(ytp+b5)*sin6)*cos987-xtp*sin987+b10/math.cos(alpha10m[ii-kk])+((ytp+b5)*cos6+ztp*sin6-c10)*math.tan(alpha10m[ii-kk])
m = (K1*K1+K2*K2+a8*a8-a7*a7)/(2*a8)
temp1 = K1*K1*m*m-(K1*K1+K2*K2)*(m*m-K2*K2)
if temp1>=0 :
temp2 = (-K1*m + math.sqrt(temp1))/(K1*K1+K2*K2)
temp3 = (-K1*m - math.sqrt(temp1))/(K1*K1+K2*K2)
if math.fabs(temp2) <= 1 and math.fabs(temp3) <= 1:
alpha91 = math.asin(temp2)
alpha92 = math.asin(temp3)
else:
alpha6m.pop(ii-kk)
alpha10m.pop(ii-kk)
kk=kk+1
continue
else:
alpha6m.pop(ii-kk)
alpha10m.pop(ii-kk)
kk=kk+1
continue
alpha81 = math.atan((K1+a8*math.sin(alpha91))/(K2+a8*math.cos(alpha91))) - alpha91
alpha82 = math.atan((K1+a8*math.sin(alpha92))/(K2+a8*math.cos(alpha92))) - alpha92
alpha71 = alpha91+alpha81- alpha987
alpha72 = alpha92+alpha82- alpha987
temp71 = alpha71*1698<limAlpha7[0] or alpha71*1698>limAlpha7[1]
temp72 = alpha72*1698<limAlpha7[0] or alpha72*1698>limAlpha7[1]
temp81 = alpha81*1698<limAlpha8[0] or alpha81*1698>limAlpha8[1]
temp82 = alpha82*1698<limAlpha8[0] or alpha82*1698>limAlpha8[1]
temp91 = alpha91*1698<limAlpha9[0] or alpha91*1698>limAlpha9[1]
temp92 = alpha92*1698<limAlpha9[0] or alpha92*1698>limAlpha9[1]
if (temp71 and temp72) or (temp81 and temp82) or (temp91 and temp92) or ((temp71 or temp81 or temp91) and (temp72 or temp82 or temp92)):
alpha6m.pop(ii-kk)
alpha10m.pop(ii-kk)
kk=kk+1
continue
else:
if not (temp71 or temp81 or temp91):
ang =()
ang =alpha10m[ii-kk],alpha91,alpha81,alpha71,alpha6m[ii-kk],alpha5
angles.append(ang)
if not (temp72 or temp82 or temp92):
ang =()
ang =alpha10m[ii-kk],alpha92,alpha82,alpha72,alpha6m[ii-kk],alpha5
angles.append(ang)
return angles
class SimBackend(object):
def __init__(self, joint_names, imu_name, sim_path):
sys.path.append(sim_path)
import sim
self.sim_lib = sim
self.joint_names = joint_names
self.imu_name = imu_name
self.joint_handles = []
self.client_id = -1
self.sim_step_counter = 0
self.imu_handle = None
self.is_first_imu_call = True
def start(self):
self.sim_lib.simxFinish(-1) # just in case, close all opened connections
sim_thread_cycle_in_ms = 5
self.client_id = self.sim_lib.simxStart('127.0.0.1', -19997, True, True, 5000, sim_thread_cycle_in_ms)
_, self.imu_handle = self.sim_lib.simxGetObjectHandle(self.client_id, self.imu_name, self.sim_lib.simx_opmode_blocking)
for i, join_name in enumerate(self.joint_names):
_, handle = self.sim_lib.simxGetObjectHandle(self.client_id, join_name, self.sim_lib.simx_opmode_blocking)
self.joint_handles.append(handle)
self.sim_lib.simxGetIntegerParameter(self.client_id, self.sim_lib.sim_intparam_program_version, self.sim_lib.simx_opmode_streaming)
time.sleep(0.1)
self.sim_lib.simxStartSimulation(self.client_id, self.sim_lib.simx_opmode_oneshot)
def wait_step(self):
while True:
self.sim_lib.simxGetIntegerParameter(self.client_id, self.sim_lib.sim_intparam_program_version, self.sim_lib.simx_opmode_buffer)
tim = self.sim_lib.simxGetLastCmdTime(self.client_id)
if tim > self.sim_step_counter:
self.sim_step_counter = tim
break
time.sleep(0.001)
def stop(self):
self.sim_lib.simxStopSimulation(self.client_id, self.sim_lib.simx_opmode_oneshot)
def disable(self):
time.sleep(0.2)
self.sim_lib.simxFinish(self.client_id)
def set_joint_positions(self, positions):
self.sim_lib.simxPauseCommunication(self.client_id, True)
for position, joint_handle in zip(positions, self.joint_handles):
self.sim_lib.simxSetJointTargetPosition(
self.client_id,
joint_handle,
position,
self.sim_lib.simx_opmode_oneshot
)
self.sim_lib.simxPauseCommunication(self.client_id, False)
def get_joint_positions(self):
positions = []
for i, joint_handle in enumerate(self.joint_handles):
_, position = self.sim_lib.simxGetJointPosition(self.client_id, joint_handle, self.sim_lib.simx_opmode_blocking)
positions.append(position)
return positions
def get_imu_quaternion(self):
# if self.is_first_imu_call:
# self.is_first_imu_call = False
# self.get_imu_quaternion()
# self.get_imu_quaternion()
_, dummy_h_quaternion = self.sim_lib.simxGetObjectQuaternion(self.client_id, self.imu_handle, -1, self.sim_lib.simx_opmode_streaming)
return dummy_h_quaternion
class DirectEnvironment(object):
def __init__(self, joint_names, imu_name, sim_path):
self.sim_backend = SimBackend(joint_names, imu_name, sim_path)
self.joint_positions = None
def __del__(self):
self.sim_backend.stop()
self.sim_backend.disable()
def reset(self):
self.sim_backend.start()
self.joint_positions = self.sim_backend.get_joint_positions()
return (self.joint_positions, self.sim_backend.get_imu_quaternion())
def step(self, action):
self.sim_backend.wait_step()
if action:
self.joint_positions = action
self.sim_backend.set_joint_positions(self.joint_positions)
return (self.joint_positions, self.sim_backend.get_imu_quaternion()), 0
class MotionSim(object):
def __init__(self, random_mode=False, foot_only_mode=False):
self.FRAMELENGTH = 0.02
self.trims = []
self.joint_handle = []
self.dummy_h_handle = 0
self.client_id = -1
self.sim_step_counter = 0
self._foot_only_mode = foot_only_mode
if random_mode:
self.params = {
"BODY_TILT_AT_WALK": np.random.uniform(low=0.001, high=0.1),
"SOLE_LANDING_SKEW": np.random.uniform(low=0.035, high=0.085),
"FIRST_LEG_IS_RIGHT": np.random.choice([True, False]),
# "BASE_STEP_LENGTH": np.random.uniform(low=20., high=120),
# "BASE_SIDE_LENGTH": np.random.uniform(low=0., high=40),
"BASE_STEP_LENGTH": np.random.uniform(low=40., high=100),
"BASE_SIDE_LENGTH": np.random.uniform(low=0., high=20),
"AMPLITUDE": np.random.uniform(low=5., high=35),
"FR2": np.random.randint(low=18, high=24),
"GAIT_HEIGHT": np.random.uniform(low=180., high=200),
"STEP_HEIGHT": np.random.uniform(low=23., high=45),
}
else:
self.params = {
"BODY_TILT_AT_WALK": 0.03,
"SOLE_LANDING_SKEW": 0.06,
"FIRST_LEG_IS_RIGHT": False,
"BASE_STEP_LENGTH": 90,
"BASE_SIDE_LENGTH": 0,
"AMPLITUDE": 20,
"FR2": 24,
"GAIT_HEIGHT": 190,
"STEP_HEIGHT": 32.0,
}
self.FACTOR = [1, 1, 1, -1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, -1, 1, 1, 1, 1, 1, 1, 1, 1]
a5 = 21.5 # мм расстояние от оси симметрии до оси сервы 5
b5 = 18.5 # мм расстояние от оси сервы 5 до оси сервы 6 по горизонтали
c5 = 0 # мм расстояние от оси сервы 6 до нуля Z по вертикали
a6 = 42 # мм расстояние от оси сервы 6 до оси сервы 7
a7 = 65.5 # мм расстояние от оси сервы 7 до оси сервы 8
a8 = 63.8 # мм расстояние от оси сервы 8 до оси сервы 9
a9 = 35.5 # мм расстояние от оси сервы 9 до оси сервы 10
a10 = 25.4 # мм расстояние от оси сервы 10 до центра стопы по горизонтали
b10 = 26.4 # мм расстояние от оси сервы 10 до низа стопы 26.4
c10 = 12 # мм расстояние от оси сервы 6 до оси сервы 10 по горизонтали
self.SIZES = [a5, b5, c5, a6, a7, a8, a9, a10, b10, c10]
self.d10 = 53.4 # 53.4 расстояние по Y от центра стопы до оси робота
limAlpha5 = [-2667, 2667]
limAlpha6 = [-3000, 740]
limAlpha7 = [-3555, 3260]
limAlpha8 = [-4150, 1777]
limAlpha9 = [-4000, 2960]
limAlpha10 = [-2815, 600]
self.LIM_ALPHA = [limAlpha5, limAlpha6, limAlpha7, limAlpha8, limAlpha9, limAlpha10]
self.LIM_ALPHA[3][1] = 0
self.TIK2RAD = 0.00058909
self.slow_time = 0.0 # seconds
self.sim_thread_cycle_in_ms = 20
self.rotation = 0 # -45 - +45 degrees Centigrade per step + CW, - CCW.
# self.params["BASE_STEP_LENGTH"] = 90
# self.params["BASE_SIDE_LENGTH"] = 0
# # Following paramenetrs Not recommended for change
# self.params["AMPLITUDE"] = 20 # mm side amplitude (maximum distance between most right and most left position of Center of Mass) 53.4*2
# self.params["FR2"] = 24 # frame number for 2-nd phase of gait ( one leg in air)
# self.params["GAIT_HEIGHT"] = 190 # Distance between Center of mass and floor in walk pose
# self.params["STEP_HEIGHT"] = 32.0 # elevation of sole over floor
self.alpha = Alpha()
self.exit_flag = 0
self.neck_pan = 0
self.xtr = 0
self.ytr = -self.d10 # -53.4
self.ztr = -self.params["GAIT_HEIGHT"]
self.xr = 0
self.yr = 0
self.zr = -1
self.wr = 0
self.xtl = 0
self.ytl = self.d10 # 53.4
self.ztl = -self.params["GAIT_HEIGHT"]
self.xl = 0
self.yl = 0
self.zl = -1
self.wl = 0
self.euler_angle = {}
self.ACTIVEJOINTS = ['Leg_right_10', 'Leg_right_9', 'Leg_right_8', 'Leg_right_7', 'Leg_right_6', 'Leg_right_5',
'hand_right_4',
'hand_right_3', 'hand_right_2', 'hand_right_1', 'Tors1', 'Leg_left_10', 'Leg_left_9',
'Leg_left_8',
'Leg_left_7', 'Leg_left_6', 'Leg_left_5', 'hand_left_4', 'hand_left_3', 'hand_left_2',
'hand_left_1']
self.cycle = 0
self.number_of_cycles = 50
self.general_step = 0
self.total_steps = self.params["FR2"] + self.number_of_cycles
self.framestep = self.sim_thread_cycle_in_ms // 10
self.walk_cycle_steps_each_leg = self.params["FR2"] // self.framestep
self.total_walk_cycle_steps = 2 * self.walk_cycle_steps_each_leg
self.walk_cycle_step = 0
@staticmethod
def norm_yaw(yaw):
yaw %= 2 * math.pi
if yaw > math.pi:
yaw -= 2 * math.pi
if yaw < -math.pi:
yaw += 2 * math.pi
return yaw
@staticmethod
def quaternion_to_euler_angle(quaternion):
euler_angle = {}
w,x,y,z = quaternion
ysqr = y*y
t0 = +2.0 * (w * x + y * z)
t1 = +1.0 - 2.0 * (x * x + ysqr)
X = math.degrees(math.atan2(t0,t1))
t2 = +2.0 * (w * y - z * x)
t2 = +1.0 if t2 > +1.0 else t2
t2 = -1.0 if t2 < -1.0 else t2
Y = math.degrees(math.asin(t2))
t3 = +2.0 * (w * z + x * y)
t4 = +1.0 - 2.0 * (ysqr + z * z)
Z = math.degrees(math.atan2(t3,t4))
euler_angle['yaw'] = math.radians(X)
euler_angle['pitch'] = math.radians(Y)
euler_angle['roll'] = math.radians(Z)
return euler_angle
@staticmethod
def normalize_rotation(yaw):
if abs(yaw) > 2 * math.pi:
yaw %= (2 * math.pi)
if yaw > math.pi:
yaw -= (2 * math.pi)
if yaw < -math.pi:
yaw += (2 * math.pi)
if yaw > 0.5:
yaw = 0.5
if yaw < -0.5:
yaw = -0.5
return yaw
def imu_body_yaw(self):
yaw = self.neck_pan * self.TIK2RAD + self.euler_angle['yaw']
yaw = self.norm_yaw(yaw)
return yaw
def compute_alpha_for_walk(self):
angles = []
hands_on = True
angles_r = self.alpha.compute_alpha_v3(self.xtr, self.ytr, self.ztr, self.xr, self.yr, self.zr, self.wr, self.SIZES, self.LIM_ALPHA)
angles_l = self.alpha.compute_alpha_v3(self.xtl, -self.ytl, self.ztl, self.xl, -self.yl, self.zl, self.wl, self.SIZES, self.LIM_ALPHA)
if not len(angles_r) or not len(angles_l):
return []
for i in range(len(angles_r)):
if len(angles_r) == 1:
break
if angles_r[0][2] < angles_r[1][2]:
angles_r.pop(1)
else:
angles_r.pop(0)
for i in range(len(angles_l)):
if len(angles_l) == 1:
break
if angles_l[0][2] < angles_l[1][2]:
angles_l.pop(1)
else:
angles_l.pop(0)
if self.params["FIRST_LEG_IS_RIGHT"]:
angles_l, angles_r = angles_r, angles_l
for j in range(6):
angles.append(angles_l[0][j])
if hands_on:
angles.append(1.745)
else:
angles.append(0.0)
angles.append(0.0)
angles.append(0.0)
if hands_on:
angles.append(0.524 - self.xtr / 57.3)
else:
angles.append(0.0)
angles.append(0.0)
for j in range(6):
angles.append(-angles_r[0][j])
if hands_on:
angles.append(-1.745)
else:
angles.append(0.0)
angles.append(0.0)
angles.append(0.0)
if hands_on:
angles.append(-0.524 + self.xtl / 57.3)
else:
angles.append(0.0)
return angles
def step_length_planer(self, regular_step_length, regular_side_length, framestep, hovernum1):
xt0 = regular_step_length / 2 * self.params["FR2"] / (self.params["FR2"] + framestep * hovernum1)
dy0 = regular_side_length / (self.params["FR2"] + hovernum1 * framestep) * framestep
dy = regular_side_length / (self.params["FR2"] - hovernum1 * framestep) * framestep
return xt0, dy0, dy
def get_feet_action(self):
angles = self.compute_alpha_for_walk()
new_positions = []
if not len(angles):
self.exit_flag = self.exit_flag + 1
else:
for i in range(len(angles)):
new_positions.append(angles[i] * self.FACTOR[i])
result_positions = []
if self._foot_only_mode and len(new_positions):
for i, joint_name in enumerate(self.ACTIVEJOINTS):
if joint_name == "Tors1" or "Leg" in joint_name:
result_positions.append(new_positions[i])
else:
result_positions = new_positions
return result_positions
def refresh_orientation(self):
dummy_h_quaternion = self.imu_quaternion
self.euler_angle = self.quaternion_to_euler_angle(dummy_h_quaternion)
def act(self, imu_quaternion):
self.imu_quaternion = imu_quaternion
if self.general_step >= self.total_steps:
return None
if not self.general_step:
self.refresh_orientation()
if self.general_step < self.params["FR2"]:
i = self.general_step
amplitude = 70
self.ztr = -223.1 + i * (223.1-self.params["GAIT_HEIGHT"]) / self.params["FR2"]
self.ztl = -223.1 + i * (223.1-self.params["GAIT_HEIGHT"]) / self.params["FR2"]
self.ytr = -self.d10 - i * amplitude / 2 / self.params["FR2"]
self.ytl = self.d10 - i * amplitude / 2 / self.params["FR2"]
new_positions = self.get_feet_action()
self.general_step += 1
else:
if self.walk_cycle_step == 0:
self.cycle = self.general_step - self.params["FR2"]
self.refresh_orientation()
self.rotation = self.imu_body_yaw() * 1.2
if self.params["FIRST_LEG_IS_RIGHT"]:
self.rotation *= -1
self.rotation = self.normalize_rotation(self.rotation)
self.rotation = math.degrees(self.rotation)
self.side_length = self.params["BASE_SIDE_LENGTH"]
self.step_length = self.params["BASE_STEP_LENGTH"]
self.second_step_length = self.params["BASE_STEP_LENGTH"]
if self.cycle == 0:
self.step_length = self.step_length / 3
self.second_step_length = self.step_length / 3
if self.cycle == 1:
self.step_length = self.step_length / 3 * 2
self.second_step_length = self.step_length / 3 * 2
self.rotation = -self.rotation / 286
self.alpha01 = math.pi / self.params["FR2"]
self.hovernum = 6 # number of steps hovering over take off + landing points
self.xr_old, self.xl_old, self.yr_old, self.yl_old = self.xr, self.xl, self.yr, self.yl
# correction of sole skew depending on side angle of body when step pushes land
self.yr, self.yl = - self.params['SOLE_LANDING_SKEW'], self.params['SOLE_LANDING_SKEW']
# correction of body tilt forward
self.xr, self.xl = self.params['BODY_TILT_AT_WALK'], self.params['BODY_TILT_AT_WALK'] #
self.wr_old = self.wr
self.wl_old = self.wl
self.wr_target = - self.rotation
self.wl_target = - self.rotation
self.xt0, self.dy0, self.dy = self.step_length_planer(self.step_length, self.side_length, self.framestep,
self.hovernum)
self.ztl = -self.params["GAIT_HEIGHT"]
xtl0 = self.xtl
xtr0 = self.xtr
self.xtl1 = -self.xt0
self.xtr1 = self.xt0
self.dx0 = (self.xtl1 - xtl0) * self.framestep / self.params["FR2"]
self.dx = (self.xtr1 - xtr0) * self.framestep / self.params["FR2"] * (self.params["FR2"] + self.hovernum * self.framestep) / (
self.params["FR2"] - self.hovernum * self.framestep)
if self.walk_cycle_step < self.walk_cycle_steps_each_leg:
iii = self.walk_cycle_step * self.framestep
if 2 * self.framestep < iii < self.params["FR2"] - 4 * self.framestep:
self.xt0, self.dy0, self.dy = self.step_length_planer(self.step_length, self.side_length, self.framestep, self.hovernum)
self.xtl1 = -self.xt0
self.dx0 = (self.xtl1 - self.xtl) * self.framestep / (self.params["FR2"] - iii)
self.dx = (- self.xtr - self.xtl - self.dx0 * ((self.params["FR2"] - iii) / self.framestep + 3)) / (
(self.params["FR2"] - iii) / self.framestep - 3)
S = self.params["AMPLITUDE"] / 2 * math.sin(self.alpha01 * iii)
self.ytr = -S - self.d10
self.ytl = -S + self.d10
self.ztr = -self.params["GAIT_HEIGHT"]
if iii == 0:
self.ztr = -self.params["GAIT_HEIGHT"] + self.params["STEP_HEIGHT"] / 3
elif iii == self.framestep:
self.ztr = -self.params["GAIT_HEIGHT"] + self.params["STEP_HEIGHT"] * 2 / 3
elif iii == self.params["FR2"] - self.framestep:
self.ztr = -self.params["GAIT_HEIGHT"] + self.params["STEP_HEIGHT"] / 4
elif iii == self.params["FR2"] - 2 * self.framestep:
self.ztr = -self.params["GAIT_HEIGHT"] + self.params["STEP_HEIGHT"] * 2 / 4
elif iii == self.params["FR2"] - 3 * self.framestep:
self.ztr = -self.params["GAIT_HEIGHT"] + self.params["STEP_HEIGHT"] * 3 / 4
else:
self.ztr = -self.params["GAIT_HEIGHT"] + self.params["STEP_HEIGHT"]
if iii == 0 or iii == self.framestep or iii == 2 * self.framestep:
self.xtr += self.dx0
self.ytr = -64 + self.dy0 * iii
elif iii == self.params["FR2"] - self.framestep or iii == self.params["FR2"] - 2 * self.framestep or iii == self.params["FR2"] - 3 * self.framestep:
self.xtr += self.dx0
self.ytr = -64 + self.dy0 * 3 * self.framestep - self.dy * (self.params["FR2"] - 3 * self.framestep) / 2 + self.dy0 * (
iii - (self.params["FR2"] - 3 * self.framestep))
else:
self.xtr += self.dx
self.ytr = - 64 + self.dy0 * 3 * self.framestep - self.dy * iii / 2
self.wr = self.wr_old + (self.wr_target - self.wr_old) * (iii) / (self.params["FR2"] - self.hovernum * self.framestep)
self.wl = self.wl_old + (self.wl_target - self.wl_old) * (iii) / (self.params["FR2"] - self.hovernum * self.framestep)
self.xtl += self.dx0
self.ytl = -S + self.d10 + self.dy0 * iii
else:
if self.walk_cycle_step == self.walk_cycle_steps_each_leg:
self.xr, self.xl = self.params['BODY_TILT_AT_WALK'], self.params['BODY_TILT_AT_WALK'] #
self.xt0, self.dy0, self.dy = self.step_length_planer(self.second_step_length, self.side_length, self.framestep, self.hovernum)
self.xtr1 = self.xtr
self.ztr = -self.params["GAIT_HEIGHT"]
if self.cycle == self.number_of_cycles - 1:
xtr2 = 0
else:
xtr2 = -self.xt0
self.dx0 = (xtr2 - self.xtr1) * self.framestep / self.params["FR2"]
self.dx = - self.dx0 * (self.params["FR2"] + self.hovernum * self.framestep) / (self.params["FR2"] - self.hovernum * self.framestep)
iii = (self.walk_cycle_step - self.walk_cycle_steps_each_leg) * self.framestep
if 2 * self.framestep < iii < self.params["FR2"] - 4 * self.framestep:
self.xt0, self.dy0, self.dy = self.step_length_planer(self.second_step_length, self.side_length, self.framestep, self.hovernum)
if self.cycle == self.number_of_cycles - 1:
xtr2 = 0
else:
xtr2 = -self.xt0
self.dx0 = (xtr2 - self.xtr) * self.framestep / (self.params["FR2"] - iii)
self.dx = (- self.xtr - self.xtl - self.dx0 * ((self.params["FR2"] - iii) / self.framestep + 3)) / (
(self.params["FR2"] - iii) / self.framestep - 3)
S = -self.params["AMPLITUDE"] / 2 * math.sin(self.alpha01 * iii)
self.ytr = -S - self.d10
self.ytl = -S + self.d10
self.ztl = -self.params["GAIT_HEIGHT"]
if iii == 0:
self.ztl = -self.params["GAIT_HEIGHT"] + self.params["STEP_HEIGHT"] / 3
elif iii == self.framestep:
self.ztl = -self.params["GAIT_HEIGHT"] + self.params["STEP_HEIGHT"] * 2 / 3
elif iii == self.params["FR2"] - self.framestep:
self.ztl = -self.params["GAIT_HEIGHT"] + self.params["STEP_HEIGHT"] / 4
elif iii == self.params["FR2"] - 2 * self.framestep:
self.ztl = -self.params["GAIT_HEIGHT"] + self.params["STEP_HEIGHT"] * 2 / 4
elif iii == self.params["FR2"] - 3 * self.framestep:
self.ztl = -self.params["GAIT_HEIGHT"] + self.params["STEP_HEIGHT"] * 3 / 4
else:
self.ztl = -self.params["GAIT_HEIGHT"] + self.params["STEP_HEIGHT"]
if self.cycle == self.number_of_cycles - 1:
if iii == (self.params["FR2"] - self.framestep):
self.ztl = -self.params["GAIT_HEIGHT"]
self.ytl = S + self.d10
if iii == 0 or iii == self.framestep or iii == 2 * self.framestep:
self.xtl += self.dx0
self.ytl = S + self.d10 + self.dy0 * iii
elif iii == self.params["FR2"] - self.framestep or iii == self.params["FR2"] - 2 * self.framestep or iii == self.params["FR2"] - 3 * self.framestep:
self.xtl += self.dx0
self.ytl = S + 64 + self.dy0 * 3 * self.framestep - self.dy * (self.params["FR2"] - self.hovernum * self.framestep) + self.dy0 * (
iii - (self.params["FR2"] - 3 * self.framestep))
else:
self.xtl += self.dx
self.ytl = S + 64 + self.dy0 * 3 * self.framestep - self.dy * (iii - 3 * self.framestep)
self.wr = self.wr_target * (1 - iii / (self.params["FR2"] - self.hovernum * self.framestep) * 2)
self.wl = self.wl_target * (1 - iii / (self.params["FR2"] - self.hovernum * self.framestep) * 2)
self.xtr += self.dx0
self.ytr += self.dy0
if self.ytl < 54:
self.ytl = 54
new_positions = self.get_feet_action()
self.walk_cycle_step += 1
if self.walk_cycle_step == self.total_walk_cycle_steps:
self.xr, self.xl, self.yr, self.yl = self.xr_old, self.xl_old, self.yr_old, self.yl_old
self.general_step += 1
self.walk_cycle_step = 0
return new_positions
class BaseAgent(object):
def __init__(self, random_mode=False, foot_only_mode=False):
self.motion = MotionSim(random_mode=random_mode, foot_only_mode=foot_only_mode)
self.prev_positions = None
def act(self, state):
positions = state[:-4]
imu = state[-4:]
if self.prev_positions is None:
self.prev_positions = positions
new_positions = self.motion.act(imu)
if new_positions is not None and len(new_positions):
self.prev_positions = new_positions
return self.prev_positions
# return new_positions
if __name__ == "__main__":
print('This is not main module!')
| [
"math.tan",
"numpy.random.choice",
"math.asin",
"math.sqrt",
"math.degrees",
"time.sleep",
"math.radians",
"math.cos",
"numpy.random.randint",
"math.fabs",
"math.atan2",
"numpy.random.uniform",
"math.sin",
"sys.path.append",
"math.atan"
] | [((506, 522), 'math.cos', 'math.cos', (['alpha5'], {}), '(alpha5)\n', (514, 522), False, 'import math\n'), ((538, 554), 'math.sin', 'math.sin', (['alpha5'], {}), '(alpha5)\n', (546, 554), False, 'import math\n'), ((569, 601), 'math.sqrt', 'math.sqrt', (['(x * x + y * y + z * z)'], {}), '(x * x + y * y + z * z)\n', (578, 601), False, 'import math\n'), ((6360, 6385), 'sys.path.append', 'sys.path.append', (['sim_path'], {}), '(sim_path)\n', (6375, 6385), False, 'import sys\n'), ((7417, 7432), 'time.sleep', 'time.sleep', (['(0.1)'], {}), '(0.1)\n', (7427, 7432), False, 'import time\n'), ((8061, 8076), 'time.sleep', 'time.sleep', (['(0.2)'], {}), '(0.2)\n', (8071, 8076), False, 'import time\n'), ((15783, 15798), 'math.radians', 'math.radians', (['X'], {}), '(X)\n', (15795, 15798), False, 'import math\n'), ((15830, 15845), 'math.radians', 'math.radians', (['Y'], {}), '(Y)\n', (15842, 15845), False, 'import math\n'), ((15876, 15891), 'math.radians', 'math.radians', (['Z'], {}), '(Z)\n', (15888, 15891), False, 'import math\n'), ((1104, 1120), 'math.cos', 'math.cos', (['alpha6'], {}), '(alpha6)\n', (1112, 1120), False, 'import math\n'), ((1138, 1154), 'math.sin', 'math.sin', (['alpha6'], {}), '(alpha6)\n', (1146, 1154), False, 'import math\n'), ((3279, 3304), 'math.tan', 'math.tan', (['alpha6m[i - kk]'], {}), '(alpha6m[i - kk])\n', (3287, 3304), False, 'import math\n'), ((3647, 3673), 'math.cos', 'math.cos', (['alpha6m[ii - kk]'], {}), '(alpha6m[ii - kk])\n', (3655, 3673), False, 'import math\n'), ((3691, 3717), 'math.sin', 'math.sin', (['alpha6m[ii - kk]'], {}), '(alpha6m[ii - kk])\n', (3699, 3717), False, 'import math\n'), ((3739, 3779), 'math.atan', 'math.atan', (['(-xp / (zp * cos6 - yp * sin6))'], {}), '(-xp / (zp * cos6 - yp * sin6))\n', (3748, 3779), False, 'import math\n'), ((3794, 3812), 'math.sin', 'math.sin', (['alpha987'], {}), '(alpha987)\n', (3802, 3812), False, 'import math\n'), ((3834, 3852), 'math.cos', 'math.cos', (['alpha987'], {}), '(alpha987)\n', (3842, 3852), False, 'import math\n'), ((7900, 7917), 'time.sleep', 'time.sleep', (['(0.001)'], {}), '(0.001)\n', (7910, 7917), False, 'import time\n'), ((15460, 15478), 'math.atan2', 'math.atan2', (['t0', 't1'], {}), '(t0, t1)\n', (15470, 15478), False, 'import math\n'), ((15618, 15631), 'math.asin', 'math.asin', (['t2'], {}), '(t2)\n', (15627, 15631), False, 'import math\n'), ((15735, 15753), 'math.atan2', 'math.atan2', (['t3', 't4'], {}), '(t3, t4)\n', (15745, 15753), False, 'import math\n'), ((10442, 10480), 'numpy.random.uniform', 'np.random.uniform', ([], {'low': '(0.001)', 'high': '(0.1)'}), '(low=0.001, high=0.1)\n', (10459, 10480), True, 'import numpy as np\n'), ((10519, 10559), 'numpy.random.uniform', 'np.random.uniform', ([], {'low': '(0.035)', 'high': '(0.085)'}), '(low=0.035, high=0.085)\n', (10536, 10559), True, 'import numpy as np\n'), ((10599, 10630), 'numpy.random.choice', 'np.random.choice', (['[True, False]'], {}), '([True, False])\n', (10615, 10630), True, 'import numpy as np\n'), ((10818, 10855), 'numpy.random.uniform', 'np.random.uniform', ([], {'low': '(40.0)', 'high': '(100)'}), '(low=40.0, high=100)\n', (10835, 10855), True, 'import numpy as np\n'), ((10892, 10927), 'numpy.random.uniform', 'np.random.uniform', ([], {'low': '(0.0)', 'high': '(20)'}), '(low=0.0, high=20)\n', (10909, 10927), True, 'import numpy as np\n'), ((10957, 10992), 'numpy.random.uniform', 'np.random.uniform', ([], {'low': '(5.0)', 'high': '(35)'}), '(low=5.0, high=35)\n', (10974, 10992), True, 'import numpy as np\n'), ((11016, 11050), 'numpy.random.randint', 'np.random.randint', ([], {'low': '(18)', 'high': '(24)'}), '(low=18, high=24)\n', (11033, 11050), True, 'import numpy as np\n'), ((11083, 11121), 'numpy.random.uniform', 'np.random.uniform', ([], {'low': '(180.0)', 'high': '(200)'}), '(low=180.0, high=200)\n', (11100, 11121), True, 'import numpy as np\n'), ((11153, 11189), 'numpy.random.uniform', 'np.random.uniform', ([], {'low': '(23.0)', 'high': '(45)'}), '(low=23.0, high=45)\n', (11170, 11189), True, 'import numpy as np\n'), ((20577, 20604), 'math.degrees', 'math.degrees', (['self.rotation'], {}), '(self.rotation)\n', (20589, 20604), False, 'import math\n'), ((1593, 1617), 'math.fabs', 'math.fabs', (['testalpha6[i]'], {}), '(testalpha6[i])\n', (1602, 1617), False, 'import math\n'), ((1620, 1644), 'math.fabs', 'math.fabs', (['testalpha6[k]'], {}), '(testalpha6[k])\n', (1629, 1644), False, 'import math\n'), ((1728, 1756), 'math.fabs', 'math.fabs', (['testalpha6[k - 1]'], {}), '(testalpha6[k - 1])\n', (1737, 1756), False, 'import math\n'), ((1757, 1785), 'math.fabs', 'math.fabs', (['testalpha6[k + 1]'], {}), '(testalpha6[k + 1])\n', (1766, 1785), False, 'import math\n'), ((2167, 2183), 'math.cos', 'math.cos', (['alpha6'], {}), '(alpha6)\n', (2175, 2183), False, 'import math\n'), ((2209, 2225), 'math.sin', 'math.sin', (['alpha6'], {}), '(alpha6)\n', (2217, 2225), False, 'import math\n'), ((3349, 3411), 'math.sqrt', 'math.sqrt', (['((zp - yp * tan6) ** 2 + xp * xp * (1 + tan6 * tan6))'], {}), '((zp - yp * tan6) ** 2 + xp * xp * (1 + tan6 * tan6))\n', (3358, 3411), False, 'import math\n'), ((4055, 4082), 'math.tan', 'math.tan', (['alpha10m[ii - kk]'], {}), '(alpha10m[ii - kk])\n', (4063, 4082), False, 'import math\n'), ((4442, 4458), 'math.asin', 'math.asin', (['temp2'], {}), '(temp2)\n', (4451, 4458), False, 'import math\n'), ((4489, 4505), 'math.asin', 'math.asin', (['temp3'], {}), '(temp3)\n', (4498, 4505), False, 'import math\n'), ((23423, 23451), 'math.sin', 'math.sin', (['(self.alpha01 * iii)'], {}), '(self.alpha01 * iii)\n', (23431, 23451), False, 'import math\n'), ((27265, 27293), 'math.sin', 'math.sin', (['(self.alpha01 * iii)'], {}), '(self.alpha01 * iii)\n', (27273, 27293), False, 'import math\n'), ((1302, 1349), 'math.sqrt', 'math.sqrt', (['((zp * cos - yp * sin) ** 2 + xp * xp)'], {}), '((zp * cos - yp * sin) ** 2 + xp * xp)\n', (1311, 1349), False, 'import math\n'), ((2505, 2529), 'math.fabs', 'math.fabs', (['testalpha6[i]'], {}), '(testalpha6[i])\n', (2514, 2529), False, 'import math\n'), ((2532, 2556), 'math.fabs', 'math.fabs', (['testalpha6[k]'], {}), '(testalpha6[k])\n', (2541, 2556), False, 'import math\n'), ((4000, 4027), 'math.cos', 'math.cos', (['alpha10m[ii - kk]'], {}), '(alpha10m[ii - kk])\n', (4008, 4027), False, 'import math\n'), ((4247, 4263), 'math.sqrt', 'math.sqrt', (['temp1'], {}), '(temp1)\n', (4256, 4263), False, 'import math\n'), ((4312, 4328), 'math.sqrt', 'math.sqrt', (['temp1'], {}), '(temp1)\n', (4321, 4328), False, 'import math\n'), ((4363, 4379), 'math.fabs', 'math.fabs', (['temp2'], {}), '(temp2)\n', (4372, 4379), False, 'import math\n'), ((4389, 4405), 'math.fabs', 'math.fabs', (['temp3'], {}), '(temp3)\n', (4398, 4405), False, 'import math\n'), ((2676, 2704), 'math.fabs', 'math.fabs', (['testalpha6[k - 1]'], {}), '(testalpha6[k - 1])\n', (2685, 2704), False, 'import math\n'), ((2705, 2733), 'math.fabs', 'math.fabs', (['testalpha6[k + 1]'], {}), '(testalpha6[k + 1])\n', (2714, 2733), False, 'import math\n'), ((2388, 2435), 'math.sqrt', 'math.sqrt', (['((zp * cos - yp * sin) ** 2 + xp * xp)'], {}), '((zp * cos - yp * sin) ** 2 + xp * xp)\n', (2397, 2435), False, 'import math\n'), ((4841, 4858), 'math.sin', 'math.sin', (['alpha91'], {}), '(alpha91)\n', (4849, 4858), False, 'import math\n'), ((4867, 4884), 'math.cos', 'math.cos', (['alpha91'], {}), '(alpha91)\n', (4875, 4884), False, 'import math\n'), ((4936, 4953), 'math.sin', 'math.sin', (['alpha92'], {}), '(alpha92)\n', (4944, 4953), False, 'import math\n'), ((4962, 4979), 'math.cos', 'math.cos', (['alpha92'], {}), '(alpha92)\n', (4970, 4979), False, 'import math\n')] |
from __future__ import print_function, absolute_import, division
from future.builtins import *
from future import standard_library
standard_library.install_aliases()
import future.utils
from functools import reduce
import fractions
import operator
import os
import re
import sys
import tempfile
from html.parser import HTMLParser
def make_none(*args, **kwargs):
return None
def if_not_none(item, default):
""" Equivalent to `item if item is not None else default` """
if item is None:
return default
else:
return item
class MLStripper(HTMLParser):
""" Strips markup language tags from a string.
FROM http://stackoverflow.com/a/925630/1958900
"""
def __init__(self):
if not future.utils.PY2:
super().__init__()
self.reset()
self.fed = []
self.strict = False
self.convert_charrefs = True
def handle_data(self, d):
self.fed.append(d)
def get_data(self):
return ''.join(self.fed)
def html_to_text(html):
"""
FROM http://stackoverflow.com/a/925630/1958900
"""
s = MLStripper()
s.unescape = True # convert HTML entities to text
s.feed(html)
return s.get_data()
def printflush(s, newline=True):
if newline:
print(s)
else:
print(s, end=' ')
sys.stdout.flush()
def which(cmd, mode=os.F_OK | os.X_OK, path=None):
"""Given a command, mode, and a PATH string, return the path which
conforms to the given mode on the PATH, or None if there is no such
file.
`mode` defaults to os.F_OK | os.X_OK. `path` defaults to the result
of os.environ.get("PATH"), or can be overridden with a custom search
path.
Note:
Copied without modification from Python 3.6.1 ``shutil.which`
source code
"""
# Check that a given file can be accessed with the correct mode.
# Additionally check that `file` is not a directory, as on Windows
# directories pass the os.access check.
def _access_check(fn, mode):
return (os.path.exists(fn) and os.access(fn, mode)
and not os.path.isdir(fn))
# If we're given a path with a directory part, look it up directly rather
# than referring to PATH directories. This includes checking relative to the
# current directory, e.g. ./script
if os.path.dirname(cmd):
if _access_check(cmd, mode):
return cmd
return None
if path is None:
path = os.environ.get("PATH", os.defpath)
if not path:
return None
path = path.split(os.pathsep)
if sys.platform == "win32":
# The current directory takes precedence on Windows.
if not os.curdir in path:
path.insert(0, os.curdir)
# PATHEXT is necessary to check on Windows.
pathext = os.environ.get("PATHEXT", "").split(os.pathsep)
# See if the given file matches any of the expected path extensions.
# This will allow us to short circuit when given "python.exe".
# If it does match, only test that one, otherwise we have to try
# others.
if any(cmd.lower().endswith(ext.lower()) for ext in pathext):
files = [cmd]
else:
files = [cmd + ext for ext in pathext]
else:
# On other platforms you don't have things like PATHEXT to tell you
# what file suffixes are executable, so just pass on cmd as-is.
files = [cmd]
seen = set()
for dir in path:
normdir = os.path.normcase(dir)
if not normdir in seen:
seen.add(normdir)
for thefile in files:
name = os.path.join(dir, thefile)
if _access_check(name, mode):
return name
return None
class methodcaller(object):
"""The pickleable implementation of the standard library operator.methodcaller.
This was copied without modification from:
https://github.com/python/cpython/blob/065990fa5bd30fb3ca61b90adebc7d8cb3f16b5a/Lib/operator.py
The c-extension version is not pickleable, so we keep a copy of the pure-python standard library
code here. See https://bugs.python.org/issue22955
Original documentation:
Return a callable object that calls the given method on its operand.
After f = methodcaller('name'), the call f(r) returns r.name().
After g = methodcaller('name', 'date', foo=1), the call g(r) returns
r.name('date', foo=1).
"""
__slots__ = ('_name', '_args', '_kwargs')
def __init__(*args, **kwargs):
if len(args) < 2:
msg = "methodcaller needs at least one argument, the method name"
raise TypeError(msg)
self = args[0]
self._name = args[1]
if not isinstance(self._name, future.utils.native_str):
raise TypeError('method name must be a string')
self._args = args[2:]
self._kwargs = kwargs
def __call__(self, obj):
return getattr(obj, self._name)(*self._args, **self._kwargs)
def __repr__(self):
args = [repr(self._name)]
args.extend(list(map(repr, self._args)))
args.extend('%s=%r' % (k, v) for k, v in list(self._kwargs.items()))
return '%s.%s(%s)' % (self.__class__.__module__,
self.__class__.__name__,
', '.join(args))
def __reduce__(self):
if not self._kwargs:
return self.__class__, (self._name,) + self._args
else:
from functools import partial
return partial(self.__class__, self._name, **self._kwargs), self._args
class textnotify(object):
""" Print a single, immediately flushed line to log the execution of a block.
Prints 'done' at the end of the line (or 'ERROR' if an uncaught exception)
Examples:
>>> import time
>>> with textnotify('starting to sleep'):
>>> time.sleep(3)
starting to sleep...done
>>> with textnotify('raising an exception...'):
>>> raise ValueError()
raising an exception...error
ValueError [...]
"""
def __init__(self, startmsg):
if startmsg.strip()[-3:] != '...':
startmsg = startmsg.strip() + '...'
self.startmsg = startmsg
def __enter__(self):
printflush(self.startmsg, newline=False)
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type is None:
printflush('done')
else:
printflush('ERROR')
class BaseTable(object):
def __init__(self, categories, fileobj=None):
self.categories = categories
self.lines = []
self.fileobj = fileobj
def add_line(self, obj):
if hasattr(obj, 'keys'):
newline = [obj.get(cat, '') for cat in self.categories]
else:
assert len(obj) == len(self.categories)
newline = obj
self.lines.append(newline)
self.writeline(newline)
def writeline(self, newline):
raise NotImplementedError()
def getstring(self):
raise NotImplementedError()
class MarkdownTable(BaseTable):
def __init__(self, *categories):
super().__init__(categories)
def markdown(self, replace=None):
if replace is None: replace = {}
outlines = ['| ' + ' | '.join(self.categories) + ' |',
'|-' + ''.join('|-' for x in self.categories) + '|']
for line in self.lines:
nextline = [str(replace.get(val, val)) for val in line]
outlines.append('| ' + ' | '.join(nextline) + ' |')
return '\n'.join(outlines)
def writeline(self, newline):
pass
def getstring(self):
return self.markdown()
def binomial_coefficient(n, k):
# credit to http://stackoverflow.com/users/226086/nas-banov
return int(reduce(operator.mul,
(fractions.Fraction(n - i, i + 1) for i in range(k)), 1))
def pairwise_displacements(a):
"""
:type a: numpy.array
from http://stackoverflow.com/questions/22390418/pairwise-displacement-vectors-among-set-of-points
"""
import numpy as np
n = a.shape[0]
d = a.shape[1]
c = binomial_coefficient(n, 2)
out = np.zeros((c, d))
l = 0
r = l + n - 1
for sl in range(1, n): # no point1 - point1!
out[l:r] = a[:n - sl] - a[sl:]
l = r
r += n - (sl + 1)
return out
def is_printable(s):
import string
for c in s:
if c not in string.printable:
return False
else:
return True
class _RedirectStream(object):
"""From python3.4 stdlib
"""
_stream = None
def __init__(self, new_target):
self._new_target = new_target
# We use a list of old targets to make this CM re-entrant
self._old_targets = []
def __enter__(self):
self._old_targets.append(getattr(sys, self._stream))
setattr(sys, self._stream, self._new_target)
return self._new_target
def __exit__(self, exctype, excinst, exctb):
setattr(sys, self._stream, self._old_targets.pop())
class redirect_stderr(_RedirectStream):
"""From python3.4 stdlib"""
_stream = "stderr"
GETFLOAT = re.compile(r'-?\d+(\.\d+)?(e[-+]?\d+)') # matches numbers, e.g. 1, -2.0, 3.5e50, 0.001e-10
def from_filepath(func, filelike):
"""Run func on a temporary *path* assigned to filelike"""
if type(filelike) == str:
return func(filelike)
else:
with tempfile.NamedTemporaryFile() as outfile:
outfile.write(filelike.read().encode()) # hack - prob need to detect bytes
outfile.flush()
result = func(outfile.name)
return result
| [
"os.path.exists",
"re.compile",
"os.access",
"os.environ.get",
"os.path.join",
"fractions.Fraction",
"future.standard_library.install_aliases",
"os.path.dirname",
"numpy.zeros",
"os.path.isdir",
"functools.partial",
"tempfile.NamedTemporaryFile",
"sys.stdout.flush",
"os.path.normcase"
] | [((131, 165), 'future.standard_library.install_aliases', 'standard_library.install_aliases', ([], {}), '()\n', (163, 165), False, 'from future import standard_library\n'), ((9231, 9273), 're.compile', 're.compile', (['"""-?\\\\d+(\\\\.\\\\d+)?(e[-+]?\\\\d+)"""'], {}), "('-?\\\\d+(\\\\.\\\\d+)?(e[-+]?\\\\d+)')\n", (9241, 9273), False, 'import re\n'), ((1328, 1346), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (1344, 1346), False, 'import sys\n'), ((2342, 2362), 'os.path.dirname', 'os.path.dirname', (['cmd'], {}), '(cmd)\n', (2357, 2362), False, 'import os\n'), ((8238, 8254), 'numpy.zeros', 'np.zeros', (['(c, d)'], {}), '((c, d))\n', (8246, 8254), True, 'import numpy as np\n'), ((2481, 2515), 'os.environ.get', 'os.environ.get', (['"""PATH"""', 'os.defpath'], {}), "('PATH', os.defpath)\n", (2495, 2515), False, 'import os\n'), ((3509, 3530), 'os.path.normcase', 'os.path.normcase', (['dir'], {}), '(dir)\n', (3525, 3530), False, 'import os\n'), ((2050, 2068), 'os.path.exists', 'os.path.exists', (['fn'], {}), '(fn)\n', (2064, 2068), False, 'import os\n'), ((2073, 2092), 'os.access', 'os.access', (['fn', 'mode'], {}), '(fn, mode)\n', (2082, 2092), False, 'import os\n'), ((9505, 9534), 'tempfile.NamedTemporaryFile', 'tempfile.NamedTemporaryFile', ([], {}), '()\n', (9532, 9534), False, 'import tempfile\n'), ((2117, 2134), 'os.path.isdir', 'os.path.isdir', (['fn'], {}), '(fn)\n', (2130, 2134), False, 'import os\n'), ((2824, 2853), 'os.environ.get', 'os.environ.get', (['"""PATHEXT"""', '""""""'], {}), "('PATHEXT', '')\n", (2838, 2853), False, 'import os\n'), ((3650, 3676), 'os.path.join', 'os.path.join', (['dir', 'thefile'], {}), '(dir, thefile)\n', (3662, 3676), False, 'import os\n'), ((5559, 5610), 'functools.partial', 'partial', (['self.__class__', 'self._name'], {}), '(self.__class__, self._name, **self._kwargs)\n', (5566, 5610), False, 'from functools import partial\n'), ((7897, 7929), 'fractions.Fraction', 'fractions.Fraction', (['(n - i)', '(i + 1)'], {}), '(n - i, i + 1)\n', (7915, 7929), False, 'import fractions\n')] |
# Copyright 2018 the GPflow 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 pytest
import tensorflow as tf
import gpflow
from gpflow.config import Config, as_context
from gpflow.utilities import set_trainable
from gpflow.utilities.traversal import (
_merge_leaf_components,
leaf_components,
tabulate_module_summary,
)
rng = np.random.RandomState(0)
class Data:
H0 = 5
H1 = 2
M = 10
D = 1
Z = 0.5 * np.ones((M, 1))
ls = 2.0
var = 1.0
# ------------------------------------------
# Helpers
# ------------------------------------------
class A(tf.Module):
def __init__(self, name=None):
super().__init__(name)
self.var_trainable = tf.Variable(tf.zeros((2, 2, 1)), trainable=True)
self.var_fixed = tf.Variable(tf.ones((2, 2, 1)), trainable=False)
class B(tf.Module):
def __init__(self, name=None):
super().__init__(name)
self.submodule_list = [A(), A()]
self.submodule_dict = dict(a=A(), b=A())
self.var_trainable = tf.Variable(tf.zeros((2, 2, 1)), trainable=True)
self.var_fixed = tf.Variable(tf.ones((2, 2, 1)), trainable=False)
class C(tf.keras.Model):
def __init__(self, name=None):
super().__init__(name)
self.variable = tf.Variable(tf.zeros((2, 2, 1)), trainable=True)
self.param = gpflow.Parameter(0.0)
self.dense = tf.keras.layers.Dense(5)
def create_kernel():
kern = gpflow.kernels.SquaredExponential(lengthscales=Data.ls, variance=Data.var)
set_trainable(kern.lengthscales, False)
return kern
def create_compose_kernel():
kernel = gpflow.kernels.Product(
[
gpflow.kernels.Sum([create_kernel(), create_kernel()]),
gpflow.kernels.Sum([create_kernel(), create_kernel()]),
]
)
return kernel
def create_model():
kernel = create_kernel()
model = gpflow.models.SVGP(
kernel=kernel,
likelihood=gpflow.likelihoods.Gaussian(variance_lower_bound=0.0),
inducing_variable=Data.Z,
q_diag=True,
)
set_trainable(model.q_mu, False)
return model
# ------------------------------------------
# Reference
# ------------------------------------------
example_tf_module_variable_dict = {
"A.var_trainable": {"value": np.zeros((2, 2, 1)), "trainable": True, "shape": (2, 2, 1),},
"A.var_fixed": {"value": np.ones((2, 2, 1)), "trainable": False, "shape": (2, 2, 1),},
}
example_module_list_variable_dict = {
"submodule_list[0].var_trainable": example_tf_module_variable_dict["A.var_trainable"],
"submodule_list[0].var_fixed": example_tf_module_variable_dict["A.var_fixed"],
"submodule_list[1].var_trainable": example_tf_module_variable_dict["A.var_trainable"],
"submodule_list[1].var_fixed": example_tf_module_variable_dict["A.var_fixed"],
"submodule_dict['a'].var_trainable": example_tf_module_variable_dict["A.var_trainable"],
"submodule_dict['a'].var_fixed": example_tf_module_variable_dict["A.var_fixed"],
"submodule_dict['b'].var_trainable": example_tf_module_variable_dict["A.var_trainable"],
"submodule_dict['b'].var_fixed": example_tf_module_variable_dict["A.var_fixed"],
"B.var_trainable": example_tf_module_variable_dict["A.var_trainable"],
"B.var_fixed": example_tf_module_variable_dict["A.var_fixed"],
}
kernel_param_dict = {
"SquaredExponential.lengthscales": {"value": Data.ls, "trainable": False, "shape": (),},
"SquaredExponential.variance": {"value": Data.var, "trainable": True, "shape": ()},
}
compose_kernel_param_dict = {
"kernels[0].kernels[0].variance": kernel_param_dict["SquaredExponential.variance"],
"kernels[0].kernels[0].lengthscales": kernel_param_dict["SquaredExponential.lengthscales"],
"kernels[0].kernels[1].variance": kernel_param_dict["SquaredExponential.variance"],
"kernels[0].kernels[1].lengthscales": kernel_param_dict["SquaredExponential.lengthscales"],
"kernels[1].kernels[0].variance": kernel_param_dict["SquaredExponential.variance"],
"kernels[1].kernels[0].lengthscales": kernel_param_dict["SquaredExponential.lengthscales"],
"kernels[1].kernels[1].variance": kernel_param_dict["SquaredExponential.variance"],
"kernels[1].kernels[1].lengthscales": kernel_param_dict["SquaredExponential.lengthscales"],
}
model_gp_param_dict = {
"kernel.lengthscales": kernel_param_dict["SquaredExponential.lengthscales"],
"kernel.variance": kernel_param_dict["SquaredExponential.variance"],
"likelihood.variance": {"value": 1.0, "trainable": True, "shape": ()},
"inducing_variable.Z": {"value": Data.Z, "trainable": True, "shape": (Data.M, Data.D),},
"SVGP.q_mu": {"value": np.zeros((Data.M, 1)), "trainable": False, "shape": (Data.M, 1),},
"SVGP.q_sqrt": {"value": np.ones((Data.M, 1)), "trainable": True, "shape": (Data.M, 1),},
}
example_dag_module_param_dict = {
"SVGP.kernel.variance\nSVGP.kernel.lengthscales": kernel_param_dict[
"SquaredExponential.lengthscales"
],
"SVGP.likelihood.variance": {"value": 1.0, "trainable": True, "shape": ()},
"SVGP.inducing_variable.Z": {"value": Data.Z, "trainable": True, "shape": (Data.M, Data.D),},
"SVGP.q_mu": {"value": np.zeros((Data.M, 1)), "trainable": False, "shape": (Data.M, 1),},
"SVGP.q_sqrt": {"value": np.ones((Data.M, 1)), "trainable": True, "shape": (Data.M, 1),},
}
compose_kernel_param_print_string = """\
name class transform prior trainable shape dtype value\n\
------------------------------------------ --------- ----------- ------- ----------- ------- ------- -------\n\
Product.kernels[0].kernels[0].variance Parameter Softplus True () float64 1\n\
Product.kernels[0].kernels[0].lengthscales Parameter Softplus False () float64 2\n\
Product.kernels[0].kernels[1].variance Parameter Softplus True () float64 1\n\
Product.kernels[0].kernels[1].lengthscales Parameter Softplus False () float64 2\n\
Product.kernels[1].kernels[0].variance Parameter Softplus True () float64 1\n\
Product.kernels[1].kernels[0].lengthscales Parameter Softplus False () float64 2\n\
Product.kernels[1].kernels[1].variance Parameter Softplus True () float64 1\n\
Product.kernels[1].kernels[1].lengthscales Parameter Softplus False () float64 2"""
kernel_param_print_string = """\
name class transform prior trainable shape dtype value\n\
------------------------------- --------- ----------- ------- ----------- ------- ------- -------\n\
SquaredExponential.variance Parameter Softplus True () float64 1\n\
SquaredExponential.lengthscales Parameter Softplus False () float64 2"""
kernel_param_print_string_with_shift = """\
name class transform prior trainable shape dtype value\n\
------------------------------- --------- ---------------- ------- ----------- ------- ------- -------\n\
SquaredExponential.variance Parameter Softplus + Shift True () float64 1\n\
SquaredExponential.lengthscales Parameter Softplus + Shift False () float64 2"""
model_gp_param_print_string = """\
name class transform prior trainable shape dtype value\n\
------------------------ --------- ----------- ------- ----------- ------- ------- --------\n\
SVGP.kernel.variance Parameter Softplus True () float64 1.0\n\
SVGP.kernel.lengthscales Parameter Softplus False () float64 2.0\n\
SVGP.likelihood.variance Parameter Softplus True () float64 1.0\n\
SVGP.inducing_variable.Z Parameter Identity True (10, 1) float64 [[0.5...\n\
SVGP.q_mu Parameter Identity False (10, 1) float64 [[0....\n\
SVGP.q_sqrt Parameter Softplus True (10, 1) float64 [[1...."""
example_tf_module_variable_print_string = """\
name class transform prior trainable shape dtype value\n\
--------------- ---------------- ----------- ------- ----------- --------- ------- --------\n\
A.var_trainable ResourceVariable True (2, 2, 1) float32 [[[0....\n\
A.var_fixed ResourceVariable False (2, 2, 1) float32 [[[1...."""
example_module_list_variable_print_string = """\
name class transform prior trainable shape dtype value\n\
----------------------------------- ---------------- ----------- ------- ----------- --------- ------- --------\n\
B.submodule_list[0].var_trainable ResourceVariable True (2, 2, 1) float32 [[[0....\n\
B.submodule_list[0].var_fixed ResourceVariable False (2, 2, 1) float32 [[[1....\n\
B.submodule_list[1].var_trainable ResourceVariable True (2, 2, 1) float32 [[[0....\n\
B.submodule_list[1].var_fixed ResourceVariable False (2, 2, 1) float32 [[[1....\n\
B.submodule_dict['a'].var_trainable ResourceVariable True (2, 2, 1) float32 [[[0....\n\
B.submodule_dict['a'].var_fixed ResourceVariable False (2, 2, 1) float32 [[[1....\n\
B.submodule_dict['b'].var_trainable ResourceVariable True (2, 2, 1) float32 [[[0....\n\
B.submodule_dict['b'].var_fixed ResourceVariable False (2, 2, 1) float32 [[[1....\n\
B.var_trainable ResourceVariable True (2, 2, 1) float32 [[[0....\n\
B.var_fixed ResourceVariable False (2, 2, 1) float32 [[[1...."""
# Note: we use grid format here because we have a double reference to the same variable
# which does not render nicely in the table formatting.
example_tf_keras_model = """\
+-------------------------+------------------+-------------+---------+-------------+-----------+---------+----------+\n\
| name | class | transform | prior | trainable | shape | dtype | value |\n\
+=========================+==================+=============+=========+=============+===========+=========+==========+\n\
| C._trainable_weights[0] | ResourceVariable | | | True | (2, 2, 1) | float32 | [[[0.... |\n\
| C.variable | | | | | | | |\n\
+-------------------------+------------------+-------------+---------+-------------+-----------+---------+----------+\n\
| C.param | Parameter | Identity | | True | () | float64 | 0.0 |\n\
+-------------------------+------------------+-------------+---------+-------------+-----------+---------+----------+"""
# ------------------------------------------
# Fixtures
# ------------------------------------------
@pytest.fixture(params=[A, B, create_kernel, create_model])
def module(request):
return request.param()
@pytest.fixture
def dag_module():
dag = create_model()
dag.kernel.variance = dag.kernel.lengthscales
return dag
# ------------------------------------------
# Tests
# ------------------------------------------
def test_leaf_components_only_returns_parameters_and_variables(module):
for path, variable in leaf_components(module).items():
assert isinstance(variable, tf.Variable) or isinstance(variable, gpflow.Parameter)
@pytest.mark.parametrize(
"module_callable, expected_param_dicts",
[(create_kernel, kernel_param_dict), (create_model, model_gp_param_dict)],
)
def test_leaf_components_registers_variable_properties(module_callable, expected_param_dicts):
module = module_callable()
for path, variable in leaf_components(module).items():
param_name = path.split(".")[-2] + "." + path.split(".")[-1]
assert isinstance(variable, gpflow.Parameter)
np.testing.assert_equal(variable.numpy(), expected_param_dicts[param_name]["value"])
assert variable.trainable == expected_param_dicts[param_name]["trainable"]
assert variable.shape == expected_param_dicts[param_name]["shape"]
@pytest.mark.parametrize(
"module_callable, expected_param_dicts", [(create_compose_kernel, compose_kernel_param_dict),],
)
def test_leaf_components_registers_compose_kernel_variable_properties(
module_callable, expected_param_dicts
):
module = module_callable()
leaf_components_dict = leaf_components(module)
assert len(leaf_components_dict) > 0
for path, variable in leaf_components_dict.items():
path_as_list = path.split(".")
param_name = path_as_list[-3] + "." + path_as_list[-2] + "." + path_as_list[-1]
assert isinstance(variable, gpflow.Parameter)
np.testing.assert_equal(variable.numpy(), expected_param_dicts[param_name]["value"])
assert variable.trainable == expected_param_dicts[param_name]["trainable"]
assert variable.shape == expected_param_dicts[param_name]["shape"]
@pytest.mark.parametrize(
"module_class, expected_var_dicts",
[(A, example_tf_module_variable_dict), (B, example_module_list_variable_dict),],
)
def test_leaf_components_registers_param_properties(module_class, expected_var_dicts):
module = module_class()
for path, variable in leaf_components(module).items():
var_name = path.split(".")[-2] + "." + path.split(".")[-1]
assert isinstance(variable, tf.Variable)
np.testing.assert_equal(variable.numpy(), expected_var_dicts[var_name]["value"])
assert variable.trainable == expected_var_dicts[var_name]["trainable"]
assert variable.shape == expected_var_dicts[var_name]["shape"]
@pytest.mark.parametrize("expected_var_dicts", [example_dag_module_param_dict])
def test_merge_leaf_components_merges_keys_with_same_values(dag_module, expected_var_dicts):
leaf_components_dict = leaf_components(dag_module)
for path, variable in _merge_leaf_components(leaf_components_dict).items():
assert path in expected_var_dicts
for sub_path in path.split("\n"):
assert sub_path in leaf_components_dict
assert leaf_components_dict[sub_path] is variable
@pytest.mark.parametrize(
"module_callable, expected_param_print_string",
[
(create_compose_kernel, compose_kernel_param_print_string),
(create_kernel, kernel_param_print_string),
(create_model, model_gp_param_print_string),
(A, example_tf_module_variable_print_string),
(B, example_module_list_variable_print_string),
],
)
def test_print_summary_output_string(module_callable, expected_param_print_string):
with as_context(Config(positive_minimum=0.0)):
assert tabulate_module_summary(module_callable()) == expected_param_print_string
def test_print_summary_output_string_with_positive_minimum():
with as_context(Config(positive_minimum=1e-6)):
assert tabulate_module_summary(create_kernel()) == kernel_param_print_string_with_shift
def test_print_summary_for_keras_model():
# Note: best to use `grid` formatting for `tf.keras.Model` printing
# because of the duplicates in the references to the variables.
assert tabulate_module_summary(C(), tablefmt="grid") == example_tf_keras_model
def test_leaf_components_combination_kernel():
"""
Regression test for kernel compositions - output for printing should not be empty (issue #1066).
"""
k = gpflow.kernels.SquaredExponential() + gpflow.kernels.SquaredExponential()
assert leaf_components(k), "Combination kernel should have non-empty leaf components"
def test_module_parameters_return_iterators_not_generators():
"""
Regression test: Ensure that gpflow.Module parameters return iterators like in TF2, not
generators.
Reason:
param = m.params # <generator object>
x = [p for p in param] # List[Parameters]
y = [p for p in param] # [] empty!
"""
m = create_model()
assert isinstance(m, gpflow.base.Module)
assert isinstance(m.parameters, tuple)
assert isinstance(m.trainable_parameters, tuple)
| [
"gpflow.config.Config",
"numpy.ones",
"gpflow.utilities.set_trainable",
"tensorflow.ones",
"gpflow.likelihoods.Gaussian",
"gpflow.kernels.SquaredExponential",
"gpflow.utilities.traversal.leaf_components",
"gpflow.Parameter",
"pytest.mark.parametrize",
"numpy.zeros",
"tensorflow.keras.layers.Dens... | [((868, 892), 'numpy.random.RandomState', 'np.random.RandomState', (['(0)'], {}), '(0)\n', (889, 892), True, 'import numpy as np\n'), ((12138, 12196), 'pytest.fixture', 'pytest.fixture', ([], {'params': '[A, B, create_kernel, create_model]'}), '(params=[A, B, create_kernel, create_model])\n', (12152, 12196), False, 'import pytest\n'), ((12698, 12842), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""module_callable, expected_param_dicts"""', '[(create_kernel, kernel_param_dict), (create_model, model_gp_param_dict)]'], {}), "('module_callable, expected_param_dicts', [(\n create_kernel, kernel_param_dict), (create_model, model_gp_param_dict)])\n", (12721, 12842), False, 'import pytest\n'), ((13411, 13534), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""module_callable, expected_param_dicts"""', '[(create_compose_kernel, compose_kernel_param_dict)]'], {}), "('module_callable, expected_param_dicts', [(\n create_compose_kernel, compose_kernel_param_dict)])\n", (13434, 13534), False, 'import pytest\n'), ((14268, 14411), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""module_class, expected_var_dicts"""', '[(A, example_tf_module_variable_dict), (B, example_module_list_variable_dict)]'], {}), "('module_class, expected_var_dicts', [(A,\n example_tf_module_variable_dict), (B, example_module_list_variable_dict)])\n", (14291, 14411), False, 'import pytest\n'), ((14952, 15030), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""expected_var_dicts"""', '[example_dag_module_param_dict]'], {}), "('expected_var_dicts', [example_dag_module_param_dict])\n", (14975, 15030), False, 'import pytest\n'), ((15460, 15798), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""module_callable, expected_param_print_string"""', '[(create_compose_kernel, compose_kernel_param_print_string), (create_kernel,\n kernel_param_print_string), (create_model, model_gp_param_print_string),\n (A, example_tf_module_variable_print_string), (B,\n example_module_list_variable_print_string)]'], {}), "('module_callable, expected_param_print_string', [(\n create_compose_kernel, compose_kernel_param_print_string), (\n create_kernel, kernel_param_print_string), (create_model,\n model_gp_param_print_string), (A,\n example_tf_module_variable_print_string), (B,\n example_module_list_variable_print_string)])\n", (15483, 15798), False, 'import pytest\n'), ((1968, 2042), 'gpflow.kernels.SquaredExponential', 'gpflow.kernels.SquaredExponential', ([], {'lengthscales': 'Data.ls', 'variance': 'Data.var'}), '(lengthscales=Data.ls, variance=Data.var)\n', (2001, 2042), False, 'import gpflow\n'), ((2047, 2086), 'gpflow.utilities.set_trainable', 'set_trainable', (['kern.lengthscales', '(False)'], {}), '(kern.lengthscales, False)\n', (2060, 2086), False, 'from gpflow.utilities import set_trainable\n'), ((2596, 2628), 'gpflow.utilities.set_trainable', 'set_trainable', (['model.q_mu', '(False)'], {}), '(model.q_mu, False)\n', (2609, 2628), False, 'from gpflow.utilities import set_trainable\n'), ((13712, 13735), 'gpflow.utilities.traversal.leaf_components', 'leaf_components', (['module'], {}), '(module)\n', (13727, 13735), False, 'from gpflow.utilities.traversal import _merge_leaf_components, leaf_components, tabulate_module_summary\n'), ((15151, 15178), 'gpflow.utilities.traversal.leaf_components', 'leaf_components', (['dag_module'], {}), '(dag_module)\n', (15166, 15178), False, 'from gpflow.utilities.traversal import _merge_leaf_components, leaf_components, tabulate_module_summary\n'), ((16797, 16815), 'gpflow.utilities.traversal.leaf_components', 'leaf_components', (['k'], {}), '(k)\n', (16812, 16815), False, 'from gpflow.utilities.traversal import _merge_leaf_components, leaf_components, tabulate_module_summary\n'), ((964, 979), 'numpy.ones', 'np.ones', (['(M, 1)'], {}), '((M, 1))\n', (971, 979), True, 'import numpy as np\n'), ((1866, 1887), 'gpflow.Parameter', 'gpflow.Parameter', (['(0.0)'], {}), '(0.0)\n', (1882, 1887), False, 'import gpflow\n'), ((1909, 1933), 'tensorflow.keras.layers.Dense', 'tf.keras.layers.Dense', (['(5)'], {}), '(5)\n', (1930, 1933), True, 'import tensorflow as tf\n'), ((2820, 2839), 'numpy.zeros', 'np.zeros', (['(2, 2, 1)'], {}), '((2, 2, 1))\n', (2828, 2839), True, 'import numpy as np\n'), ((2911, 2929), 'numpy.ones', 'np.ones', (['(2, 2, 1)'], {}), '((2, 2, 1))\n', (2918, 2929), True, 'import numpy as np\n'), ((5211, 5232), 'numpy.zeros', 'np.zeros', (['(Data.M, 1)'], {}), '((Data.M, 1))\n', (5219, 5232), True, 'import numpy as np\n'), ((5307, 5327), 'numpy.ones', 'np.ones', (['(Data.M, 1)'], {}), '((Data.M, 1))\n', (5314, 5327), True, 'import numpy as np\n'), ((5736, 5757), 'numpy.zeros', 'np.zeros', (['(Data.M, 1)'], {}), '((Data.M, 1))\n', (5744, 5757), True, 'import numpy as np\n'), ((5832, 5852), 'numpy.ones', 'np.ones', (['(Data.M, 1)'], {}), '((Data.M, 1))\n', (5839, 5852), True, 'import numpy as np\n'), ((16712, 16747), 'gpflow.kernels.SquaredExponential', 'gpflow.kernels.SquaredExponential', ([], {}), '()\n', (16745, 16747), False, 'import gpflow\n'), ((16750, 16785), 'gpflow.kernels.SquaredExponential', 'gpflow.kernels.SquaredExponential', ([], {}), '()\n', (16783, 16785), False, 'import gpflow\n'), ((1238, 1257), 'tensorflow.zeros', 'tf.zeros', (['(2, 2, 1)'], {}), '((2, 2, 1))\n', (1246, 1257), True, 'import tensorflow as tf\n'), ((1312, 1330), 'tensorflow.ones', 'tf.ones', (['(2, 2, 1)'], {}), '((2, 2, 1))\n', (1319, 1330), True, 'import tensorflow as tf\n'), ((1568, 1587), 'tensorflow.zeros', 'tf.zeros', (['(2, 2, 1)'], {}), '((2, 2, 1))\n', (1576, 1587), True, 'import tensorflow as tf\n'), ((1642, 1660), 'tensorflow.ones', 'tf.ones', (['(2, 2, 1)'], {}), '((2, 2, 1))\n', (1649, 1660), True, 'import tensorflow as tf\n'), ((1808, 1827), 'tensorflow.zeros', 'tf.zeros', (['(2, 2, 1)'], {}), '((2, 2, 1))\n', (1816, 1827), True, 'import tensorflow as tf\n'), ((2476, 2529), 'gpflow.likelihoods.Gaussian', 'gpflow.likelihoods.Gaussian', ([], {'variance_lower_bound': '(0.0)'}), '(variance_lower_bound=0.0)\n', (2503, 2529), False, 'import gpflow\n'), ((12571, 12594), 'gpflow.utilities.traversal.leaf_components', 'leaf_components', (['module'], {}), '(module)\n', (12586, 12594), False, 'from gpflow.utilities.traversal import _merge_leaf_components, leaf_components, tabulate_module_summary\n'), ((13001, 13024), 'gpflow.utilities.traversal.leaf_components', 'leaf_components', (['module'], {}), '(module)\n', (13016, 13024), False, 'from gpflow.utilities.traversal import _merge_leaf_components, leaf_components, tabulate_module_summary\n'), ((14561, 14584), 'gpflow.utilities.traversal.leaf_components', 'leaf_components', (['module'], {}), '(module)\n', (14576, 14584), False, 'from gpflow.utilities.traversal import _merge_leaf_components, leaf_components, tabulate_module_summary\n'), ((15205, 15249), 'gpflow.utilities.traversal._merge_leaf_components', '_merge_leaf_components', (['leaf_components_dict'], {}), '(leaf_components_dict)\n', (15227, 15249), False, 'from gpflow.utilities.traversal import _merge_leaf_components, leaf_components, tabulate_module_summary\n'), ((15939, 15967), 'gpflow.config.Config', 'Config', ([], {'positive_minimum': '(0.0)'}), '(positive_minimum=0.0)\n', (15945, 15967), False, 'from gpflow.config import Config, as_context\n'), ((16143, 16173), 'gpflow.config.Config', 'Config', ([], {'positive_minimum': '(1e-06)'}), '(positive_minimum=1e-06)\n', (16149, 16173), False, 'from gpflow.config import Config, as_context\n')] |
"""
This module is used to call Quantum Espresso simulation and parse its output
The user need to supply a complete input script with single-point scf
calculation, CELL_PARAMETERS, ATOMIC_POSITIONS, nat, ATOMIC_SPECIES
arguments. It is case sensitive. and the nat line should be the first
argument of the line it appears. The user can also opt to the ASE interface instead.
This module will copy the input template to a new file with "_run" suffix,
edit the atomic coordination in the ATOMIC_POSITIONS block and run the similation with the parallel set up given.
"""
import os
from subprocess import call
import time
import numpy as np
from flare import struc
from typing import List
name = "QE"
def run_dft_par(
dft_input,
structure,
dft_loc,
n_cpus=1,
dft_out="pwscf.out",
npool=None,
mpi="mpi",
**dft_kwargs,
):
"""run DFT calculation with given input template
and atomic configurations. if n_cpus == 1, it executes serial run.
:param dft_input: input template file name
:param structure: atomic configuration
:param dft_loc: relative/absolute executable of the DFT code
:param n_cpus: # of CPU for mpi
:param dft_out: output file name
:param npool: not used
:param mpi: not used
:param **dft_wargs: not used
:return: forces
"""
newfilename = edit_dft_input_positions(dft_input, structure)
if npool is None:
dft_command = f"{dft_loc} -i {newfilename}"
else:
dft_command = f"{dft_loc} -nk {npool} -i {newfilename}"
if n_cpus > 1:
if mpi == "mpi":
dft_command = f"mpirun -np {n_cpus} {dft_command}"
else:
dft_command = f"srun -n {n_cpus} --mpi=pmi2 {dft_command}"
with open(dft_out, "w+") as fout:
call(dft_command.split(), stdout=fout)
os.remove(newfilename)
return parse_dft_forces(dft_out)
def run_dft_en_par(dft_input, structure, dft_loc, n_cpus):
"""run DFT calculation with given input template
and atomic configurations. This function is not used atm
if n_cpus == 1, it executes serial run.
:param dft_input: input template file name
:param structure: atomic configuration
:param dft_loc: relative/absolute executable of the DFT code
:param n_cpus: # of CPU for mpi
:param dft_out: output file name
:param npool: not used
:param mpi: not used
:param **dft_wargs: not used
:return: forces, energy
"""
run_qe_path = dft_input
edit_dft_input_positions(run_qe_path, structure)
qe_command = "mpirun -np {n_cpus} {dft_loc} -i {run_qe_path}"
with open("pwscf.out", "w+") as fout:
call(qe_command.split(), stdout=fout)
forces, energy = parse_dft_forces_and_energy("pwscf.out")
return forces, energy
def run_dft_en_npool(qe_input, structure, dft_loc, npool):
run_qe_path = qe_input
edit_dft_input_positions(run_qe_path, structure)
qe_command = "mpirun {0} -npool {1} < {2} > {3}".format(
dft_loc, npool, run_qe_path, "pwscf.out"
)
call(qe_command, shell=True)
forces, energy = parse_dft_forces_and_energy("pwscf.out")
return forces, energy
def parse_dft_input(dft_input: str):
"""parse the input to get information of atomic configuration
:param dft_input: input file name
:return: positions, species, cell, masses
"""
positions = []
species = []
cell = []
with open(dft_input) as f:
lines = f.readlines()
# Find the cell and positions in the output file
cell_index = None
positions_index = None
nat = None
species_index = None
for i, line in enumerate(lines):
if "CELL_PARAMETERS" in line:
cell_index = int(i + 1)
if "ATOMIC_POSITIONS" in line:
positions_index = int(i + 1)
if "nat" in line:
nat = int(line.split("=")[1])
if "ATOMIC_SPECIES" in line:
species_index = int(i + 1)
assert cell_index is not None, "Failed to find cell in input"
assert positions_index is not None, "Failed to find positions in input"
assert nat is not None, "Failed to find number of atoms in input"
assert species_index is not None, "Failed to find atomic species in input"
# Load cell
for i in range(cell_index, cell_index + 3):
cell_line = lines[i].strip()
cell.append(np.fromstring(cell_line, sep=" "))
cell = np.array(cell)
# Check cell IO
assert len(cell) != 0, "Cell failed to load"
assert np.shape(cell) == (3, 3), "Cell failed to load correctly"
# Load positions
for i in range(positions_index, positions_index + nat):
line_string = lines[i].strip().split()
species.append(line_string[0])
pos_string = " ".join(line_string[1:4])
positions.append(np.fromstring(pos_string, sep=" "))
# Check position IO
assert positions != [], "Positions failed to load"
positions = np.array(positions)
# see conversions.nb for conversion from amu to md units
massconvert = 0.000103642695727
masses = {}
for i in range(species_index, species_index + len(set(species))):
# Expects lines of format like: H 1.0 H_pseudo_name.ext
line = lines[i].strip().split()
masses[line[0]] = float(line[1]) * massconvert
return positions, species, cell, masses
def dft_input_to_structure(dft_input: str):
"""Parses a qe input and returns the atoms in the
file as a Structure object
:param dft_input: QE Input file to parse
:return: class Structure
"""
positions, species, cell, masses = parse_dft_input(dft_input)
_, coded_species = struc.get_unique_species(species)
return struc.Structure(
positions=positions,
species=coded_species,
cell=cell,
mass_dict=masses,
species_labels=species,
)
def edit_dft_input_positions(dft_input: str, structure):
"""
Write the current configuration of the OTF structure to the
qe input file
:param dft_input: dft input file name
:param structure: atomic structure to compute
:return: the name of the edited file
"""
with open(dft_input, "r") as f:
lines = f.readlines()
file_pos_index = None
cell_index = None
nat = None
for i, line in enumerate(lines):
if "ATOMIC_POSITIONS" in line:
file_pos_index = int(i + 1)
if "CELL_PARAMETERS" in line:
cell_index = int(i + 1)
# Load nat into variable then overwrite it with new nat
if "nat" in line:
nat = int(line.split("=")[1])
nat_index = int(i)
lines[nat_index] = "nat = " + str(structure.nat) + "\n"
assert file_pos_index is not None, "Failed to find positions in input"
assert cell_index is not None, "Failed to find cell in input"
assert nat is not None, "Failed to find nat in input"
# TODO Catch case where the punchout structure has more atoms than the
# original structure
for pos_index, line_index in enumerate(
range(file_pos_index, file_pos_index + structure.nat)
):
pos_string = " ".join(
[
structure.species_labels[pos_index],
str(structure.positions[pos_index][0]),
str(structure.positions[pos_index][1]),
str(structure.positions[pos_index][2]),
]
)
if line_index < len(lines):
lines[line_index] = str(pos_string + "\n")
else:
lines.append(str(pos_string + "\n"))
# TODO current assumption: if there is a new structure, then the new
# structure has fewer atoms than the previous one. If we are always
# 'editing' a version of the larger structure than this will be okay with
# the punchout method.
for line_index in range(file_pos_index + structure.nat, file_pos_index + nat):
lines[line_index] = ""
lines[cell_index] = " ".join([str(x) for x in structure.vec1]) + "\n"
lines[cell_index + 1] = " ".join([str(x) for x in structure.vec2]) + "\n"
lines[cell_index + 2] = " ".join([str(x) for x in structure.vec3]) + "\n"
newfilename = dft_input + "_run"
with open(newfilename, "w") as f:
for line in lines:
f.write(line)
return newfilename
def parse_dft_forces(outfile: str):
"""
Get forces from a pwscf file in eV/A
:param outfile: str, Path to pwscf output file
:return: list[nparray] , List of forces acting on atoms
"""
forces = []
total_energy = np.nan
with open(outfile, "r") as outf:
for line in outf:
if line.lower().startswith("! total energy"):
total_energy = float(line.split()[-2])
if line.find("force") != -1 and line.find("atom") != -1:
line = line.split("force =")[-1]
line = line.strip()
line = line.split(" ")
line = [x for x in line if x != ""]
temp_forces = []
for x in line:
temp_forces.append(float(x))
forces.append(np.array(list(temp_forces)))
assert (
total_energy != np.nan
), "Quantum ESPRESSO parser failed to read the file {}. Run failed.".format(outfile)
# Convert from ry/au to ev/angstrom
conversion_factor = 25.71104309541616
forces = [conversion_factor * force for force in forces]
forces = np.array(forces)
return forces
def parse_dft_forces_and_energy(outfile: str):
"""
Get forces from a pwscf file in eV/A
:param outfile: str, Path to pwscf output file
:return: list[nparray] , List of forces acting on atoms
"""
forces = []
total_energy = np.nan
with open(outfile, "r") as outf:
for line in outf:
if line.lower().startswith("! total energy"):
total_energy = float(line.split()[-2])
if line.find("force") != -1 and line.find("atom") != -1:
line = line.split("force =")[-1]
line = line.strip()
line = line.split(" ")
line = [x for x in line if x != ""]
temp_forces = []
for x in line:
temp_forces.append(float(x))
forces.append(np.array(list(temp_forces)))
assert (
total_energy != np.nan
), "Quantum ESPRESSO parser failed to read the file {}. Run failed.".format(outfile)
# Convert from ry/au to ev/angstrom
conversion_factor = 25.71104309541616
forces = [conversion_factor * force for force in forces]
forces = np.array(forces)
return forces, total_energy
| [
"flare.struc.get_unique_species",
"numpy.array",
"subprocess.call",
"flare.struc.Structure",
"numpy.shape",
"numpy.fromstring",
"os.remove"
] | [((1834, 1856), 'os.remove', 'os.remove', (['newfilename'], {}), '(newfilename)\n', (1843, 1856), False, 'import os\n'), ((3069, 3097), 'subprocess.call', 'call', (['qe_command'], {'shell': '(True)'}), '(qe_command, shell=True)\n', (3073, 3097), False, 'from subprocess import call\n'), ((4437, 4451), 'numpy.array', 'np.array', (['cell'], {}), '(cell)\n', (4445, 4451), True, 'import numpy as np\n'), ((4965, 4984), 'numpy.array', 'np.array', (['positions'], {}), '(positions)\n', (4973, 4984), True, 'import numpy as np\n'), ((5676, 5709), 'flare.struc.get_unique_species', 'struc.get_unique_species', (['species'], {}), '(species)\n', (5700, 5709), False, 'from flare import struc\n'), ((5721, 5837), 'flare.struc.Structure', 'struc.Structure', ([], {'positions': 'positions', 'species': 'coded_species', 'cell': 'cell', 'mass_dict': 'masses', 'species_labels': 'species'}), '(positions=positions, species=coded_species, cell=cell,\n mass_dict=masses, species_labels=species)\n', (5736, 5837), False, 'from flare import struc\n'), ((9473, 9489), 'numpy.array', 'np.array', (['forces'], {}), '(forces)\n', (9481, 9489), True, 'import numpy as np\n'), ((10659, 10675), 'numpy.array', 'np.array', (['forces'], {}), '(forces)\n', (10667, 10675), True, 'import numpy as np\n'), ((4533, 4547), 'numpy.shape', 'np.shape', (['cell'], {}), '(cell)\n', (4541, 4547), True, 'import numpy as np\n'), ((4391, 4424), 'numpy.fromstring', 'np.fromstring', (['cell_line'], {'sep': '""" """'}), "(cell_line, sep=' ')\n", (4404, 4424), True, 'import numpy as np\n'), ((4834, 4868), 'numpy.fromstring', 'np.fromstring', (['pos_string'], {'sep': '""" """'}), "(pos_string, sep=' ')\n", (4847, 4868), True, 'import numpy as np\n')] |
import numpy as np
import random
from collections import defaultdict
class Agent:
def __init__(self, nA=6 ):
""" Initialize agent.
Params
======
- nA: number of actions available to the agent
"""
self.nA = nA
self.Q = defaultdict(lambda: np.zeros(self.nA))
self.alpha=0.1
self.eps = 1.0
self.eps_min = 0.005
self.episode_i = 1
self.method = 'EXPECTED_SARSA'
def select_action(self, state):
""" Given the state, select an action.
It implements an e-greedy policy
Params
======
- state: the current state of the environment
Returns
=======
- action: an integer, compatible with the task's action space
"""
#Implementing an eps-greedy
if state in self.Q and random.uniform(0,1) > self.eps:
return np.argmax( self.Q[state] )
else:
return np.random.choice(self.nA)
def update_q_sarsamax( self, state, action, reward, next_state ):
q_current = self.Q[state][action]
q_target = np.max( self.Q[next_state] ) + reward
return q_current + self.alpha*( q_target - q_current )
def update_q_sarsa( self, state, action, reward, next_state ):
q_current = self.Q[state][action]
next_expected_action = self.select_action( state )
q_target = self.Q[next_state][next_expected_action] + reward
return q_current + self.alpha*( q_target - q_current )
def update_q_expected_sarsa( self, state, action, reward, next_state ):
q_current = self.Q[state][action]
p_probs = np.ones( self.nA )*(self.eps)/self.nA
p_probs[ np.argmax( self.Q[ next_state ] ) ] = 1.0 - ( self.nA - 1 )*self.eps/self.nA
expected_Q = np.dot( self.Q[next_state], p_probs )
q_target = expected_Q + reward
return q_current + self.alpha*( q_target - q_current )
def step(self, state, action, reward, next_state, done):
""" Update the agent's knowledge, using the most recently sampled tuple.
Params
======
- state: the previous state of the environment
- action: the agent's previous choice of action
- reward: last reward received
- next_state: the current state of the environment
- done: whether the episode is complete (True or False)
"""
if( self.method == 'SARSA' ):
self.Q[state][action] = self.update_q_sarsa( state, action, reward, next_state )
elif( self.method == 'SARSA_MAX' ):
self.Q[state][action] = self.update_q_sarsamax( state, action, reward, next_state )
elif( self.method == 'EXPECTED_SARSA' ):
self.Q[state][action] = self.update_q_expected_sarsa( state, action, reward, next_state )
if done:
self.eps = max( 1.0/self.episode_i, self.eps_min ) #Deixa 1% de probabilidade de explorar
self.episode_i += 1 | [
"random.uniform",
"numpy.ones",
"numpy.random.choice",
"numpy.argmax",
"numpy.max",
"numpy.dot",
"numpy.zeros"
] | [((1831, 1866), 'numpy.dot', 'np.dot', (['self.Q[next_state]', 'p_probs'], {}), '(self.Q[next_state], p_probs)\n', (1837, 1866), True, 'import numpy as np\n'), ((907, 931), 'numpy.argmax', 'np.argmax', (['self.Q[state]'], {}), '(self.Q[state])\n', (916, 931), True, 'import numpy as np\n'), ((967, 992), 'numpy.random.choice', 'np.random.choice', (['self.nA'], {}), '(self.nA)\n', (983, 992), True, 'import numpy as np\n'), ((1126, 1152), 'numpy.max', 'np.max', (['self.Q[next_state]'], {}), '(self.Q[next_state])\n', (1132, 1152), True, 'import numpy as np\n'), ((1731, 1760), 'numpy.argmax', 'np.argmax', (['self.Q[next_state]'], {}), '(self.Q[next_state])\n', (1740, 1760), True, 'import numpy as np\n'), ((301, 318), 'numpy.zeros', 'np.zeros', (['self.nA'], {}), '(self.nA)\n', (309, 318), True, 'import numpy as np\n'), ((856, 876), 'random.uniform', 'random.uniform', (['(0)', '(1)'], {}), '(0, 1)\n', (870, 876), False, 'import random\n'), ((1675, 1691), 'numpy.ones', 'np.ones', (['self.nA'], {}), '(self.nA)\n', (1682, 1691), True, 'import numpy as np\n')] |
"""
Tests for Series cumulative operations.
See also
--------
tests.frame.test_cumulative
"""
from itertools import product
import numpy as np
import pytest
import pandas as pd
from pandas import _is_numpy_dev
import pandas._testing as tm
def _check_accum_op(name, series, check_dtype=True):
func = getattr(np, name)
tm.assert_numpy_array_equal(
func(series).values, func(np.array(series)), check_dtype=check_dtype,
)
# with missing values
ts = series.copy()
ts[::2] = np.NaN
result = func(ts)[1::2]
expected = func(np.array(ts.dropna()))
tm.assert_numpy_array_equal(result.values, expected, check_dtype=False)
class TestSeriesCumulativeOps:
def test_cumsum(self, datetime_series):
_check_accum_op("cumsum", datetime_series)
def test_cumprod(self, datetime_series):
_check_accum_op("cumprod", datetime_series)
@pytest.mark.xfail(
_is_numpy_dev,
reason="https://github.com/pandas-dev/pandas/issues/31992",
strict=False,
)
def test_cummin(self, datetime_series):
tm.assert_numpy_array_equal(
datetime_series.cummin().values,
np.minimum.accumulate(np.array(datetime_series)),
)
ts = datetime_series.copy()
ts[::2] = np.NaN
result = ts.cummin()[1::2]
expected = np.minimum.accumulate(ts.dropna())
tm.assert_series_equal(result, expected)
@pytest.mark.xfail(
_is_numpy_dev,
reason="https://github.com/pandas-dev/pandas/issues/31992",
strict=False,
)
def test_cummax(self, datetime_series):
tm.assert_numpy_array_equal(
datetime_series.cummax().values,
np.maximum.accumulate(np.array(datetime_series)),
)
ts = datetime_series.copy()
ts[::2] = np.NaN
result = ts.cummax()[1::2]
expected = np.maximum.accumulate(ts.dropna())
tm.assert_series_equal(result, expected)
@pytest.mark.parametrize("tz", [None, "US/Pacific"])
def test_cummin_datetime64(self, tz):
s = pd.Series(
pd.to_datetime(
["NaT", "2000-1-2", "NaT", "2000-1-1", "NaT", "2000-1-3"]
).tz_localize(tz)
)
expected = pd.Series(
pd.to_datetime(
["NaT", "2000-1-2", "NaT", "2000-1-1", "NaT", "2000-1-1"]
).tz_localize(tz)
)
result = s.cummin(skipna=True)
tm.assert_series_equal(expected, result)
expected = pd.Series(
pd.to_datetime(
["NaT", "2000-1-2", "2000-1-2", "2000-1-1", "2000-1-1", "2000-1-1"]
).tz_localize(tz)
)
result = s.cummin(skipna=False)
tm.assert_series_equal(expected, result)
@pytest.mark.parametrize("tz", [None, "US/Pacific"])
def test_cummax_datetime64(self, tz):
s = pd.Series(
pd.to_datetime(
["NaT", "2000-1-2", "NaT", "2000-1-1", "NaT", "2000-1-3"]
).tz_localize(tz)
)
expected = pd.Series(
pd.to_datetime(
["NaT", "2000-1-2", "NaT", "2000-1-2", "NaT", "2000-1-3"]
).tz_localize(tz)
)
result = s.cummax(skipna=True)
tm.assert_series_equal(expected, result)
expected = pd.Series(
pd.to_datetime(
["NaT", "2000-1-2", "2000-1-2", "2000-1-2", "2000-1-2", "2000-1-3"]
).tz_localize(tz)
)
result = s.cummax(skipna=False)
tm.assert_series_equal(expected, result)
def test_cummin_timedelta64(self):
s = pd.Series(pd.to_timedelta(["NaT", "2 min", "NaT", "1 min", "NaT", "3 min"]))
expected = pd.Series(
pd.to_timedelta(["NaT", "2 min", "NaT", "1 min", "NaT", "1 min"])
)
result = s.cummin(skipna=True)
tm.assert_series_equal(expected, result)
expected = pd.Series(
pd.to_timedelta(["NaT", "2 min", "2 min", "1 min", "1 min", "1 min"])
)
result = s.cummin(skipna=False)
tm.assert_series_equal(expected, result)
def test_cummax_timedelta64(self):
s = pd.Series(pd.to_timedelta(["NaT", "2 min", "NaT", "1 min", "NaT", "3 min"]))
expected = pd.Series(
pd.to_timedelta(["NaT", "2 min", "NaT", "2 min", "NaT", "3 min"])
)
result = s.cummax(skipna=True)
tm.assert_series_equal(expected, result)
expected = pd.Series(
pd.to_timedelta(["NaT", "2 min", "2 min", "2 min", "2 min", "3 min"])
)
result = s.cummax(skipna=False)
tm.assert_series_equal(expected, result)
def test_cummethods_bool(self):
# GH#6270
a = pd.Series([False, False, False, True, True, False, False])
b = ~a
c = pd.Series([False] * len(b))
d = ~c
methods = {
"cumsum": np.cumsum,
"cumprod": np.cumprod,
"cummin": np.minimum.accumulate,
"cummax": np.maximum.accumulate,
}
args = product((a, b, c, d), methods)
for s, method in args:
expected = pd.Series(methods[method](s.values))
result = getattr(s, method)()
tm.assert_series_equal(result, expected)
e = pd.Series([False, True, np.nan, False])
cse = pd.Series([0, 1, np.nan, 1], dtype=object)
cpe = pd.Series([False, 0, np.nan, 0])
cmin = pd.Series([False, False, np.nan, False])
cmax = pd.Series([False, True, np.nan, True])
expecteds = {"cumsum": cse, "cumprod": cpe, "cummin": cmin, "cummax": cmax}
for method in methods:
res = getattr(e, method)()
tm.assert_series_equal(res, expecteds[method])
| [
"pandas.Series",
"pandas._testing.assert_series_equal",
"pandas.to_timedelta",
"pytest.mark.xfail",
"itertools.product",
"pytest.mark.parametrize",
"pandas._testing.assert_numpy_array_equal",
"numpy.array",
"pandas.to_datetime"
] | [((621, 692), 'pandas._testing.assert_numpy_array_equal', 'tm.assert_numpy_array_equal', (['result.values', 'expected'], {'check_dtype': '(False)'}), '(result.values, expected, check_dtype=False)\n', (648, 692), True, 'import pandas._testing as tm\n'), ((935, 1046), 'pytest.mark.xfail', 'pytest.mark.xfail', (['_is_numpy_dev'], {'reason': '"""https://github.com/pandas-dev/pandas/issues/31992"""', 'strict': '(False)'}), "(_is_numpy_dev, reason=\n 'https://github.com/pandas-dev/pandas/issues/31992', strict=False)\n", (952, 1046), False, 'import pytest\n'), ((1494, 1605), 'pytest.mark.xfail', 'pytest.mark.xfail', (['_is_numpy_dev'], {'reason': '"""https://github.com/pandas-dev/pandas/issues/31992"""', 'strict': '(False)'}), "(_is_numpy_dev, reason=\n 'https://github.com/pandas-dev/pandas/issues/31992', strict=False)\n", (1511, 1605), False, 'import pytest\n'), ((2053, 2104), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""tz"""', "[None, 'US/Pacific']"], {}), "('tz', [None, 'US/Pacific'])\n", (2076, 2104), False, 'import pytest\n'), ((2875, 2926), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""tz"""', "[None, 'US/Pacific']"], {}), "('tz', [None, 'US/Pacific'])\n", (2898, 2926), False, 'import pytest\n'), ((1445, 1485), 'pandas._testing.assert_series_equal', 'tm.assert_series_equal', (['result', 'expected'], {}), '(result, expected)\n', (1467, 1485), True, 'import pandas._testing as tm\n'), ((2004, 2044), 'pandas._testing.assert_series_equal', 'tm.assert_series_equal', (['result', 'expected'], {}), '(result, expected)\n', (2026, 2044), True, 'import pandas._testing as tm\n'), ((2546, 2586), 'pandas._testing.assert_series_equal', 'tm.assert_series_equal', (['expected', 'result'], {}), '(expected, result)\n', (2568, 2586), True, 'import pandas._testing as tm\n'), ((2826, 2866), 'pandas._testing.assert_series_equal', 'tm.assert_series_equal', (['expected', 'result'], {}), '(expected, result)\n', (2848, 2866), True, 'import pandas._testing as tm\n'), ((3368, 3408), 'pandas._testing.assert_series_equal', 'tm.assert_series_equal', (['expected', 'result'], {}), '(expected, result)\n', (3390, 3408), True, 'import pandas._testing as tm\n'), ((3648, 3688), 'pandas._testing.assert_series_equal', 'tm.assert_series_equal', (['expected', 'result'], {}), '(expected, result)\n', (3670, 3688), True, 'import pandas._testing as tm\n'), ((3993, 4033), 'pandas._testing.assert_series_equal', 'tm.assert_series_equal', (['expected', 'result'], {}), '(expected, result)\n', (4015, 4033), True, 'import pandas._testing as tm\n'), ((4211, 4251), 'pandas._testing.assert_series_equal', 'tm.assert_series_equal', (['expected', 'result'], {}), '(expected, result)\n', (4233, 4251), True, 'import pandas._testing as tm\n'), ((4556, 4596), 'pandas._testing.assert_series_equal', 'tm.assert_series_equal', (['expected', 'result'], {}), '(expected, result)\n', (4578, 4596), True, 'import pandas._testing as tm\n'), ((4774, 4814), 'pandas._testing.assert_series_equal', 'tm.assert_series_equal', (['expected', 'result'], {}), '(expected, result)\n', (4796, 4814), True, 'import pandas._testing as tm\n'), ((4888, 4946), 'pandas.Series', 'pd.Series', (['[False, False, False, True, True, False, False]'], {}), '([False, False, False, True, True, False, False])\n', (4897, 4946), True, 'import pandas as pd\n'), ((5230, 5260), 'itertools.product', 'product', (['(a, b, c, d)', 'methods'], {}), '((a, b, c, d), methods)\n', (5237, 5260), False, 'from itertools import product\n'), ((5466, 5505), 'pandas.Series', 'pd.Series', (['[False, True, np.nan, False]'], {}), '([False, True, np.nan, False])\n', (5475, 5505), True, 'import pandas as pd\n'), ((5521, 5563), 'pandas.Series', 'pd.Series', (['[0, 1, np.nan, 1]'], {'dtype': 'object'}), '([0, 1, np.nan, 1], dtype=object)\n', (5530, 5563), True, 'import pandas as pd\n'), ((5579, 5611), 'pandas.Series', 'pd.Series', (['[False, 0, np.nan, 0]'], {}), '([False, 0, np.nan, 0])\n', (5588, 5611), True, 'import pandas as pd\n'), ((5628, 5668), 'pandas.Series', 'pd.Series', (['[False, False, np.nan, False]'], {}), '([False, False, np.nan, False])\n', (5637, 5668), True, 'import pandas as pd\n'), ((5685, 5723), 'pandas.Series', 'pd.Series', (['[False, True, np.nan, True]'], {}), '([False, True, np.nan, True])\n', (5694, 5723), True, 'import pandas as pd\n'), ((413, 429), 'numpy.array', 'np.array', (['series'], {}), '(series)\n', (421, 429), True, 'import numpy as np\n'), ((3754, 3819), 'pandas.to_timedelta', 'pd.to_timedelta', (["['NaT', '2 min', 'NaT', '1 min', 'NaT', '3 min']"], {}), "(['NaT', '2 min', 'NaT', '1 min', 'NaT', '3 min'])\n", (3769, 3819), True, 'import pandas as pd\n'), ((3867, 3932), 'pandas.to_timedelta', 'pd.to_timedelta', (["['NaT', '2 min', 'NaT', '1 min', 'NaT', '1 min']"], {}), "(['NaT', '2 min', 'NaT', '1 min', 'NaT', '1 min'])\n", (3882, 3932), True, 'import pandas as pd\n'), ((4080, 4149), 'pandas.to_timedelta', 'pd.to_timedelta', (["['NaT', '2 min', '2 min', '1 min', '1 min', '1 min']"], {}), "(['NaT', '2 min', '2 min', '1 min', '1 min', '1 min'])\n", (4095, 4149), True, 'import pandas as pd\n'), ((4317, 4382), 'pandas.to_timedelta', 'pd.to_timedelta', (["['NaT', '2 min', 'NaT', '1 min', 'NaT', '3 min']"], {}), "(['NaT', '2 min', 'NaT', '1 min', 'NaT', '3 min'])\n", (4332, 4382), True, 'import pandas as pd\n'), ((4430, 4495), 'pandas.to_timedelta', 'pd.to_timedelta', (["['NaT', '2 min', 'NaT', '2 min', 'NaT', '3 min']"], {}), "(['NaT', '2 min', 'NaT', '2 min', 'NaT', '3 min'])\n", (4445, 4495), True, 'import pandas as pd\n'), ((4643, 4712), 'pandas.to_timedelta', 'pd.to_timedelta', (["['NaT', '2 min', '2 min', '2 min', '2 min', '3 min']"], {}), "(['NaT', '2 min', '2 min', '2 min', '2 min', '3 min'])\n", (4658, 4712), True, 'import pandas as pd\n'), ((5410, 5450), 'pandas._testing.assert_series_equal', 'tm.assert_series_equal', (['result', 'expected'], {}), '(result, expected)\n', (5432, 5450), True, 'import pandas._testing as tm\n'), ((5896, 5942), 'pandas._testing.assert_series_equal', 'tm.assert_series_equal', (['res', 'expecteds[method]'], {}), '(res, expecteds[method])\n', (5918, 5942), True, 'import pandas._testing as tm\n'), ((1241, 1266), 'numpy.array', 'np.array', (['datetime_series'], {}), '(datetime_series)\n', (1249, 1266), True, 'import numpy as np\n'), ((1800, 1825), 'numpy.array', 'np.array', (['datetime_series'], {}), '(datetime_series)\n', (1808, 1825), True, 'import numpy as np\n'), ((2185, 2258), 'pandas.to_datetime', 'pd.to_datetime', (["['NaT', '2000-1-2', 'NaT', '2000-1-1', 'NaT', '2000-1-3']"], {}), "(['NaT', '2000-1-2', 'NaT', '2000-1-1', 'NaT', '2000-1-3'])\n", (2199, 2258), True, 'import pandas as pd\n'), ((2364, 2437), 'pandas.to_datetime', 'pd.to_datetime', (["['NaT', '2000-1-2', 'NaT', '2000-1-1', 'NaT', '2000-1-1']"], {}), "(['NaT', '2000-1-2', 'NaT', '2000-1-1', 'NaT', '2000-1-1'])\n", (2378, 2437), True, 'import pandas as pd\n'), ((2633, 2720), 'pandas.to_datetime', 'pd.to_datetime', (["['NaT', '2000-1-2', '2000-1-2', '2000-1-1', '2000-1-1', '2000-1-1']"], {}), "(['NaT', '2000-1-2', '2000-1-2', '2000-1-1', '2000-1-1',\n '2000-1-1'])\n", (2647, 2720), True, 'import pandas as pd\n'), ((3007, 3080), 'pandas.to_datetime', 'pd.to_datetime', (["['NaT', '2000-1-2', 'NaT', '2000-1-1', 'NaT', '2000-1-3']"], {}), "(['NaT', '2000-1-2', 'NaT', '2000-1-1', 'NaT', '2000-1-3'])\n", (3021, 3080), True, 'import pandas as pd\n'), ((3186, 3259), 'pandas.to_datetime', 'pd.to_datetime', (["['NaT', '2000-1-2', 'NaT', '2000-1-2', 'NaT', '2000-1-3']"], {}), "(['NaT', '2000-1-2', 'NaT', '2000-1-2', 'NaT', '2000-1-3'])\n", (3200, 3259), True, 'import pandas as pd\n'), ((3455, 3542), 'pandas.to_datetime', 'pd.to_datetime', (["['NaT', '2000-1-2', '2000-1-2', '2000-1-2', '2000-1-2', '2000-1-3']"], {}), "(['NaT', '2000-1-2', '2000-1-2', '2000-1-2', '2000-1-2',\n '2000-1-3'])\n", (3469, 3542), True, 'import pandas as pd\n')] |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import os
import sys
import unittest
import pytest
from numpy.testing import assert_array_equal
import numpy as np
from pandas.util.testing import assert_frame_equal
import pandas as pd
import pyarrow as pa
from pyarrow.compat import guid
from pyarrow.feather import (read_feather, write_feather,
FeatherReader)
from pyarrow.lib import FeatherWriter
def random_path():
return 'feather_{}'.format(guid())
class TestFeatherReader(unittest.TestCase):
def setUp(self):
self.test_files = []
def tearDown(self):
for path in self.test_files:
try:
os.remove(path)
except os.error:
pass
def test_file_not_exist(self):
with self.assertRaises(pa.ArrowIOError):
FeatherReader('test_invalid_file')
def _get_null_counts(self, path, columns=None):
reader = FeatherReader(path)
counts = []
for i in range(reader.num_columns):
col = reader.get_column(i)
if columns is None or col.name in columns:
counts.append(col.null_count)
return counts
def _check_pandas_roundtrip(self, df, expected=None, path=None,
columns=None, null_counts=None,
nthreads=1):
if path is None:
path = random_path()
self.test_files.append(path)
write_feather(df, path)
if not os.path.exists(path):
raise Exception('file not written')
result = read_feather(path, columns, nthreads=nthreads)
if expected is None:
expected = df
assert_frame_equal(result, expected)
if null_counts is None:
null_counts = np.zeros(len(expected.columns))
np.testing.assert_array_equal(self._get_null_counts(path, columns),
null_counts)
def _assert_error_on_write(self, df, exc, path=None):
# check that we are raising the exception
# on writing
if path is None:
path = random_path()
self.test_files.append(path)
def f():
write_feather(df, path)
self.assertRaises(exc, f)
def test_num_rows_attr(self):
df = pd.DataFrame({'foo': [1, 2, 3, 4, 5]})
path = random_path()
self.test_files.append(path)
write_feather(df, path)
reader = FeatherReader(path)
assert reader.num_rows == len(df)
df = pd.DataFrame({})
path = random_path()
self.test_files.append(path)
write_feather(df, path)
reader = FeatherReader(path)
assert reader.num_rows == 0
def test_float_no_nulls(self):
data = {}
numpy_dtypes = ['f4', 'f8']
num_values = 100
for dtype in numpy_dtypes:
values = np.random.randn(num_values)
data[dtype] = values.astype(dtype)
df = pd.DataFrame(data)
self._check_pandas_roundtrip(df)
def test_float_nulls(self):
num_values = 100
path = random_path()
self.test_files.append(path)
writer = FeatherWriter()
writer.open(path)
null_mask = np.random.randint(0, 10, size=num_values) < 3
dtypes = ['f4', 'f8']
expected_cols = []
null_counts = []
for name in dtypes:
values = np.random.randn(num_values).astype(name)
writer.write_array(name, values, null_mask)
values[null_mask] = np.nan
expected_cols.append(values)
null_counts.append(null_mask.sum())
writer.close()
ex_frame = pd.DataFrame(dict(zip(dtypes, expected_cols)),
columns=dtypes)
result = read_feather(path)
assert_frame_equal(result, ex_frame)
assert_array_equal(self._get_null_counts(path), null_counts)
def test_integer_no_nulls(self):
data = {}
numpy_dtypes = ['i1', 'i2', 'i4', 'i8',
'u1', 'u2', 'u4', 'u8']
num_values = 100
for dtype in numpy_dtypes:
values = np.random.randint(0, 100, size=num_values)
data[dtype] = values.astype(dtype)
df = pd.DataFrame(data)
self._check_pandas_roundtrip(df)
def test_platform_numpy_integers(self):
data = {}
numpy_dtypes = ['longlong']
num_values = 100
for dtype in numpy_dtypes:
values = np.random.randint(0, 100, size=num_values)
data[dtype] = values.astype(dtype)
df = pd.DataFrame(data)
self._check_pandas_roundtrip(df)
def test_integer_with_nulls(self):
# pandas requires upcast to float dtype
path = random_path()
self.test_files.append(path)
int_dtypes = ['i1', 'i2', 'i4', 'i8', 'u1', 'u2', 'u4', 'u8']
num_values = 100
writer = FeatherWriter()
writer.open(path)
null_mask = np.random.randint(0, 10, size=num_values) < 3
expected_cols = []
for name in int_dtypes:
values = np.random.randint(0, 100, size=num_values)
writer.write_array(name, values, null_mask)
expected = values.astype('f8')
expected[null_mask] = np.nan
expected_cols.append(expected)
ex_frame = pd.DataFrame(dict(zip(int_dtypes, expected_cols)),
columns=int_dtypes)
writer.close()
result = read_feather(path)
assert_frame_equal(result, ex_frame)
def test_boolean_no_nulls(self):
num_values = 100
np.random.seed(0)
df = pd.DataFrame({'bools': np.random.randn(num_values) > 0})
self._check_pandas_roundtrip(df)
def test_boolean_nulls(self):
# pandas requires upcast to object dtype
path = random_path()
self.test_files.append(path)
num_values = 100
np.random.seed(0)
writer = FeatherWriter()
writer.open(path)
mask = np.random.randint(0, 10, size=num_values) < 3
values = np.random.randint(0, 10, size=num_values) < 5
writer.write_array('bools', values, mask)
expected = values.astype(object)
expected[mask] = None
writer.close()
ex_frame = pd.DataFrame({'bools': expected})
result = read_feather(path)
assert_frame_equal(result, ex_frame)
def test_buffer_bounds_error(self):
# ARROW-1676
path = random_path()
self.test_files.append(path)
for i in range(16, 256):
values = pa.array([None] + list(range(i)), type=pa.float64())
writer = FeatherWriter()
writer.open(path)
writer.write_array('arr', values)
writer.close()
result = read_feather(path)
expected = pd.DataFrame({'arr': values.to_pandas()})
assert_frame_equal(result, expected)
self._check_pandas_roundtrip(expected, null_counts=[1])
def test_boolean_object_nulls(self):
repeats = 100
arr = np.array([False, None, True] * repeats, dtype=object)
df = pd.DataFrame({'bools': arr})
self._check_pandas_roundtrip(df, null_counts=[1 * repeats])
def test_delete_partial_file_on_error(self):
if sys.platform == 'win32':
pytest.skip('Windows hangs on to file handle for some reason')
# strings will fail
df = pd.DataFrame(
{
'numbers': range(5),
'strings': [b'foo', None, u'bar', 'qux', np.nan]},
columns=['numbers', 'strings'])
path = random_path()
try:
write_feather(df, path)
except:
pass
assert not os.path.exists(path)
def test_strings(self):
repeats = 1000
# we hvae mixed bytes, unicode, strings
values = [b'foo', None, u'bar', 'qux', np.nan]
df = pd.DataFrame({'strings': values * repeats})
self._assert_error_on_write(df, ValueError)
# embedded nulls are ok
values = ['foo', None, 'bar', 'qux', None]
df = pd.DataFrame({'strings': values * repeats})
expected = pd.DataFrame({'strings': values * repeats})
self._check_pandas_roundtrip(df, expected, null_counts=[2 * repeats])
values = ['foo', None, 'bar', 'qux', np.nan]
df = pd.DataFrame({'strings': values * repeats})
expected = pd.DataFrame({'strings': values * repeats})
self._check_pandas_roundtrip(df, expected, null_counts=[2 * repeats])
def test_empty_strings(self):
df = pd.DataFrame({'strings': [''] * 10})
self._check_pandas_roundtrip(df)
def test_all_none(self):
df = pd.DataFrame({'all_none': [None] * 10})
self._check_pandas_roundtrip(df, null_counts=[10])
def test_all_null_category(self):
# ARROW-1188
df = pd.DataFrame({"A": (1, 2, 3), "B": (None, None, None)})
df = df.assign(B=df.B.astype("category"))
self._check_pandas_roundtrip(df, null_counts=[0, 3])
def test_multithreaded_read(self):
data = {'c{0}'.format(i): [''] * 10
for i in range(100)}
df = pd.DataFrame(data)
self._check_pandas_roundtrip(df, nthreads=4)
def test_nan_as_null(self):
# Create a nan that is not numpy.nan
values = np.array(['foo', np.nan, np.nan * 2, 'bar'] * 10)
df = pd.DataFrame({'strings': values})
self._check_pandas_roundtrip(df)
def test_category(self):
repeats = 1000
values = ['foo', None, u'bar', 'qux', np.nan]
df = pd.DataFrame({'strings': values * repeats})
df['strings'] = df['strings'].astype('category')
values = ['foo', None, 'bar', 'qux', None]
expected = pd.DataFrame({'strings': pd.Categorical(values * repeats)})
self._check_pandas_roundtrip(df, expected,
null_counts=[2 * repeats])
def test_timestamp(self):
df = pd.DataFrame({'naive': pd.date_range('2016-03-28', periods=10)})
df['with_tz'] = (df.naive.dt.tz_localize('utc')
.dt.tz_convert('America/Los_Angeles'))
self._check_pandas_roundtrip(df)
def test_timestamp_with_nulls(self):
df = pd.DataFrame({'test': [pd.datetime(2016, 1, 1),
None,
pd.datetime(2016, 1, 3)]})
df['with_tz'] = df.test.dt.tz_localize('utc')
self._check_pandas_roundtrip(df, null_counts=[1, 1])
@pytest.mark.xfail(reason="not supported ATM",
raises=NotImplementedError)
def test_timedelta_with_nulls(self):
df = pd.DataFrame({'test': [pd.Timedelta('1 day'),
None,
pd.Timedelta('3 day')]})
self._check_pandas_roundtrip(df, null_counts=[1, 1])
def test_out_of_float64_timestamp_with_nulls(self):
df = pd.DataFrame(
{'test': pd.DatetimeIndex([1451606400000000001,
None, 14516064000030405])})
df['with_tz'] = df.test.dt.tz_localize('utc')
self._check_pandas_roundtrip(df, null_counts=[1, 1])
def test_non_string_columns(self):
df = pd.DataFrame({0: [1, 2, 3, 4],
1: [True, False, True, False]})
expected = df.rename(columns=str)
self._check_pandas_roundtrip(df, expected)
@pytest.mark.skipif(not os.path.supports_unicode_filenames,
reason='unicode filenames not supported')
def test_unicode_filename(self):
# GH #209
name = (b'Besa_Kavaj\xc3\xab.feather').decode('utf-8')
df = pd.DataFrame({'foo': [1, 2, 3, 4]})
self._check_pandas_roundtrip(df, path=name)
def test_read_columns(self):
data = {'foo': [1, 2, 3, 4],
'boo': [5, 6, 7, 8],
'woo': [1, 3, 5, 7]}
columns = list(data.keys())[1:3]
df = pd.DataFrame(data)
expected = pd.DataFrame({c: data[c] for c in columns})
self._check_pandas_roundtrip(df, expected, columns=columns)
def test_overwritten_file(self):
path = random_path()
self.test_files.append(path)
num_values = 100
np.random.seed(0)
values = np.random.randint(0, 10, size=num_values)
write_feather(pd.DataFrame({'ints': values}), path)
df = pd.DataFrame({'ints': values[0: num_values//2]})
self._check_pandas_roundtrip(df, path=path)
def test_filelike_objects(self):
from io import BytesIO
buf = BytesIO()
# the copy makes it non-strided
df = pd.DataFrame(np.arange(12).reshape(4, 3),
columns=['a', 'b', 'c']).copy()
write_feather(df, buf)
buf.seek(0)
result = read_feather(buf)
assert_frame_equal(result, df)
def test_sparse_dataframe(self):
# GH #221
data = {'A': [0, 1, 2],
'B': [1, 0, 1]}
df = pd.DataFrame(data).to_sparse(fill_value=1)
expected = df.to_dense()
self._check_pandas_roundtrip(df, expected)
def test_duplicate_columns(self):
# https://github.com/wesm/feather/issues/53
# not currently able to handle duplicate columns
df = pd.DataFrame(np.arange(12).reshape(4, 3),
columns=list('aaa')).copy()
self._assert_error_on_write(df, ValueError)
def test_unsupported(self):
# https://github.com/wesm/feather/issues/240
# serializing actual python objects
# period
df = pd.DataFrame({'a': pd.period_range('2013', freq='M', periods=3)})
self._assert_error_on_write(df, ValueError)
# non-strings
df = pd.DataFrame({'a': ['a', 1, 2.0]})
self._assert_error_on_write(df, ValueError)
| [
"io.BytesIO",
"numpy.array",
"pyarrow.feather.write_feather",
"pandas.date_range",
"pandas.util.testing.assert_frame_equal",
"os.remove",
"os.path.exists",
"numpy.arange",
"pytest.mark.xfail",
"pyarrow.lib.FeatherWriter",
"pandas.Categorical",
"numpy.random.seed",
"pytest.mark.skipif",
"pa... | [((11435, 11508), 'pytest.mark.xfail', 'pytest.mark.xfail', ([], {'reason': '"""not supported ATM"""', 'raises': 'NotImplementedError'}), "(reason='not supported ATM', raises=NotImplementedError)\n", (11452, 11508), False, 'import pytest\n'), ((12366, 12471), 'pytest.mark.skipif', 'pytest.mark.skipif', (['(not os.path.supports_unicode_filenames)'], {'reason': '"""unicode filenames not supported"""'}), "(not os.path.supports_unicode_filenames, reason=\n 'unicode filenames not supported')\n", (12384, 12471), False, 'import pytest\n'), ((1220, 1226), 'pyarrow.compat.guid', 'guid', ([], {}), '()\n', (1224, 1226), False, 'from pyarrow.compat import guid\n'), ((1688, 1707), 'pyarrow.feather.FeatherReader', 'FeatherReader', (['path'], {}), '(path)\n', (1701, 1707), False, 'from pyarrow.feather import read_feather, write_feather, FeatherReader\n'), ((2217, 2240), 'pyarrow.feather.write_feather', 'write_feather', (['df', 'path'], {}), '(df, path)\n', (2230, 2240), False, 'from pyarrow.feather import read_feather, write_feather, FeatherReader\n'), ((2344, 2390), 'pyarrow.feather.read_feather', 'read_feather', (['path', 'columns'], {'nthreads': 'nthreads'}), '(path, columns, nthreads=nthreads)\n', (2356, 2390), False, 'from pyarrow.feather import read_feather, write_feather, FeatherReader\n'), ((2455, 2491), 'pandas.util.testing.assert_frame_equal', 'assert_frame_equal', (['result', 'expected'], {}), '(result, expected)\n', (2473, 2491), False, 'from pandas.util.testing import assert_frame_equal\n'), ((3075, 3113), 'pandas.DataFrame', 'pd.DataFrame', (["{'foo': [1, 2, 3, 4, 5]}"], {}), "({'foo': [1, 2, 3, 4, 5]})\n", (3087, 3113), True, 'import pandas as pd\n'), ((3188, 3211), 'pyarrow.feather.write_feather', 'write_feather', (['df', 'path'], {}), '(df, path)\n', (3201, 3211), False, 'from pyarrow.feather import read_feather, write_feather, FeatherReader\n'), ((3230, 3249), 'pyarrow.feather.FeatherReader', 'FeatherReader', (['path'], {}), '(path)\n', (3243, 3249), False, 'from pyarrow.feather import read_feather, write_feather, FeatherReader\n'), ((3306, 3322), 'pandas.DataFrame', 'pd.DataFrame', (['{}'], {}), '({})\n', (3318, 3322), True, 'import pandas as pd\n'), ((3397, 3420), 'pyarrow.feather.write_feather', 'write_feather', (['df', 'path'], {}), '(df, path)\n', (3410, 3420), False, 'from pyarrow.feather import read_feather, write_feather, FeatherReader\n'), ((3439, 3458), 'pyarrow.feather.FeatherReader', 'FeatherReader', (['path'], {}), '(path)\n', (3452, 3458), False, 'from pyarrow.feather import read_feather, write_feather, FeatherReader\n'), ((3756, 3774), 'pandas.DataFrame', 'pd.DataFrame', (['data'], {}), '(data)\n', (3768, 3774), True, 'import pandas as pd\n'), ((3958, 3973), 'pyarrow.lib.FeatherWriter', 'FeatherWriter', ([], {}), '()\n', (3971, 3973), False, 'from pyarrow.lib import FeatherWriter\n'), ((4582, 4600), 'pyarrow.feather.read_feather', 'read_feather', (['path'], {}), '(path)\n', (4594, 4600), False, 'from pyarrow.feather import read_feather, write_feather, FeatherReader\n'), ((4609, 4645), 'pandas.util.testing.assert_frame_equal', 'assert_frame_equal', (['result', 'ex_frame'], {}), '(result, ex_frame)\n', (4627, 4645), False, 'from pandas.util.testing import assert_frame_equal\n'), ((5054, 5072), 'pandas.DataFrame', 'pd.DataFrame', (['data'], {}), '(data)\n', (5066, 5072), True, 'import pandas as pd\n'), ((5400, 5418), 'pandas.DataFrame', 'pd.DataFrame', (['data'], {}), '(data)\n', (5412, 5418), True, 'import pandas as pd\n'), ((5728, 5743), 'pyarrow.lib.FeatherWriter', 'FeatherWriter', ([], {}), '()\n', (5741, 5743), False, 'from pyarrow.lib import FeatherWriter\n'), ((6310, 6328), 'pyarrow.feather.read_feather', 'read_feather', (['path'], {}), '(path)\n', (6322, 6328), False, 'from pyarrow.feather import read_feather, write_feather, FeatherReader\n'), ((6337, 6373), 'pandas.util.testing.assert_frame_equal', 'assert_frame_equal', (['result', 'ex_frame'], {}), '(result, ex_frame)\n', (6355, 6373), False, 'from pandas.util.testing import assert_frame_equal\n'), ((6446, 6463), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (6460, 6463), True, 'import numpy as np\n'), ((6760, 6777), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (6774, 6777), True, 'import numpy as np\n'), ((6796, 6811), 'pyarrow.lib.FeatherWriter', 'FeatherWriter', ([], {}), '()\n', (6809, 6811), False, 'from pyarrow.lib import FeatherWriter\n'), ((7129, 7162), 'pandas.DataFrame', 'pd.DataFrame', (["{'bools': expected}"], {}), "({'bools': expected})\n", (7141, 7162), True, 'import pandas as pd\n'), ((7181, 7199), 'pyarrow.feather.read_feather', 'read_feather', (['path'], {}), '(path)\n', (7193, 7199), False, 'from pyarrow.feather import read_feather, write_feather, FeatherReader\n'), ((7208, 7244), 'pandas.util.testing.assert_frame_equal', 'assert_frame_equal', (['result', 'ex_frame'], {}), '(result, ex_frame)\n', (7226, 7244), False, 'from pandas.util.testing import assert_frame_equal\n'), ((7925, 7978), 'numpy.array', 'np.array', (['([False, None, True] * repeats)'], {'dtype': 'object'}), '([False, None, True] * repeats, dtype=object)\n', (7933, 7978), True, 'import numpy as np\n'), ((7992, 8020), 'pandas.DataFrame', 'pd.DataFrame', (["{'bools': arr}"], {}), "({'bools': arr})\n", (8004, 8020), True, 'import pandas as pd\n'), ((8790, 8833), 'pandas.DataFrame', 'pd.DataFrame', (["{'strings': values * repeats}"], {}), "({'strings': values * repeats})\n", (8802, 8833), True, 'import pandas as pd\n'), ((8983, 9026), 'pandas.DataFrame', 'pd.DataFrame', (["{'strings': values * repeats}"], {}), "({'strings': values * repeats})\n", (8995, 9026), True, 'import pandas as pd\n'), ((9046, 9089), 'pandas.DataFrame', 'pd.DataFrame', (["{'strings': values * repeats}"], {}), "({'strings': values * repeats})\n", (9058, 9089), True, 'import pandas as pd\n'), ((9235, 9278), 'pandas.DataFrame', 'pd.DataFrame', (["{'strings': values * repeats}"], {}), "({'strings': values * repeats})\n", (9247, 9278), True, 'import pandas as pd\n'), ((9298, 9341), 'pandas.DataFrame', 'pd.DataFrame', (["{'strings': values * repeats}"], {}), "({'strings': values * repeats})\n", (9310, 9341), True, 'import pandas as pd\n'), ((9468, 9504), 'pandas.DataFrame', 'pd.DataFrame', (["{'strings': [''] * 10}"], {}), "({'strings': [''] * 10})\n", (9480, 9504), True, 'import pandas as pd\n'), ((9589, 9628), 'pandas.DataFrame', 'pd.DataFrame', (["{'all_none': [None] * 10}"], {}), "({'all_none': [None] * 10})\n", (9601, 9628), True, 'import pandas as pd\n'), ((9761, 9816), 'pandas.DataFrame', 'pd.DataFrame', (["{'A': (1, 2, 3), 'B': (None, None, None)}"], {}), "({'A': (1, 2, 3), 'B': (None, None, None)})\n", (9773, 9816), True, 'import pandas as pd\n'), ((10062, 10080), 'pandas.DataFrame', 'pd.DataFrame', (['data'], {}), '(data)\n', (10074, 10080), True, 'import pandas as pd\n'), ((10229, 10278), 'numpy.array', 'np.array', (["(['foo', np.nan, np.nan * 2, 'bar'] * 10)"], {}), "(['foo', np.nan, np.nan * 2, 'bar'] * 10)\n", (10237, 10278), True, 'import numpy as np\n'), ((10292, 10325), 'pandas.DataFrame', 'pd.DataFrame', (["{'strings': values}"], {}), "({'strings': values})\n", (10304, 10325), True, 'import pandas as pd\n'), ((10487, 10530), 'pandas.DataFrame', 'pd.DataFrame', (["{'strings': values * repeats}"], {}), "({'strings': values * repeats})\n", (10499, 10530), True, 'import pandas as pd\n'), ((12176, 12242), 'pandas.DataFrame', 'pd.DataFrame', (['{(0): [1, 2, 3, 4], (1): [True, False, True, False]}'], {}), '({(0): [1, 2, 3, 4], (1): [True, False, True, False]})\n', (12188, 12242), True, 'import pandas as pd\n'), ((12622, 12657), 'pandas.DataFrame', 'pd.DataFrame', (["{'foo': [1, 2, 3, 4]}"], {}), "({'foo': [1, 2, 3, 4]})\n", (12634, 12657), True, 'import pandas as pd\n'), ((12909, 12927), 'pandas.DataFrame', 'pd.DataFrame', (['data'], {}), '(data)\n', (12921, 12927), True, 'import pandas as pd\n'), ((12947, 12990), 'pandas.DataFrame', 'pd.DataFrame', (['{c: data[c] for c in columns}'], {}), '({c: data[c] for c in columns})\n', (12959, 12990), True, 'import pandas as pd\n'), ((13197, 13214), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (13211, 13214), True, 'import numpy as np\n'), ((13233, 13274), 'numpy.random.randint', 'np.random.randint', (['(0)', '(10)'], {'size': 'num_values'}), '(0, 10, size=num_values)\n', (13250, 13274), True, 'import numpy as np\n'), ((13349, 13398), 'pandas.DataFrame', 'pd.DataFrame', (["{'ints': values[0:num_values // 2]}"], {}), "({'ints': values[0:num_values // 2]})\n", (13361, 13398), True, 'import pandas as pd\n'), ((13534, 13543), 'io.BytesIO', 'BytesIO', ([], {}), '()\n', (13541, 13543), False, 'from io import BytesIO\n'), ((13706, 13728), 'pyarrow.feather.write_feather', 'write_feather', (['df', 'buf'], {}), '(df, buf)\n', (13719, 13728), False, 'from pyarrow.feather import read_feather, write_feather, FeatherReader\n'), ((13768, 13785), 'pyarrow.feather.read_feather', 'read_feather', (['buf'], {}), '(buf)\n', (13780, 13785), False, 'from pyarrow.feather import read_feather, write_feather, FeatherReader\n'), ((13794, 13824), 'pandas.util.testing.assert_frame_equal', 'assert_frame_equal', (['result', 'df'], {}), '(result, df)\n', (13812, 13824), False, 'from pandas.util.testing import assert_frame_equal\n'), ((14710, 14744), 'pandas.DataFrame', 'pd.DataFrame', (["{'a': ['a', 1, 2.0]}"], {}), "({'a': ['a', 1, 2.0]})\n", (14722, 14744), True, 'import pandas as pd\n'), ((1583, 1617), 'pyarrow.feather.FeatherReader', 'FeatherReader', (['"""test_invalid_file"""'], {}), "('test_invalid_file')\n", (1596, 1617), False, 'from pyarrow.feather import read_feather, write_feather, FeatherReader\n'), ((2256, 2276), 'os.path.exists', 'os.path.exists', (['path'], {}), '(path)\n', (2270, 2276), False, 'import os\n'), ((2968, 2991), 'pyarrow.feather.write_feather', 'write_feather', (['df', 'path'], {}), '(df, path)\n', (2981, 2991), False, 'from pyarrow.feather import read_feather, write_feather, FeatherReader\n'), ((3667, 3694), 'numpy.random.randn', 'np.random.randn', (['num_values'], {}), '(num_values)\n', (3682, 3694), True, 'import numpy as np\n'), ((4021, 4062), 'numpy.random.randint', 'np.random.randint', (['(0)', '(10)'], {'size': 'num_values'}), '(0, 10, size=num_values)\n', (4038, 4062), True, 'import numpy as np\n'), ((4950, 4992), 'numpy.random.randint', 'np.random.randint', (['(0)', '(100)'], {'size': 'num_values'}), '(0, 100, size=num_values)\n', (4967, 4992), True, 'import numpy as np\n'), ((5296, 5338), 'numpy.random.randint', 'np.random.randint', (['(0)', '(100)'], {'size': 'num_values'}), '(0, 100, size=num_values)\n', (5313, 5338), True, 'import numpy as np\n'), ((5791, 5832), 'numpy.random.randint', 'np.random.randint', (['(0)', '(10)'], {'size': 'num_values'}), '(0, 10, size=num_values)\n', (5808, 5832), True, 'import numpy as np\n'), ((5917, 5959), 'numpy.random.randint', 'np.random.randint', (['(0)', '(100)'], {'size': 'num_values'}), '(0, 100, size=num_values)\n', (5934, 5959), True, 'import numpy as np\n'), ((6854, 6895), 'numpy.random.randint', 'np.random.randint', (['(0)', '(10)'], {'size': 'num_values'}), '(0, 10, size=num_values)\n', (6871, 6895), True, 'import numpy as np\n'), ((6917, 6958), 'numpy.random.randint', 'np.random.randint', (['(0)', '(10)'], {'size': 'num_values'}), '(0, 10, size=num_values)\n', (6934, 6958), True, 'import numpy as np\n'), ((7503, 7518), 'pyarrow.lib.FeatherWriter', 'FeatherWriter', ([], {}), '()\n', (7516, 7518), False, 'from pyarrow.lib import FeatherWriter\n'), ((7645, 7663), 'pyarrow.feather.read_feather', 'read_feather', (['path'], {}), '(path)\n', (7657, 7663), False, 'from pyarrow.feather import read_feather, write_feather, FeatherReader\n'), ((7741, 7777), 'pandas.util.testing.assert_frame_equal', 'assert_frame_equal', (['result', 'expected'], {}), '(result, expected)\n', (7759, 7777), False, 'from pandas.util.testing import assert_frame_equal\n'), ((8187, 8249), 'pytest.skip', 'pytest.skip', (['"""Windows hangs on to file handle for some reason"""'], {}), "('Windows hangs on to file handle for some reason')\n", (8198, 8249), False, 'import pytest\n'), ((8523, 8546), 'pyarrow.feather.write_feather', 'write_feather', (['df', 'path'], {}), '(df, path)\n', (8536, 8546), False, 'from pyarrow.feather import read_feather, write_feather, FeatherReader\n'), ((8600, 8620), 'os.path.exists', 'os.path.exists', (['path'], {}), '(path)\n', (8614, 8620), False, 'import os\n'), ((13297, 13327), 'pandas.DataFrame', 'pd.DataFrame', (["{'ints': values}"], {}), "({'ints': values})\n", (13309, 13327), True, 'import pandas as pd\n'), ((1420, 1435), 'os.remove', 'os.remove', (['path'], {}), '(path)\n', (1429, 1435), False, 'import os\n'), ((10684, 10716), 'pandas.Categorical', 'pd.Categorical', (['(values * repeats)'], {}), '(values * repeats)\n', (10698, 10716), True, 'import pandas as pd\n'), ((10901, 10940), 'pandas.date_range', 'pd.date_range', (['"""2016-03-28"""'], {'periods': '(10)'}), "('2016-03-28', periods=10)\n", (10914, 10940), True, 'import pandas as pd\n'), ((11902, 11966), 'pandas.DatetimeIndex', 'pd.DatetimeIndex', (['[1451606400000000001, None, 14516064000030405]'], {}), '([1451606400000000001, None, 14516064000030405])\n', (11918, 11966), True, 'import pandas as pd\n'), ((13958, 13976), 'pandas.DataFrame', 'pd.DataFrame', (['data'], {}), '(data)\n', (13970, 13976), True, 'import pandas as pd\n'), ((14575, 14619), 'pandas.period_range', 'pd.period_range', (['"""2013"""'], {'freq': '"""M"""', 'periods': '(3)'}), "('2013', freq='M', periods=3)\n", (14590, 14619), True, 'import pandas as pd\n'), ((4198, 4225), 'numpy.random.randn', 'np.random.randn', (['num_values'], {}), '(num_values)\n', (4213, 4225), True, 'import numpy as np\n'), ((6501, 6528), 'numpy.random.randn', 'np.random.randn', (['num_values'], {}), '(num_values)\n', (6516, 6528), True, 'import numpy as np\n'), ((7467, 7479), 'pyarrow.float64', 'pa.float64', ([], {}), '()\n', (7477, 7479), True, 'import pyarrow as pa\n'), ((11183, 11206), 'pandas.datetime', 'pd.datetime', (['(2016)', '(1)', '(1)'], {}), '(2016, 1, 1)\n', (11194, 11206), True, 'import pandas as pd\n'), ((11286, 11309), 'pandas.datetime', 'pd.datetime', (['(2016)', '(1)', '(3)'], {}), '(2016, 1, 3)\n', (11297, 11309), True, 'import pandas as pd\n'), ((11609, 11630), 'pandas.Timedelta', 'pd.Timedelta', (['"""1 day"""'], {}), "('1 day')\n", (11621, 11630), True, 'import pandas as pd\n'), ((11710, 11731), 'pandas.Timedelta', 'pd.Timedelta', (['"""3 day"""'], {}), "('3 day')\n", (11722, 11731), True, 'import pandas as pd\n'), ((13611, 13624), 'numpy.arange', 'np.arange', (['(12)'], {}), '(12)\n', (13620, 13624), True, 'import numpy as np\n'), ((14260, 14273), 'numpy.arange', 'np.arange', (['(12)'], {}), '(12)\n', (14269, 14273), True, 'import numpy as np\n')] |
import sys,os
import math
import random
#import mpmath
import operator
import csv
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.pylab as pyl
import itertools
import scipy as sp
from scipy import stats
from scipy import optimize
from scipy.integrate import quad
#import scikits.statsmodels as sm
def segno(x):
"""
Input: x, a number
Return: 1.0 if x>0,
-1.0 if x<0,
0.0 if x==0
"""
if x > 0.0: return 1.0
elif x < 0.0: return -1.0
elif x == 0.0: return 0.0
def standard_dev(list):
ll = len(list)
m = 1.0 * sum(list)/ll
return ( sum([(elem-m)**2.0 for elem in list]) / ll )**0.5
def list_check(lista):
"""
If a list has only one element, return that element. Otherwise return the whole list.
"""
try:
e2 = lista[1]
return lista
except IndexError:
return lista[0]
#______________________________________#
# #
# Probability distributions #
#______________________________________#
# #
def pdf(binsize, input, out='no', normalize=True, include_zeros=False, vmin='NA', vmax='NA',start_from='NA', closing_bin=False):
"""
Return the probability density function of "input"
using linear bins of size "binsize"
Input format: one column of numbers
Example:
---------
a, m = 0.5, 1.
data = np.random.pareto(a, 1000) + m
xy = pdf(10.0, data)
"""
# Detect input type:
if input == sys.stdin:
# the data come form standard input
d = [ list_check(map(float,l.split())) for l in sys.stdin ]
# d = [ float(l) for l in sys.stdin if l.strip() ]
elif isinstance(input, str):
# the data come from a file
d = [ list_check(map(float,l.split())) for l in open(input,'r') ]
# d = [ float(w) for w in open(input,'r') if w.split()]
else:
# the data are in a list
try:
iterator = iter(input)
d = list(input)
except TypeError:
print("The input is not iterable.")
bin = 1.0*binsize
d.sort()
lend = len(d)
hist = []
if out != 'no' and out != 'stdout': f = open(out,'wb')
j = 0
if not isinstance(start_from, str):
i = int(start_from / bin)+ 1.0 * segno(start_from)
else:
i = int(d[j] / bin) + 1.0 *segno(d[j])
while True:
cont = 0
average = 0.0
if i>=0: ii = i-1
else: ii = i
# To include the lower end in the previous bin, substitute "<" with "<="
while d[j] < bin*(ii+1):
cont += 1.0
average += 1.0
j += 1
if j == lend: break
if cont > 0 or include_zeros==True:
if normalize == True and i != 0:
hist += [[ bin*(ii)+bin/2.0 , average/(lend*bin) ]]
elif i != 0:
hist += [[ bin*(ii)+bin/2.0 , average/bin ]]
if j == lend: break
i += 1
if closing_bin:
# Add the "closing" bin
hist += [[ hist[-1][0]+bin , 0.0 ]]
if out == 'stdout':
for l in hist:
print("%s %s" % (l[0],l[1]))
elif out != 'no':
for l in hist:
f.write("%s %s\n" % (l[0],l[1]))
f.close()
if out == 'no': return hist
def lbpdf(binsize, input, out='no'):
"""
Return the probability density function of "input"
using logarithmic bins of size "binsize"
Input format: one column of numbers
Example:
---------
a, m = 0.5, 1.
data = np.random.pareto(a, 1000) + m
xy = lbpdf(1.5, data)
"""
# Detect input type:
if input == sys.stdin:
# the data come form standard input
d = [ list_check(map(float,l.split())) for l in sys.stdin ]
# d = [ float(l) for l in sys.stdin if l.strip() ]
elif isinstance(input, str):
# the data come from a file
d = [ list_check(map(float,l.split())) for l in open(input,'r') ]
# d = [ float(w) for w in open(input,'r') if w.split()]
else:
# the data are in a list
try:
iterator = iter(input)
d = list(input)
except TypeError:
print("The input is not iterable.")
bin = 1.0*binsize
d.sort()
# The following removes elements too close to zero
while d[0] < 1e-12:
del(d[0])
lend = len(d)
tot = 0
hist = []
j = 0
i = 1.0
previous = min(d)
while True:
cont = 0
average = 0.0
next = previous * bin
# To include the lower end in the previous bin, substitute "<" with "<="
while d[j] < next:
cont += 1.0
average += 1.0
j += 1
if j == lend: break
if cont > 0:
hist += [[previous+(next-previous)/2.0 , average/(next-previous)]]
tot += average
if j == lend: break
i += 1
previous = next
if out != 'no' and out != 'stdout': f = open(out,'wb')
if out == 'stdout':
for x,y in hist:
print("%s %s" % (x,y/tot))
elif out != 'no':
f = open(out,'wb')
for x,y in hist:
f.write("%s %s\n" % (x,y/tot))
f.close()
if out == 'no': return [[x,y/tot] for x,y in hist]
#______________________________________#
# #
# Least Squares Fit #
#______________________________________#
# #
class Parameter:
def __init__(self, value):
self.value = value
def set(self, value):
self.value = value
def __call__(self):
return self.value
def LSfit(function, parameters, y, x):
"""
*** ATTENTION! ***
*** _x_ and _y_ MUST be NUMPY arrays !!! ***
*** and use NUMPY FUNCTIONS, e.g. np.exp() and not math.exp() ***
_function_ -> Used to calculate the sum of the squares:
min sum( (y - function(x, parameters))**2 )
{params}
_parameters_ -> List of elements of the Class "Parameter"
_y_ -> List of observations: [ y0, y1, ... ]
_x_ -> List of variables: [ [x0,z0], [x1,z1], ... ]
Then _function_ must be function of xi=x[0] and zi=x[1]:
def f(x): return x[0] * x[1] / mu()
# Gaussian
np.exp( -(x-mu())**2.0/sigma()**2.0/2.0)/(2.0*sigma()**2.0*np.pi)**0.5
# Lognormal
np.exp( -(np.log(x)-mu())**2.0/sigma()**2.0/2.0)/(2.0*sigma()**2.0*np.pi)**0.5/x
Example:
x=[np.random.normal() for i in range(1000)]
variables,data = map(np.array,zip(*pdf(0.4,x)))
# giving INITIAL _PARAMETERS_:
mu = Parameter(7)
sigma = Parameter(3)
# define your _FUNCTION_:
def function(x): return np.exp( -(x-mu())**2.0/sigma()**2.0/2.0)/(2.0*sigma()**2.0*np.pi)**0.5
######################################################################################
USA QUESTE FORMULE
#Gaussian formula
#np.exp( -(x-mu())**2.0/sigma()**2.0/2.0)/(2.0*np.pi)**0.5/sigma()
# Lognormal formula
#np.exp( -(np.log(x)-mu())**2.0/sigma()**2.0/2.0)/(2.0*np.pi)**0.5/x/sigma()
######################################################################################
np.exp( -(x-mu())**2.0/sigma()**2.0/2.0)/(2.0*np.pi)**0.5/sigma()
# fit! (given that data is an array with the data to fit)
popt,cov,infodict,mesg,ier,pcov,chi2 = LSfit(function, [mu, sigma], data, variables)
"""
x = np.array(x)
y = np.array(y)
def f(params):
i = 0
for p in parameters:
p.set(params[i])
i += 1
return y - function(x)
p = [param() for param in parameters]
popt,cov,infodict,mesg,ier = optimize.leastsq(f, p, maxfev=10000, full_output=1) #, warning=True) #, args=(x, y))
if (len(y) > len(p)) and cov is not None:
#s_sq = (f(popt)**2).sum()/(len(y)-len(p))
s_sq = (infodict['fvec']**2).sum()/(len(y)-len(p))
pcov = cov * s_sq
else:
pcov = float('Inf')
R2 = 1.0 - (infodict['fvec']**2.0).sum() / standard_dev(y)**2.0 / len(y)
# Detailed Output: p,cov,infodict,mesg,ier,pcov,R2
return popt,cov,infodict,mesg,ier,pcov,R2
#______________________________________#
# #
# Maximum Likelihood Fit #
#______________________________________#
# #
def maximum_likelihood(function, parameters, data, full_output=True, verbose=True):
"""
function -> callable: Distribution from which data are drawn. Args: (parameters, x)
parameters -> np.array: initial parameters
data -> np.array: Data
Example:
m=0.5
v=0.5
parameters = numpy.array([m,v])
data = [random.normalvariate(m,v**0.5) for i in range(1000)]
def function(p,x): return numpy.exp(-(x-p[0])**2.0/2.0/p[1])/(2.0*numpy.pi*p[1])**0.5
maximum_likelihood(function, parameters, data)
# # Check that is consistent with Least Squares when "function" is a gaussian:
# mm=Parameter(0.1)
# vv=Parameter(0.1)
# def func(x): return numpy.exp(-(x-mm())**2.0/2.0/vv())/(2.0*numpy.pi*vv())**0.5
# x,y = zip(*pdf(0.1,data,out='no'))
# popt,cov,infodict,mesg,ier,pcov,chi2 = LSfit(func, [mm,vv], y, x)
# popt
#
# # And with the exact M-L values:
# mm = sum(data)/len(data)
# vv = standard_dev(data)
# mm, vv**2.0
"""
def MLprod(p, data, function):
return -np.sum(np.array([np.log(function(p,x)) for x in data]))
return optimize.fmin(MLprod, parameters, args=(data,function), full_output=full_output, disp=verbose)
| [
"numpy.array",
"scipy.optimize.fmin",
"scipy.optimize.leastsq"
] | [((7735, 7746), 'numpy.array', 'np.array', (['x'], {}), '(x)\n', (7743, 7746), True, 'import numpy as np\n'), ((7755, 7766), 'numpy.array', 'np.array', (['y'], {}), '(y)\n', (7763, 7766), True, 'import numpy as np\n'), ((7985, 8036), 'scipy.optimize.leastsq', 'optimize.leastsq', (['f', 'p'], {'maxfev': '(10000)', 'full_output': '(1)'}), '(f, p, maxfev=10000, full_output=1)\n', (8001, 8036), False, 'from scipy import optimize\n'), ((9917, 10017), 'scipy.optimize.fmin', 'optimize.fmin', (['MLprod', 'parameters'], {'args': '(data, function)', 'full_output': 'full_output', 'disp': 'verbose'}), '(MLprod, parameters, args=(data, function), full_output=\n full_output, disp=verbose)\n', (9930, 10017), False, 'from scipy import optimize\n')] |
#!/usr/bin/env python3
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
# Author: <NAME>, <NAME> & <NAME>
# Copyright 2019, by the California Institute of Technology. ALL RIGHTS
# RESERVED. United States Government Sponsorship acknowledged.
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
import os
import numpy as np
from RAiDER.logger import logger
from RAiDER.utilFcns import getTimeFromFile
import matplotlib.pyplot as plt
def prepareWeatherModel(
weatherDict,
time=None,
wmLoc=None,
lats=None,
lons=None,
zref=None,
download_only=False,
makePlots=False
):
'''
Parse inputs to download and prepare a weather model grid for interpolation
'''
weather_model, weather_files = (weatherDict['type'],
weatherDict['files']
)
weather_model.files = weather_files
# Ensure the file output location exists
if wmLoc is None:
wmLoc = os.path.join(os.getcwd(), 'weather_files')
os.makedirs(wmLoc, exist_ok=True)
# check whether weather model files are supplied or should be downloaded
download_flag = True
if weather_model.files is None:
if time is None:
raise RuntimeError(
'prepareWeatherModel: Either a file or a time must be specified'
)
weather_model.filename(time, wmLoc)
if os.path.exists(weather_model.files[0]):
logger.warning(
'Weather model already exists, '
'please remove it ("%s") if you want '
'to download a new one.', weather_model.files
)
download_flag = False
else:
download_flag = False
# if no weather model files supplied, check the standard location
if download_flag:
weather_model.fetch(*weather_model.files, lats, lons, time)
else:
time = getTimeFromFile(weather_model.files[0])
weather_model.setTime(time)
containment = weather_model.checkContainment(lats, lons)
if not containment:
logger.error(
'The weather model passed does not cover all of the input '
'points; you need to download a larger area.'
)
raise RuntimeError(
'The weather model passed does not cover all of the input '
'points; you need to download a larger area.'
)
# If only downloading, exit now
if download_only:
logger.warning(
'download_only flag selected. No further processing will happen.'
)
return None
# Otherwise, load the weather model data
f = weather_model.load(
wmLoc,
outLats=lats,
outLons=lons,
zref=zref,
)
if f is not None:
logger.warning(
'The processed weather model file already exists,'
' so I will use that.'
)
return f
# Logging some basic info
logger.debug(
'Number of weather model nodes: {}'.format(
np.prod(weather_model.getWetRefractivity().shape)
)
)
shape = weather_model.getWetRefractivity().shape
logger.debug(f'Shape of weather model: {shape}')
logger.debug(
'Bounds of the weather model: %.2f/%.2f/%.2f/%.2f (SNWE)',
np.nanmin(weather_model._ys), np.nanmax(weather_model._ys),
np.nanmin(weather_model._xs), np.nanmax(weather_model._xs)
)
logger.debug('Weather model: %s', weather_model.Model())
logger.debug(
'Mean value of the wet refractivity: %f',
np.nanmean(weather_model.getWetRefractivity())
)
logger.debug(
'Mean value of the hydrostatic refractivity: %f',
np.nanmean(weather_model.getHydroRefractivity())
)
logger.debug(weather_model)
if makePlots:
weather_model.plot('wh', True)
weather_model.plot('pqt', True)
plt.close('all')
try:
f = weather_model.write()
return f
except Exception as e:
logger.exception("Unable to save weathermodel to file")
logger.exception(e)
raise RuntimeError("Unable to save weathermodel to file")
finally:
del weather_model
| [
"os.path.exists",
"os.makedirs",
"RAiDER.logger.logger.debug",
"RAiDER.logger.logger.error",
"os.getcwd",
"matplotlib.pyplot.close",
"numpy.nanmax",
"numpy.nanmin",
"RAiDER.logger.logger.warning",
"RAiDER.logger.logger.exception",
"RAiDER.utilFcns.getTimeFromFile"
] | [((1085, 1118), 'os.makedirs', 'os.makedirs', (['wmLoc'], {'exist_ok': '(True)'}), '(wmLoc, exist_ok=True)\n', (1096, 1118), False, 'import os\n'), ((3260, 3308), 'RAiDER.logger.logger.debug', 'logger.debug', (['f"""Shape of weather model: {shape}"""'], {}), "(f'Shape of weather model: {shape}')\n", (3272, 3308), False, 'from RAiDER.logger import logger\n'), ((3868, 3895), 'RAiDER.logger.logger.debug', 'logger.debug', (['weather_model'], {}), '(weather_model)\n', (3880, 3895), False, 'from RAiDER.logger import logger\n'), ((1464, 1502), 'os.path.exists', 'os.path.exists', (['weather_model.files[0]'], {}), '(weather_model.files[0])\n', (1478, 1502), False, 'import os\n'), ((1972, 2011), 'RAiDER.utilFcns.getTimeFromFile', 'getTimeFromFile', (['weather_model.files[0]'], {}), '(weather_model.files[0])\n', (1987, 2011), False, 'from RAiDER.utilFcns import getTimeFromFile\n'), ((2571, 2657), 'RAiDER.logger.logger.warning', 'logger.warning', (['"""download_only flag selected. No further processing will happen."""'], {}), "(\n 'download_only flag selected. No further processing will happen.')\n", (2585, 2657), False, 'from RAiDER.logger import logger\n'), ((2883, 2974), 'RAiDER.logger.logger.warning', 'logger.warning', (['"""The processed weather model file already exists, so I will use that."""'], {}), "(\n 'The processed weather model file already exists, so I will use that.')\n", (2897, 2974), False, 'from RAiDER.logger import logger\n'), ((3402, 3430), 'numpy.nanmin', 'np.nanmin', (['weather_model._ys'], {}), '(weather_model._ys)\n', (3411, 3430), True, 'import numpy as np\n'), ((3432, 3460), 'numpy.nanmax', 'np.nanmax', (['weather_model._ys'], {}), '(weather_model._ys)\n', (3441, 3460), True, 'import numpy as np\n'), ((3470, 3498), 'numpy.nanmin', 'np.nanmin', (['weather_model._xs'], {}), '(weather_model._xs)\n', (3479, 3498), True, 'import numpy as np\n'), ((3500, 3528), 'numpy.nanmax', 'np.nanmax', (['weather_model._xs'], {}), '(weather_model._xs)\n', (3509, 3528), True, 'import numpy as np\n'), ((4002, 4018), 'matplotlib.pyplot.close', 'plt.close', (['"""all"""'], {}), "('all')\n", (4011, 4018), True, 'import matplotlib.pyplot as plt\n'), ((1051, 1062), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (1060, 1062), False, 'import os\n'), ((1516, 1653), 'RAiDER.logger.logger.warning', 'logger.warning', (['"""Weather model already exists, please remove it ("%s") if you want to download a new one."""', 'weather_model.files'], {}), '(\n \'Weather model already exists, please remove it ("%s") if you want to download a new one.\'\n , weather_model.files)\n', (1530, 1653), False, 'from RAiDER.logger import logger\n'), ((2154, 2280), 'RAiDER.logger.logger.error', 'logger.error', (['"""The weather model passed does not cover all of the input points; you need to download a larger area."""'], {}), "(\n 'The weather model passed does not cover all of the input points; you need to download a larger area.'\n )\n", (2166, 2280), False, 'from RAiDER.logger import logger\n'), ((4115, 4170), 'RAiDER.logger.logger.exception', 'logger.exception', (['"""Unable to save weathermodel to file"""'], {}), "('Unable to save weathermodel to file')\n", (4131, 4170), False, 'from RAiDER.logger import logger\n'), ((4179, 4198), 'RAiDER.logger.logger.exception', 'logger.exception', (['e'], {}), '(e)\n', (4195, 4198), False, 'from RAiDER.logger import logger\n')] |
#!/usr/bin/python
# vim: set fileencoding=utf-8 :
"""Extract counts of each Köppen-Geiger/slope/land cover/soil health for each country,
for use in Project Drawdown solution models."""
import argparse
import math
import os.path
import pdb
import signal
import sys
import tempfile
import osgeo.gdal
import osgeo.gdal_array
import osgeo.ogr
import numpy as np
import pandas as pd
import admin_names
import geoutil
pd.set_option("display.max_rows", 500)
pd.set_option("display.max_columns", 40)
pd.options.display.float_format = '{:.2f}'.format
osgeo.gdal.PushErrorHandler("CPLQuietErrorHandler")
np.set_printoptions(threshold=sys.maxsize)
np.seterr(all='raise')
class KGlookup:
"""Lookup table of pixel color to Köppen-Geiger class.
Mappings come from legend.txt file in ZIP archive from
https://www.nature.com/articles/sdata2018214.pdf at http://www.gloh2o.org/koppen/
"""
kg_colors = {
( 0, 0, 255): 'Af', ( 0, 120, 255): 'Am', ( 70, 170, 250): 'Aw',
(255, 0, 0): 'BWh', (255, 150, 150): 'BWk', (245, 165, 0): 'BSh',
(255, 220, 100): 'BSk',
(255, 255, 0): 'Csa', (200, 200, 0): 'Csb', (150, 150, 0): 'Csc',
(150, 255, 150): 'Cwa', (100, 200, 100): 'Cwb', ( 50, 150, 50): 'Cwc',
(200, 255, 80): 'Cfa', (100, 255, 80): 'Cfb', ( 50, 200, 0): 'Cfc',
(255, 0, 255): 'Dsa', (200, 0, 200): 'Dsb', (150, 50, 150): 'Dsc',
(150, 100, 150): 'Dsd', (170, 175, 255): 'Dwa', ( 90, 120, 220): 'Dwb',
( 75, 80, 180): 'Dwc', ( 50, 0, 135): 'Dwd', ( 0, 255, 255): 'Dfa',
( 55, 200, 255): 'Dfb', ( 0, 125, 125): 'Dfc', ( 0, 70, 95): 'Dfd',
(178, 178, 178): 'ET', (102, 102, 102): 'EF',
}
def __init__(self, mapfilename, maskdim='1km'):
self.maskdim = maskdim
self.img = osgeo.gdal.Open(mapfilename, osgeo.gdal.GA_ReadOnly)
self.band = self.img.GetRasterBand(1)
self.ctable = self.band.GetColorTable()
def km2(self, x, y, ncols, nrows, maskblock, km2block, df, admin):
block = self.band.ReadAsArray(x, y, ncols, nrows)
masked = np.ma.masked_array(block, mask=np.logical_not(maskblock))
for label in np.unique(masked):
if label is np.ma.masked:
continue
r, g, b, a = self.ctable.GetColorEntry(int(label))
color = (r, g, b)
if color == (255, 255, 255) or color == (0, 0, 0):
# blank pixel == masked off, just skip it.
continue
typ = self.kg_colors[color]
df.loc[admin, typ] += km2block[masked == label].sum()
def get_columns(self):
return self.kg_colors.values()
class ESA_LC_lookup:
"""Pixel color to Land Cover class in C3S-LC-L4-LCCS-Map-300m-P1Y-2018-v2.1.1.tif
There are legends of LCCS<->color swatch in both
http://maps.elie.ucl.ac.be/CCI/viewer/download/ESACCI-LC-QuickUserGuide-LC-Maps_v2-0-7.pdf
and section 9.1 of http://maps.elie.ucl.ac.be/CCI/viewer/download/ESACCI-LC-Ph2-PUGv2_2.0.pdf
but these were generated from Microsoft Word documents and contain embedded color profiles
for color correction, meaning that what is displayed on the screen (and to any sort of
Digital Color Meter tool) have been shifted and do not match the original colors. Do not
attempt to use the color legend in these files.
There is a table of RGB to LCCS values in
http://maps.elie.ucl.ac.be/CCI/viewer/download/ESACCI-LC-Legend.csv
however: the GeoTIFF file as shipped is greyscale with no color table. Each pixel is 8 bits
not because it is looked up in a color table, it is 8 bits because it has been converted to
greyscale. The authors appear to have carefully chosen the RGB values such that when
converted to greyscale, LCCS class 10 will have a grey value of 10, LCCS class 11 will have
a grey value of 11, and so on.
So we don't need a lookup table, greyscale absolute values directly equal the LCCS class."""
def __init__(self, mapfilename, maskdim='333m'):
self.maskdim = maskdim
self.img = osgeo.gdal.Open(mapfilename, osgeo.gdal.GA_ReadOnly)
self.band = self.img.GetRasterBand(1)
def km2(self, x, y, ncols, nrows, maskblock, km2block, df, admin):
block = self.band.ReadAsArray(x, y, ncols, nrows)
masked = np.ma.masked_array(block, mask=np.logical_not(maskblock)).filled(-1)
for label in np.unique(masked):
if label is np.ma.masked or label == 0 or label == 255:
continue
df.loc[admin, label] += km2block[masked == label].sum()
def get_columns(self):
"""Return list of LCCS classes present in this dataset."""
return [10, 11, 12, 20, 30, 40, 50, 60, 61, 62, 70, 71, 72, 80, 81, 82, 90, 100, 110, 120,
121, 122, 130, 140, 150, 151, 152, 153, 160, 170, 180, 190, 200, 201, 202, 210, 220]
class GeomorphoLookup:
"""Geomorpho90m pre-processed slope file in data/geomorpho90m/classified_*.tif.
There is a band in the TIF for each slope class defined in GAEZ 3.0.
"""
gaez_slopes = ["0-0.5%", "0.5-2%", "2-5%", "5-10%", "10-15%", "15-30%", "30-45%", ">45%"]
def __init__(self, mapfilename, maskdim='1km'):
self.maskdim = maskdim
self.img = osgeo.gdal.Open(mapfilename, osgeo.gdal.GA_ReadOnly)
def km2(self, x, y, ncols, nrows, maskblock, km2block, df, admin):
for b in range(1, 9):
block = self.img.GetRasterBand(b).ReadAsArray(x, y, ncols, nrows).astype(np.float)
mask = np.logical_or(np.logical_not(maskblock), block == 127)
masked = np.ma.masked_array(block, mask=mask, fill_value=0.0)
typ = self.gaez_slopes[b - 1]
df.loc[admin, typ] += (km2block * (masked / 100.0)).sum()
def get_columns(self):
"""Return list of GAEZ slope classes."""
return self.gaez_slopes
class FaoSlopeLookup:
"""FAO GAEZ 3.0 slope files in data/FAO/GloSlopesCl*_30as.tif.
"""
gaez_slopes = ["0-0.5%", "0.5-2%", "2-5%", "5-8%", "8-15%", "15-30%", "30-45%", ">45%"]
def __init__(self, maskdim='1km'):
self.maskdim = maskdim
self.img = {}
for i in range(1, 9):
mapfilename = f"data/FAO/GloSlopesCl{i}_30as.tif"
self.img[i] = osgeo.gdal.Open(mapfilename, osgeo.gdal.GA_ReadOnly)
def km2(self, x, y, ncols, nrows, maskblock, km2block, df, admin):
for i in range(1, 9):
block = self.img[i].GetRasterBand(1).ReadAsArray(x, y, ncols, nrows).astype(np.float)
mask = np.logical_or(np.logical_not(maskblock), block == 255)
masked = np.ma.masked_array(block, mask=mask).filled(0.0)
typ = self.gaez_slopes[i - 1]
df.loc[admin, typ] += np.nansum(km2block * (masked / 100.0))
def get_columns(self):
"""Return list of GAEZ slope classes."""
return self.gaez_slopes
class WorkabilityLookup:
"""Workability TIF has been pre-processed, pixel values are workability class.
"""
def __init__(self, mapfilename, maskdim='1km'):
self.maskdim = maskdim
self.img = osgeo.gdal.Open(mapfilename, osgeo.gdal.GA_ReadOnly)
self.band = self.img.GetRasterBand(1)
def km2(self, x, y, ncols, nrows, maskblock, km2block, df, admin):
block = self.band.ReadAsArray(x, y, ncols, nrows)
masked = np.ma.masked_array(block, mask=np.logical_not(maskblock))
for label in np.unique(masked):
if label is np.ma.masked or label == 0 or label == 255:
# label 0 (black) == no land cover (like water), just skip it.
continue
df.loc[admin, label] += km2block[masked == label].sum()
def get_columns(self):
return range(1, 8)
class DegradedLandLookup:
"""Binary indication of soil in LDPclass 1, 2, or 3."""
def __init__(self, mapfilename, maskdim='1km'):
self.maskdim = maskdim
self.img = osgeo.gdal.Open(mapfilename, osgeo.gdal.GA_ReadOnly)
self.band = self.img.GetRasterBand(1)
def km2(self, x, y, ncols, nrows, maskblock, km2block, df, admin):
block = self.band.ReadAsArray(x, y, ncols, nrows)
masked = np.ma.masked_array(block, mask=np.logical_not(maskblock))
for label in np.unique(masked):
if label is np.ma.masked:
continue
if label == 0.0:
df.loc[admin, "nondegraded"] += km2block[masked == label].sum()
else:
df.loc[admin, "degraded"] += km2block[masked == label].sum()
def get_columns(self):
return ["degraded", "nondegraded"]
def start_pdb(sig, frame):
"""Start PDB on a signal."""
pdb.Pdb().set_trace(frame)
def process_map(lookupobj, csvfilename):
"""Produce a CSV file of areas per country from a dataset."""
shapefilename = 'data/ne_10m_admin_0_countries/ne_10m_admin_0_countries.shp'
df = pd.DataFrame(columns=lookupobj.get_columns(), dtype=float)
df.index.name = 'Country'
shapefile = osgeo.ogr.Open(shapefilename)
assert shapefile.GetLayerCount() == 1
layer = shapefile.GetLayerByIndex(0)
for idx, feature in enumerate(layer):
admin = admin_names.lookup(feature.GetField("ADMIN"))
if admin is None:
continue
a3 = feature.GetField("SOV_A3")
if admin not in df.index:
df.loc[admin] = [0] * len(df.columns)
print(f"Processing {admin:<41} #{a3}_{idx}")
maskfilename = f"masks/{a3}_{idx}_{lookupobj.maskdim}_mask._tif"
maskimg = osgeo.gdal.Open(maskfilename, osgeo.gdal.GA_ReadOnly)
maskband = maskimg.GetRasterBand(1)
x_siz = maskband.XSize
y_siz = maskband.YSize
x_blksiz, y_blksiz = maskband.GetBlockSize()
for y in range(0, y_siz, y_blksiz):
nrows = geoutil.blklim(coord=y, blksiz=y_blksiz, totsiz=y_siz)
for x in range(0, x_siz, x_blksiz):
ncols = geoutil.blklim(coord=x, blksiz=x_blksiz, totsiz=x_siz)
if geoutil.is_sparse(band=maskband, x=x, y=y, ncols=ncols, nrows=nrows):
# sparse hole in image, no data to process
continue
maskblock = maskband.ReadAsArray(x, y, ncols, nrows)
km2block = geoutil.km2_block(nrows=nrows, ncols=ncols, y_off=y, img=maskimg)
lookupobj.km2(x=x, y=y, ncols=ncols, nrows=nrows, maskblock=maskblock,
km2block=km2block, df=df, admin=admin)
outputfilename = os.path.join('results', csvfilename)
df.sort_index(axis='index').to_csv(outputfilename, float_format='%.2f')
return df
def output_by_region(df, csvfilename):
regions = ['OECD90', 'Eastern Europe', 'Asia (Sans Japan)', 'Middle East and Africa',
'Latin America', 'China', 'India', 'EU', 'USA']
df_region = pd.DataFrame(0, index=regions, columns=df.columns.copy())
df_region.index.name = 'Region'
for country, row in df.iterrows():
region = admin_names.region_mapping[country]
if region is not None:
df_region.loc[region, :] += row
df_region.to_csv(csvfilename, float_format='%.2f')
if __name__ == '__main__':
signal.signal(signal.SIGUSR1, start_pdb)
os.environ['GDAL_CACHEMAX'] = '128'
parser = argparse.ArgumentParser(description='Process GeoTIFF datasets for Project Drawdown')
parser.add_argument('--lc', default=False, required=False,
action='store_true', help='process land cover')
parser.add_argument('--kg', default=False, required=False,
action='store_true', help='process Köppen-Geiger')
parser.add_argument('--sl', default=False, required=False,
action='store_true', help='process slope')
parser.add_argument('--wk', default=False, required=False,
action='store_true', help='process workability')
parser.add_argument('--dg', default=False, required=False,
action='store_true', help='process degraded land')
parser.add_argument('--all', default=False, required=False,
action='store_true', help='process all')
args = parser.parse_args()
processed = False
if args.lc or args.all:
mapfilename = 'data/copernicus/C3S-LC-L4-LCCS-Map-300m-P1Y-2018-v2.1.1.tif'
countrycsv = 'Land-Cover-by-country.csv'
regioncsv = 'Land-Cover-by-region.csv'
lookupobj = ESA_LC_lookup(mapfilename)
df = process_map(lookupobj=lookupobj, csvfilename=countrycsv)
output_by_region(df=df, csvfilename=regioncsv)
print('\n')
processed = True
if args.kg or args.all:
mapfilename = 'data/Beck_KG_V1/Beck_KG_V1_present_0p0083.tif'
countrycsv = 'Köppen-Geiger-present-by-country.csv'
regioncsv = 'Köppen-Geiger-present-by-region.csv'
print(mapfilename)
lookupobj = KGlookup(mapfilename)
df = process_map(lookupobj=lookupobj, csvfilename=countrycsv)
output_by_region(df=df, csvfilename=regioncsv)
print('\n')
mapfilename = 'data/Beck_KG_V1/Beck_KG_V1_future_0p0083.tif'
countrycsv = 'Köppen-Geiger-future-by-country.csv'
regioncsv = 'Köppen-Geiger-future-by-region.csv'
print(mapfilename)
lookupobj = KGlookup(mapfilename)
df = process_map(lookupobj=lookupobj, csvfilename=countrycsv)
output_by_region(df=df, csvfilename=regioncsv)
print('\n')
processed = True
if args.sl or args.all:
mapfilename = 'data/geomorpho90m/classified_slope_merit_dem_1km_s0..0cm_2018_v1.0.tif'
countrycsv = 'Slope-by-country.csv'
regioncsv = 'Slope-by-region.csv'
print(mapfilename)
lookupobj = GeomorphoLookup(mapfilename=mapfilename)
df = process_map(lookupobj=lookupobj, csvfilename=countrycsv)
output_by_region(df=df, csvfilename=regioncsv)
print('\n')
processed = True
countrycsv = 'FAO-Slope-by-country.csv'
regioncsv = 'FAO-Slope-by-region.csv'
print('data/FAO/GloSlopesCl*_30as.tif')
lookupobj = FaoSlopeLookup()
df = process_map(lookupobj=lookupobj, csvfilename=countrycsv)
output_by_region(df=df, csvfilename=regioncsv)
print('\n')
processed = True
if args.wk or args.all:
mapfilename = 'data/FAO/workability_FAO_sq7_1km.tif'
countrycsv = 'Workability-by-country.csv'
regioncsv = 'Workability-by-region.csv'
print(mapfilename)
lookupobj = WorkabilityLookup(mapfilename)
df = process_map(lookupobj=lookupobj, csvfilename=countrycsv)
output_by_region(df=df, csvfilename=regioncsv)
print('\n')
processed = True
if not processed:
print('Select one of:')
print('\t-lc : Land Cover')
print('\t-kg : Köppen-Geiger')
print('\t-sl : Slope')
print('\t-wk : Workability')
print('\t-dg : Degraded Land')
print('\t-all')
sys.exit(1)
| [
"signal.signal",
"pdb.Pdb",
"numpy.unique",
"argparse.ArgumentParser",
"numpy.logical_not",
"geoutil.is_sparse",
"pandas.set_option",
"geoutil.km2_block",
"geoutil.blklim",
"sys.exit",
"numpy.ma.masked_array",
"numpy.nansum",
"numpy.seterr",
"numpy.set_printoptions"
] | [((420, 458), 'pandas.set_option', 'pd.set_option', (['"""display.max_rows"""', '(500)'], {}), "('display.max_rows', 500)\n", (433, 458), True, 'import pandas as pd\n'), ((459, 499), 'pandas.set_option', 'pd.set_option', (['"""display.max_columns"""', '(40)'], {}), "('display.max_columns', 40)\n", (472, 499), True, 'import pandas as pd\n'), ((602, 644), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'threshold': 'sys.maxsize'}), '(threshold=sys.maxsize)\n', (621, 644), True, 'import numpy as np\n'), ((645, 667), 'numpy.seterr', 'np.seterr', ([], {'all': '"""raise"""'}), "(all='raise')\n", (654, 667), True, 'import numpy as np\n'), ((11344, 11384), 'signal.signal', 'signal.signal', (['signal.SIGUSR1', 'start_pdb'], {}), '(signal.SIGUSR1, start_pdb)\n', (11357, 11384), False, 'import signal\n'), ((11439, 11528), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Process GeoTIFF datasets for Project Drawdown"""'}), "(description=\n 'Process GeoTIFF datasets for Project Drawdown')\n", (11462, 11528), False, 'import argparse\n'), ((2216, 2233), 'numpy.unique', 'np.unique', (['masked'], {}), '(masked)\n', (2225, 2233), True, 'import numpy as np\n'), ((4512, 4529), 'numpy.unique', 'np.unique', (['masked'], {}), '(masked)\n', (4521, 4529), True, 'import numpy as np\n'), ((7564, 7581), 'numpy.unique', 'np.unique', (['masked'], {}), '(masked)\n', (7573, 7581), True, 'import numpy as np\n'), ((8393, 8410), 'numpy.unique', 'np.unique', (['masked'], {}), '(masked)\n', (8402, 8410), True, 'import numpy as np\n'), ((15193, 15204), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (15201, 15204), False, 'import sys\n'), ((5722, 5774), 'numpy.ma.masked_array', 'np.ma.masked_array', (['block'], {'mask': 'mask', 'fill_value': '(0.0)'}), '(block, mask=mask, fill_value=0.0)\n', (5740, 5774), True, 'import numpy as np\n'), ((6871, 6909), 'numpy.nansum', 'np.nansum', (['(km2block * (masked / 100.0))'], {}), '(km2block * (masked / 100.0))\n', (6880, 6909), True, 'import numpy as np\n'), ((8816, 8825), 'pdb.Pdb', 'pdb.Pdb', ([], {}), '()\n', (8823, 8825), False, 'import pdb\n'), ((9958, 10012), 'geoutil.blklim', 'geoutil.blklim', ([], {'coord': 'y', 'blksiz': 'y_blksiz', 'totsiz': 'y_siz'}), '(coord=y, blksiz=y_blksiz, totsiz=y_siz)\n', (9972, 10012), False, 'import geoutil\n'), ((2168, 2193), 'numpy.logical_not', 'np.logical_not', (['maskblock'], {}), '(maskblock)\n', (2182, 2193), True, 'import numpy as np\n'), ((5660, 5685), 'numpy.logical_not', 'np.logical_not', (['maskblock'], {}), '(maskblock)\n', (5674, 5685), True, 'import numpy as np\n'), ((6684, 6709), 'numpy.logical_not', 'np.logical_not', (['maskblock'], {}), '(maskblock)\n', (6698, 6709), True, 'import numpy as np\n'), ((7516, 7541), 'numpy.logical_not', 'np.logical_not', (['maskblock'], {}), '(maskblock)\n', (7530, 7541), True, 'import numpy as np\n'), ((8345, 8370), 'numpy.logical_not', 'np.logical_not', (['maskblock'], {}), '(maskblock)\n', (8359, 8370), True, 'import numpy as np\n'), ((10085, 10139), 'geoutil.blklim', 'geoutil.blklim', ([], {'coord': 'x', 'blksiz': 'x_blksiz', 'totsiz': 'x_siz'}), '(coord=x, blksiz=x_blksiz, totsiz=x_siz)\n', (10099, 10139), False, 'import geoutil\n'), ((10159, 10227), 'geoutil.is_sparse', 'geoutil.is_sparse', ([], {'band': 'maskband', 'x': 'x', 'y': 'y', 'ncols': 'ncols', 'nrows': 'nrows'}), '(band=maskband, x=x, y=y, ncols=ncols, nrows=nrows)\n', (10176, 10227), False, 'import geoutil\n'), ((10418, 10483), 'geoutil.km2_block', 'geoutil.km2_block', ([], {'nrows': 'nrows', 'ncols': 'ncols', 'y_off': 'y', 'img': 'maskimg'}), '(nrows=nrows, ncols=ncols, y_off=y, img=maskimg)\n', (10435, 10483), False, 'import geoutil\n'), ((6746, 6782), 'numpy.ma.masked_array', 'np.ma.masked_array', (['block'], {'mask': 'mask'}), '(block, mask=mask)\n', (6764, 6782), True, 'import numpy as np\n'), ((4453, 4478), 'numpy.logical_not', 'np.logical_not', (['maskblock'], {}), '(maskblock)\n', (4467, 4478), True, 'import numpy as np\n')] |
"""--- Day 20: Trench Map ---"""
from pathlib import Path
from bitarray import bitarray
from bitarray.util import ba2int
from numpy import array
from numpy import byte
from numpy import ones
from numpy import sum as sum_
from numpy import zeros
from aoc import open_utf8
M_RANGE = 3 // 2 # Algorithm horizontal search window around index.
N_RANGE = 3 // 2 # Algorithm vertical search window around index.
def __enhance_image(image: array, image_enhancement: bitarray, invert):
"""Iterates through each pixel in the image resolves it via the enhancement
algorithm.
:param image: Numpy byte array with containing the pixel values.
:param image_enhancement: Bit array for resolving output pixels based on numeric value.
:param invert: If padding should be done using 1s to correct for the infinite plane.
:return: The enhanced image.
"""
initial_rows, initial_cols = image.shape
# Adding expand range and padding range for padded image
if invert: # Corrects the bordering mistakes
padded_image = ones(
(initial_rows + 4 * M_RANGE, initial_cols + 4 * N_RANGE), dtype=byte
)
else:
padded_image = zeros(
(initial_rows + 4 * M_RANGE, initial_cols + 4 * N_RANGE), dtype=byte
)
padded_image[2 * M_RANGE : -2 * M_RANGE, 2 * N_RANGE : -2 * N_RANGE] = image
# Output image only expands by m and n range.
image = zeros((initial_rows + 2 * M_RANGE, initial_cols + 2 * N_RANGE), dtype=byte)
# Go through the pixels in the actual image and compute the output.
for row_index in range(M_RANGE, padded_image.shape[0] - M_RANGE):
for col_index in range(N_RANGE, padded_image.shape[1] - N_RANGE):
cell_value = ba2int(
bitarray(
[
value
for row in padded_image[
row_index - M_RANGE : row_index + M_RANGE + 1,
col_index - N_RANGE : col_index + N_RANGE + 1,
]
for value in row
]
)
)
image[row_index - M_RANGE, col_index - N_RANGE] = image_enhancement[
cell_value
]
return image
def run_enhancement(image: array, image_enhancement: bitarray, passes: int):
"""Steps through a number of enhancement passes on the input image.
:param image: Numpy byte array with containing the pixel values.
:param image_enhancement: Bit array for resolving output pixels based on numeric value.
:param passes: The number of passes to execute on the image.
:return: The sum of the bright pixels in the resulting image.
"""
for step in range(passes):
image = __enhance_image(
image, image_enhancement, step % 2 and image_enhancement[0] == 1
)
return sum_(image)
def load_dataset(dataset_path: Path) -> (bitarray, array):
"""Loads binary data from file into a bitarray."""
with open_utf8(dataset_path) as file:
image_enhancement = bitarray(
0 if char == "." else 1 for char in file.readline().strip()
)
input_image = array(
[
[0 if char == "." else 1 for char in line.strip()]
for line in file
if len(line.strip()) > 0
],
dtype=byte,
)
return image_enhancement, input_image
| [
"numpy.ones",
"aoc.open_utf8",
"numpy.sum",
"numpy.zeros",
"bitarray.bitarray"
] | [((1422, 1497), 'numpy.zeros', 'zeros', (['(initial_rows + 2 * M_RANGE, initial_cols + 2 * N_RANGE)'], {'dtype': 'byte'}), '((initial_rows + 2 * M_RANGE, initial_cols + 2 * N_RANGE), dtype=byte)\n', (1427, 1497), False, 'from numpy import zeros\n'), ((2898, 2909), 'numpy.sum', 'sum_', (['image'], {}), '(image)\n', (2902, 2909), True, 'from numpy import sum as sum_\n'), ((1050, 1124), 'numpy.ones', 'ones', (['(initial_rows + 4 * M_RANGE, initial_cols + 4 * N_RANGE)'], {'dtype': 'byte'}), '((initial_rows + 4 * M_RANGE, initial_cols + 4 * N_RANGE), dtype=byte)\n', (1054, 1124), False, 'from numpy import ones\n'), ((1180, 1255), 'numpy.zeros', 'zeros', (['(initial_rows + 4 * M_RANGE, initial_cols + 4 * N_RANGE)'], {'dtype': 'byte'}), '((initial_rows + 4 * M_RANGE, initial_cols + 4 * N_RANGE), dtype=byte)\n', (1185, 1255), False, 'from numpy import zeros\n'), ((3035, 3058), 'aoc.open_utf8', 'open_utf8', (['dataset_path'], {}), '(dataset_path)\n', (3044, 3058), False, 'from aoc import open_utf8\n'), ((1763, 1920), 'bitarray.bitarray', 'bitarray', (['[value for row in padded_image[row_index - M_RANGE:row_index + M_RANGE + 1,\n col_index - N_RANGE:col_index + N_RANGE + 1] for value in row]'], {}), '([value for row in padded_image[row_index - M_RANGE:row_index +\n M_RANGE + 1, col_index - N_RANGE:col_index + N_RANGE + 1] for value in row]\n )\n', (1771, 1920), False, 'from bitarray import bitarray\n')] |
import numpy as np
def converge_aitken_series(f, n_start=0, f_startm1=0, eps=1e-6, max_iter=-1, min_consec=2):
"""Finds the limit of a series using Aitken acceleration
an = converge_aitken_series(f, n_start, f_startm1)
where f(n, fp) returns the nth member of the sequence given the n-1th
member e.g. to sum series s_n, f = s_n + fp.
n_start is the first value of n (default 1), f_startm1 is the value of fp
passed at the start (default 0).
Args:
min_consec (int): number of consecutive iterations error must be below eps
to terminate (for robustness)
"""
def aitken(x1, x2, x3):
x1, x2, x3 = np.asarray(x1), np.asarray(x2), np.asarray(x3)
a = x1 - (x2 - x1)**2/(x3 - 2*x2 + x1)
a = np.asarray(a)
inds = np.isnan(a)
a[inds] = x3[inds]
inds = np.isinf(a)
a[inds] = x3[inds]
return a
n = n_start
fnp0 = f(n + 0, f_startm1)
fnp1 = f(n + 1, fnp0)
fnp2 = f(n + 2, fnp1)
an = aitken(fnp0, fnp1, fnp2)
num_consec = 0
while n != max_iter:
n += 1
anm1 = an
fnp0 = fnp1
fnp1 = fnp2
fnp2 = f(n + 2, fnp1)
an = aitken(fnp0, fnp1, fnp2)
err = np.asarray((an - anm1)/an)
anz = an == 0 # Special case for an=0
err[anz] = an[anz] - anm1[anz]
if abs(err).max() < eps:
num_consec += 1
else:
num_consec = 0
if num_consec == min_consec:
break
return an
| [
"numpy.isinf",
"numpy.asarray",
"numpy.isnan"
] | [((765, 778), 'numpy.asarray', 'np.asarray', (['a'], {}), '(a)\n', (775, 778), True, 'import numpy as np\n'), ((794, 805), 'numpy.isnan', 'np.isnan', (['a'], {}), '(a)\n', (802, 805), True, 'import numpy as np\n'), ((848, 859), 'numpy.isinf', 'np.isinf', (['a'], {}), '(a)\n', (856, 859), True, 'import numpy as np\n'), ((1237, 1265), 'numpy.asarray', 'np.asarray', (['((an - anm1) / an)'], {}), '((an - anm1) / an)\n', (1247, 1265), True, 'import numpy as np\n'), ((659, 673), 'numpy.asarray', 'np.asarray', (['x1'], {}), '(x1)\n', (669, 673), True, 'import numpy as np\n'), ((675, 689), 'numpy.asarray', 'np.asarray', (['x2'], {}), '(x2)\n', (685, 689), True, 'import numpy as np\n'), ((691, 705), 'numpy.asarray', 'np.asarray', (['x3'], {}), '(x3)\n', (701, 705), True, 'import numpy as np\n')] |
from google.cloud import storage
import os
from datetime import datetime
import firebase_admin
from firebase_admin import credentials
from firebase_admin import db
import googlemaps
from time import time
import numpy as np
import cv2
# Fetch the service account key JSON file contents
try:
cred = credentials.Certificate('../smart-waste-locator-firebase-adminsdk-ljjzx-495a7e327a.json')
# Initialize the app with a service account, granting admin privileges
firebase_admin.initialize_app(cred, {
'databaseURL': 'https://smart-waste-locator.firebaseio.com/'
})
except:
print("Already Initialized")
with open("../appkey","r") as f:
appkey = f.read()[:-1]
gmaps_keys = googlemaps.Client(key = appkey)
def cloud_upload_image(image):
try:
os.environ["GOOGLE_APPLICATION_CREDENTIALS"]="../smart-waste-locator-firebase-adminsdk-ljjzx-495a7e327a.json"
# Enable firebase Storage
client = storage.Client()
# Reference an existing bucket.
bucket = client.get_bucket('smart-waste-locator.appspot.com')
# Upload a local file to a new file to be created in your bucket.
imname = str(time())+'.jpg'
# path = "./"+imname
Blob = bucket.blob(imname)
encoded, enimg = cv2.imencode('.jpg', image)
if not Blob.exists():
Blob.upload_from_string(enimg.tobytes(), content_type='image/jpeg')
print("Image Uploaded")
# Blob.upload_from_filename(filename=path)
#returning the url
return 'https://firebasestorage.googleapis.com/v0/b/smart-waste-locator.appspot.com/o/'+imname+'?alt=media'
except:
return None
def add_data(image,latitude,longitude,cArea):
link = cloud_upload_image(image)
if link != None:
key = '-'.join([''.join(str(latitude).split('.')) , ''.join(str(longitude).split('.'))])
ref = db.reference('Detected/')
child = ref.child(key)
date = datetime.now()
date = str(date.day)+"/"+str(date.month)+"/"+str(date.year)
result = gmaps_keys.reverse_geocode((latitude, longitude))
area = result[0]['address_components'][0]['long_name']
pincode = result[0]['address_components'][-1]['long_name']
try:
pincode = int(pincode)
except ValueError:
return False
child.set(
{
"Cleaned":"False",
"Notified": False,
"TimeStamp": date,
"image": link,
"Area": area,
"Pincode": pincode,
'latitude': latitude,
'longitude': longitude,
'collectorid': -1,
'contourArea': cArea,
})
return True
else:
return False
def GenerateRandomCoordinates():
#Generate Random Coordiantes in Pune
return [float("%1.4f"%(np.random.uniform(18.4311,18.5995))), float("%1.4f"%(np.random.uniform(73.7469,73.9474)))]
if __name__ == "__main__":
image = "../../img_waste.jpg"
coords = GenerateRandomCoordinates()
print(coords)
print(add_data(image,coords[0],coords[1]))
| [
"firebase_admin.db.reference",
"google.cloud.storage.Client",
"cv2.imencode",
"firebase_admin.initialize_app",
"googlemaps.Client",
"datetime.datetime.now",
"firebase_admin.credentials.Certificate",
"numpy.random.uniform",
"time.time"
] | [((701, 730), 'googlemaps.Client', 'googlemaps.Client', ([], {'key': 'appkey'}), '(key=appkey)\n', (718, 730), False, 'import googlemaps\n'), ((302, 396), 'firebase_admin.credentials.Certificate', 'credentials.Certificate', (['"""../smart-waste-locator-firebase-adminsdk-ljjzx-495a7e327a.json"""'], {}), "(\n '../smart-waste-locator-firebase-adminsdk-ljjzx-495a7e327a.json')\n", (325, 396), False, 'from firebase_admin import credentials\n'), ((471, 574), 'firebase_admin.initialize_app', 'firebase_admin.initialize_app', (['cred', "{'databaseURL': 'https://smart-waste-locator.firebaseio.com/'}"], {}), "(cred, {'databaseURL':\n 'https://smart-waste-locator.firebaseio.com/'})\n", (500, 574), False, 'import firebase_admin\n'), ((948, 964), 'google.cloud.storage.Client', 'storage.Client', ([], {}), '()\n', (962, 964), False, 'from google.cloud import storage\n'), ((1274, 1301), 'cv2.imencode', 'cv2.imencode', (['""".jpg"""', 'image'], {}), "('.jpg', image)\n", (1286, 1301), False, 'import cv2\n'), ((1895, 1920), 'firebase_admin.db.reference', 'db.reference', (['"""Detected/"""'], {}), "('Detected/')\n", (1907, 1920), False, 'from firebase_admin import db\n'), ((1967, 1981), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (1979, 1981), False, 'from datetime import datetime\n'), ((1170, 1176), 'time.time', 'time', ([], {}), '()\n', (1174, 1176), False, 'from time import time\n'), ((2901, 2936), 'numpy.random.uniform', 'np.random.uniform', (['(18.4311)', '(18.5995)'], {}), '(18.4311, 18.5995)\n', (2918, 2936), True, 'import numpy as np\n'), ((2954, 2989), 'numpy.random.uniform', 'np.random.uniform', (['(73.7469)', '(73.9474)'], {}), '(73.7469, 73.9474)\n', (2971, 2989), True, 'import numpy as np\n')] |
from numpy.testing import (assert_allclose, assert_almost_equal,
assert_array_equal, assert_array_almost_equal_nulp)
import numpy as np
import pytest
import matplotlib.mlab as mlab
from matplotlib.cbook.deprecation import MatplotlibDeprecationWarning
def _stride_repeat(*args, **kwargs):
with pytest.warns(MatplotlibDeprecationWarning):
return mlab.stride_repeat(*args, **kwargs)
class TestStride:
def get_base(self, x):
y = x
while y.base is not None:
y = y.base
return y
def calc_window_target(self, x, NFFT, noverlap=0, axis=0):
"""
This is an adaptation of the original window extraction algorithm.
This is here to test to make sure the new implementation has the same
result.
"""
step = NFFT - noverlap
ind = np.arange(0, len(x) - NFFT + 1, step)
n = len(ind)
result = np.zeros((NFFT, n))
# do the ffts of the slices
for i in range(n):
result[:, i] = x[ind[i]:ind[i]+NFFT]
if axis == 1:
result = result.T
return result
@pytest.mark.parametrize('shape', [(), (10, 1)], ids=['0D', '2D'])
def test_stride_windows_invalid_input_shape(self, shape):
x = np.arange(np.prod(shape)).reshape(shape)
with pytest.raises(ValueError):
mlab.stride_windows(x, 5)
@pytest.mark.parametrize('n, noverlap',
[(0, None), (11, None), (2, 2), (2, 3)],
ids=['n less than 1', 'n greater than input',
'noverlap greater than n',
'noverlap equal to n'])
def test_stride_windows_invalid_params(self, n, noverlap):
x = np.arange(10)
with pytest.raises(ValueError):
mlab.stride_windows(x, n, noverlap)
@pytest.mark.parametrize('shape', [(), (10, 1)], ids=['0D', '2D'])
def test_stride_repeat_invalid_input_shape(self, shape):
x = np.arange(np.prod(shape)).reshape(shape)
with pytest.raises(ValueError):
_stride_repeat(x, 5)
@pytest.mark.parametrize('axis', [-1, 2],
ids=['axis less than 0',
'axis greater than input shape'])
def test_stride_repeat_invalid_axis(self, axis):
x = np.array(0)
with pytest.raises(ValueError):
_stride_repeat(x, 5, axis=axis)
def test_stride_repeat_n_lt_1_ValueError(self):
x = np.arange(10)
with pytest.raises(ValueError):
_stride_repeat(x, 0)
@pytest.mark.parametrize('axis', [0, 1], ids=['axis0', 'axis1'])
@pytest.mark.parametrize('n', [1, 5], ids=['n1', 'n5'])
def test_stride_repeat(self, n, axis):
x = np.arange(10)
y = _stride_repeat(x, n, axis=axis)
expected_shape = [10, 10]
expected_shape[axis] = n
yr = np.repeat(np.expand_dims(x, axis), n, axis=axis)
assert yr.shape == y.shape
assert_array_equal(yr, y)
assert tuple(expected_shape) == y.shape
assert self.get_base(y) is x
@pytest.mark.parametrize('axis', [0, 1], ids=['axis0', 'axis1'])
@pytest.mark.parametrize('n, noverlap',
[(1, 0), (5, 0), (15, 2), (13, -3)],
ids=['n1-noverlap0', 'n5-noverlap0',
'n15-noverlap2', 'n13-noverlapn3'])
def test_stride_windows(self, n, noverlap, axis):
x = np.arange(100)
y = mlab.stride_windows(x, n, noverlap=noverlap, axis=axis)
expected_shape = [0, 0]
expected_shape[axis] = n
expected_shape[1 - axis] = 100 // (n - noverlap)
yt = self.calc_window_target(x, n, noverlap=noverlap, axis=axis)
assert yt.shape == y.shape
assert_array_equal(yt, y)
assert tuple(expected_shape) == y.shape
assert self.get_base(y) is x
@pytest.mark.parametrize('axis', [0, 1], ids=['axis0', 'axis1'])
def test_stride_windows_n32_noverlap0_unflatten(self, axis):
n = 32
x = np.arange(n)[np.newaxis]
x1 = np.tile(x, (21, 1))
x2 = x1.flatten()
y = mlab.stride_windows(x2, n, axis=axis)
if axis == 0:
x1 = x1.T
assert y.shape == x1.shape
assert_array_equal(y, x1)
def test_stride_ensure_integer_type(self):
N = 100
x = np.full(N + 20, np.nan)
y = x[10:-10]
y[:] = 0.3
# previous to #3845 lead to corrupt access
y_strided = mlab.stride_windows(y, n=33, noverlap=0.6)
assert_array_equal(y_strided, 0.3)
# previous to #3845 lead to corrupt access
y_strided = mlab.stride_windows(y, n=33.3, noverlap=0)
assert_array_equal(y_strided, 0.3)
# even previous to #3845 could not find any problematic
# configuration however, let's be sure it's not accidentally
# introduced
y_strided = _stride_repeat(y, n=33.815)
assert_array_equal(y_strided, 0.3)
def _apply_window(*args, **kwargs):
with pytest.warns(MatplotlibDeprecationWarning):
return mlab.apply_window(*args, **kwargs)
class TestWindow:
def setup(self):
np.random.seed(0)
n = 1000
self.sig_rand = np.random.standard_normal(n) + 100.
self.sig_ones = np.ones(n)
def check_window_apply_repeat(self, x, window, NFFT, noverlap):
"""
This is an adaptation of the original window application algorithm.
This is here to test to make sure the new implementation has the same
result.
"""
step = NFFT - noverlap
ind = np.arange(0, len(x) - NFFT + 1, step)
n = len(ind)
result = np.zeros((NFFT, n))
if np.iterable(window):
windowVals = window
else:
windowVals = window(np.ones(NFFT, x.dtype))
# do the ffts of the slices
for i in range(n):
result[:, i] = windowVals * x[ind[i]:ind[i]+NFFT]
return result
def test_window_none_rand(self):
res = mlab.window_none(self.sig_ones)
assert_array_equal(res, self.sig_ones)
def test_window_none_ones(self):
res = mlab.window_none(self.sig_rand)
assert_array_equal(res, self.sig_rand)
def test_window_hanning_rand(self):
targ = np.hanning(len(self.sig_rand)) * self.sig_rand
res = mlab.window_hanning(self.sig_rand)
assert_allclose(targ, res, atol=1e-06)
def test_window_hanning_ones(self):
targ = np.hanning(len(self.sig_ones))
res = mlab.window_hanning(self.sig_ones)
assert_allclose(targ, res, atol=1e-06)
def test_apply_window_1D_axis1_ValueError(self):
x = self.sig_rand
window = mlab.window_hanning
with pytest.raises(ValueError):
_apply_window(x, window, axis=1, return_window=False)
def test_apply_window_1D_els_wrongsize_ValueError(self):
x = self.sig_rand
window = mlab.window_hanning(np.ones(x.shape[0]-1))
with pytest.raises(ValueError):
_apply_window(x, window)
def test_apply_window_0D_ValueError(self):
x = np.array(0)
window = mlab.window_hanning
with pytest.raises(ValueError):
_apply_window(x, window, axis=1, return_window=False)
def test_apply_window_3D_ValueError(self):
x = self.sig_rand[np.newaxis][np.newaxis]
window = mlab.window_hanning
with pytest.raises(ValueError):
_apply_window(x, window, axis=1, return_window=False)
def test_apply_window_hanning_1D(self):
x = self.sig_rand
window = mlab.window_hanning
window1 = mlab.window_hanning(np.ones(x.shape[0]))
y, window2 = _apply_window(x, window, return_window=True)
yt = window(x)
assert yt.shape == y.shape
assert x.shape == y.shape
assert_allclose(yt, y, atol=1e-06)
assert_array_equal(window1, window2)
def test_apply_window_hanning_1D_axis0(self):
x = self.sig_rand
window = mlab.window_hanning
y = _apply_window(x, window, axis=0, return_window=False)
yt = window(x)
assert yt.shape == y.shape
assert x.shape == y.shape
assert_allclose(yt, y, atol=1e-06)
def test_apply_window_hanning_els_1D_axis0(self):
x = self.sig_rand
window = mlab.window_hanning(np.ones(x.shape[0]))
window1 = mlab.window_hanning
y = _apply_window(x, window, axis=0, return_window=False)
yt = window1(x)
assert yt.shape == y.shape
assert x.shape == y.shape
assert_allclose(yt, y, atol=1e-06)
def test_apply_window_hanning_2D_axis0(self):
x = np.random.standard_normal([1000, 10]) + 100.
window = mlab.window_hanning
y = _apply_window(x, window, axis=0, return_window=False)
yt = np.zeros_like(x)
for i in range(x.shape[1]):
yt[:, i] = window(x[:, i])
assert yt.shape == y.shape
assert x.shape == y.shape
assert_allclose(yt, y, atol=1e-06)
def test_apply_window_hanning_els1_2D_axis0(self):
x = np.random.standard_normal([1000, 10]) + 100.
window = mlab.window_hanning(np.ones(x.shape[0]))
window1 = mlab.window_hanning
y = _apply_window(x, window, axis=0, return_window=False)
yt = np.zeros_like(x)
for i in range(x.shape[1]):
yt[:, i] = window1(x[:, i])
assert yt.shape == y.shape
assert x.shape == y.shape
assert_allclose(yt, y, atol=1e-06)
def test_apply_window_hanning_els2_2D_axis0(self):
x = np.random.standard_normal([1000, 10]) + 100.
window = mlab.window_hanning
window1 = mlab.window_hanning(np.ones(x.shape[0]))
y, window2 = _apply_window(x, window, axis=0, return_window=True)
yt = np.zeros_like(x)
for i in range(x.shape[1]):
yt[:, i] = window1*x[:, i]
assert yt.shape == y.shape
assert x.shape == y.shape
assert_allclose(yt, y, atol=1e-06)
assert_array_equal(window1, window2)
def test_apply_window_hanning_els3_2D_axis0(self):
x = np.random.standard_normal([1000, 10]) + 100.
window = mlab.window_hanning
window1 = mlab.window_hanning(np.ones(x.shape[0]))
y, window2 = _apply_window(x, window, axis=0, return_window=True)
yt = _apply_window(x, window1, axis=0, return_window=False)
assert yt.shape == y.shape
assert x.shape == y.shape
assert_allclose(yt, y, atol=1e-06)
assert_array_equal(window1, window2)
def test_apply_window_hanning_2D_axis1(self):
x = np.random.standard_normal([10, 1000]) + 100.
window = mlab.window_hanning
y = _apply_window(x, window, axis=1, return_window=False)
yt = np.zeros_like(x)
for i in range(x.shape[0]):
yt[i, :] = window(x[i, :])
assert yt.shape == y.shape
assert x.shape == y.shape
assert_allclose(yt, y, atol=1e-06)
def test_apply_window_hanning_2D_els1_axis1(self):
x = np.random.standard_normal([10, 1000]) + 100.
window = mlab.window_hanning(np.ones(x.shape[1]))
window1 = mlab.window_hanning
y = _apply_window(x, window, axis=1, return_window=False)
yt = np.zeros_like(x)
for i in range(x.shape[0]):
yt[i, :] = window1(x[i, :])
assert yt.shape == y.shape
assert x.shape == y.shape
assert_allclose(yt, y, atol=1e-06)
def test_apply_window_hanning_2D_els2_axis1(self):
x = np.random.standard_normal([10, 1000]) + 100.
window = mlab.window_hanning
window1 = mlab.window_hanning(np.ones(x.shape[1]))
y, window2 = _apply_window(x, window, axis=1, return_window=True)
yt = np.zeros_like(x)
for i in range(x.shape[0]):
yt[i, :] = window1 * x[i, :]
assert yt.shape == y.shape
assert x.shape == y.shape
assert_allclose(yt, y, atol=1e-06)
assert_array_equal(window1, window2)
def test_apply_window_hanning_2D_els3_axis1(self):
x = np.random.standard_normal([10, 1000]) + 100.
window = mlab.window_hanning
window1 = mlab.window_hanning(np.ones(x.shape[1]))
y = _apply_window(x, window, axis=1, return_window=False)
yt = _apply_window(x, window1, axis=1, return_window=False)
assert yt.shape == y.shape
assert x.shape == y.shape
assert_allclose(yt, y, atol=1e-06)
def test_apply_window_stride_windows_hanning_2D_n13_noverlapn3_axis0(self):
x = self.sig_rand
window = mlab.window_hanning
yi = mlab.stride_windows(x, n=13, noverlap=2, axis=0)
y = _apply_window(yi, window, axis=0, return_window=False)
yt = self.check_window_apply_repeat(x, window, 13, 2)
assert yt.shape == y.shape
assert x.shape != y.shape
assert_allclose(yt, y, atol=1e-06)
def test_apply_window_hanning_2D_stack_axis1(self):
ydata = np.arange(32)
ydata1 = ydata+5
ydata2 = ydata+3.3
ycontrol1 = _apply_window(ydata1, mlab.window_hanning)
ycontrol2 = mlab.window_hanning(ydata2)
ydata = np.vstack([ydata1, ydata2])
ycontrol = np.vstack([ycontrol1, ycontrol2])
ydata = np.tile(ydata, (20, 1))
ycontrol = np.tile(ycontrol, (20, 1))
result = _apply_window(ydata, mlab.window_hanning, axis=1,
return_window=False)
assert_allclose(ycontrol, result, atol=1e-08)
def test_apply_window_hanning_2D_stack_windows_axis1(self):
ydata = np.arange(32)
ydata1 = ydata+5
ydata2 = ydata+3.3
ycontrol1 = _apply_window(ydata1, mlab.window_hanning)
ycontrol2 = mlab.window_hanning(ydata2)
ydata = np.vstack([ydata1, ydata2])
ycontrol = np.vstack([ycontrol1, ycontrol2])
ydata = np.tile(ydata, (20, 1))
ycontrol = np.tile(ycontrol, (20, 1))
result = _apply_window(ydata, mlab.window_hanning, axis=1,
return_window=False)
assert_allclose(ycontrol, result, atol=1e-08)
def test_apply_window_hanning_2D_stack_windows_axis1_unflatten(self):
n = 32
ydata = np.arange(n)
ydata1 = ydata+5
ydata2 = ydata+3.3
ycontrol1 = _apply_window(ydata1, mlab.window_hanning)
ycontrol2 = mlab.window_hanning(ydata2)
ydata = np.vstack([ydata1, ydata2])
ycontrol = np.vstack([ycontrol1, ycontrol2])
ydata = np.tile(ydata, (20, 1))
ycontrol = np.tile(ycontrol, (20, 1))
ydata = ydata.flatten()
ydata1 = mlab.stride_windows(ydata, 32, noverlap=0, axis=0)
result = _apply_window(ydata1, mlab.window_hanning, axis=0,
return_window=False)
assert_allclose(ycontrol.T, result, atol=1e-08)
class TestDetrend:
def setup(self):
np.random.seed(0)
n = 1000
x = np.linspace(0., 100, n)
self.sig_zeros = np.zeros(n)
self.sig_off = self.sig_zeros + 100.
self.sig_slope = np.linspace(-10., 90., n)
self.sig_slope_mean = x - x.mean()
sig_rand = np.random.standard_normal(n)
sig_sin = np.sin(x*2*np.pi/(n/100))
sig_rand -= sig_rand.mean()
sig_sin -= sig_sin.mean()
self.sig_base = sig_rand + sig_sin
self.atol = 1e-08
def test_detrend_none_0D_zeros(self):
input = 0.
targ = input
mlab.detrend_none(input)
assert input == targ
def test_detrend_none_0D_zeros_axis1(self):
input = 0.
targ = input
mlab.detrend_none(input, axis=1)
assert input == targ
def test_detrend_str_none_0D_zeros(self):
input = 0.
targ = input
mlab.detrend(input, key='none')
assert input == targ
def test_detrend_detrend_none_0D_zeros(self):
input = 0.
targ = input
mlab.detrend(input, key=mlab.detrend_none)
assert input == targ
def test_detrend_none_0D_off(self):
input = 5.5
targ = input
mlab.detrend_none(input)
assert input == targ
def test_detrend_none_1D_off(self):
input = self.sig_off
targ = input
res = mlab.detrend_none(input)
assert_array_equal(res, targ)
def test_detrend_none_1D_slope(self):
input = self.sig_slope
targ = input
res = mlab.detrend_none(input)
assert_array_equal(res, targ)
def test_detrend_none_1D_base(self):
input = self.sig_base
targ = input
res = mlab.detrend_none(input)
assert_array_equal(res, targ)
def test_detrend_none_1D_base_slope_off_list(self):
input = self.sig_base + self.sig_slope + self.sig_off
targ = input.tolist()
res = mlab.detrend_none(input.tolist())
assert res == targ
def test_detrend_none_2D(self):
arri = [self.sig_base,
self.sig_base + self.sig_off,
self.sig_base + self.sig_slope,
self.sig_base + self.sig_off + self.sig_slope]
input = np.vstack(arri)
targ = input
res = mlab.detrend_none(input)
assert_array_equal(res, targ)
def test_detrend_none_2D_T(self):
arri = [self.sig_base,
self.sig_base + self.sig_off,
self.sig_base + self.sig_slope,
self.sig_base + self.sig_off + self.sig_slope]
input = np.vstack(arri)
targ = input
res = mlab.detrend_none(input.T)
assert_array_equal(res.T, targ)
def test_detrend_mean_0D_zeros(self):
input = 0.
targ = 0.
res = mlab.detrend_mean(input)
assert_almost_equal(res, targ)
def test_detrend_str_mean_0D_zeros(self):
input = 0.
targ = 0.
res = mlab.detrend(input, key='mean')
assert_almost_equal(res, targ)
def test_detrend_detrend_mean_0D_zeros(self):
input = 0.
targ = 0.
res = mlab.detrend(input, key=mlab.detrend_mean)
assert_almost_equal(res, targ)
def test_detrend_mean_0D_off(self):
input = 5.5
targ = 0.
res = mlab.detrend_mean(input)
assert_almost_equal(res, targ)
def test_detrend_str_mean_0D_off(self):
input = 5.5
targ = 0.
res = mlab.detrend(input, key='mean')
assert_almost_equal(res, targ)
def test_detrend_detrend_mean_0D_off(self):
input = 5.5
targ = 0.
res = mlab.detrend(input, key=mlab.detrend_mean)
assert_almost_equal(res, targ)
def test_detrend_mean_1D_zeros(self):
input = self.sig_zeros
targ = self.sig_zeros
res = mlab.detrend_mean(input)
assert_allclose(res, targ, atol=self.atol)
def test_detrend_mean_1D_base(self):
input = self.sig_base
targ = self.sig_base
res = mlab.detrend_mean(input)
assert_allclose(res, targ, atol=self.atol)
def test_detrend_mean_1D_base_off(self):
input = self.sig_base + self.sig_off
targ = self.sig_base
res = mlab.detrend_mean(input)
assert_allclose(res, targ, atol=self.atol)
def test_detrend_mean_1D_base_slope(self):
input = self.sig_base + self.sig_slope
targ = self.sig_base + self.sig_slope_mean
res = mlab.detrend_mean(input)
assert_allclose(res, targ, atol=self.atol)
def test_detrend_mean_1D_base_slope_off(self):
input = self.sig_base + self.sig_slope + self.sig_off
targ = self.sig_base + self.sig_slope_mean
res = mlab.detrend_mean(input)
assert_allclose(res, targ, atol=1e-08)
def test_detrend_mean_1D_base_slope_off_axis0(self):
input = self.sig_base + self.sig_slope + self.sig_off
targ = self.sig_base + self.sig_slope_mean
res = mlab.detrend_mean(input, axis=0)
assert_allclose(res, targ, atol=1e-08)
def test_detrend_mean_1D_base_slope_off_list(self):
input = self.sig_base + self.sig_slope + self.sig_off
targ = self.sig_base + self.sig_slope_mean
res = mlab.detrend_mean(input.tolist())
assert_allclose(res, targ, atol=1e-08)
def test_detrend_mean_1D_base_slope_off_list_axis0(self):
input = self.sig_base + self.sig_slope + self.sig_off
targ = self.sig_base + self.sig_slope_mean
res = mlab.detrend_mean(input.tolist(), axis=0)
assert_allclose(res, targ, atol=1e-08)
def test_detrend_mean_2D_default(self):
arri = [self.sig_off,
self.sig_base + self.sig_off]
arrt = [self.sig_zeros,
self.sig_base]
input = np.vstack(arri)
targ = np.vstack(arrt)
res = mlab.detrend_mean(input)
assert_allclose(res, targ, atol=1e-08)
def test_detrend_mean_2D_none(self):
arri = [self.sig_off,
self.sig_base + self.sig_off]
arrt = [self.sig_zeros,
self.sig_base]
input = np.vstack(arri)
targ = np.vstack(arrt)
res = mlab.detrend_mean(input, axis=None)
assert_allclose(res, targ,
atol=1e-08)
def test_detrend_mean_2D_none_T(self):
arri = [self.sig_off,
self.sig_base + self.sig_off]
arrt = [self.sig_zeros,
self.sig_base]
input = np.vstack(arri).T
targ = np.vstack(arrt)
res = mlab.detrend_mean(input, axis=None)
assert_allclose(res.T, targ,
atol=1e-08)
def test_detrend_mean_2D_axis0(self):
arri = [self.sig_base,
self.sig_base + self.sig_off,
self.sig_base + self.sig_slope,
self.sig_base + self.sig_off + self.sig_slope]
arrt = [self.sig_base,
self.sig_base,
self.sig_base + self.sig_slope_mean,
self.sig_base + self.sig_slope_mean]
input = np.vstack(arri).T
targ = np.vstack(arrt).T
res = mlab.detrend_mean(input, axis=0)
assert_allclose(res, targ,
atol=1e-08)
def test_detrend_mean_2D_axis1(self):
arri = [self.sig_base,
self.sig_base + self.sig_off,
self.sig_base + self.sig_slope,
self.sig_base + self.sig_off + self.sig_slope]
arrt = [self.sig_base,
self.sig_base,
self.sig_base + self.sig_slope_mean,
self.sig_base + self.sig_slope_mean]
input = np.vstack(arri)
targ = np.vstack(arrt)
res = mlab.detrend_mean(input, axis=1)
assert_allclose(res, targ,
atol=1e-08)
def test_detrend_mean_2D_axism1(self):
arri = [self.sig_base,
self.sig_base + self.sig_off,
self.sig_base + self.sig_slope,
self.sig_base + self.sig_off + self.sig_slope]
arrt = [self.sig_base,
self.sig_base,
self.sig_base + self.sig_slope_mean,
self.sig_base + self.sig_slope_mean]
input = np.vstack(arri)
targ = np.vstack(arrt)
res = mlab.detrend_mean(input, axis=-1)
assert_allclose(res, targ,
atol=1e-08)
def test_detrend_2D_default(self):
arri = [self.sig_off,
self.sig_base + self.sig_off]
arrt = [self.sig_zeros,
self.sig_base]
input = np.vstack(arri)
targ = np.vstack(arrt)
res = mlab.detrend(input)
assert_allclose(res, targ, atol=1e-08)
def test_detrend_2D_none(self):
arri = [self.sig_off,
self.sig_base + self.sig_off]
arrt = [self.sig_zeros,
self.sig_base]
input = np.vstack(arri)
targ = np.vstack(arrt)
res = mlab.detrend(input, axis=None)
assert_allclose(res, targ, atol=1e-08)
def test_detrend_str_mean_2D_axis0(self):
arri = [self.sig_base,
self.sig_base + self.sig_off,
self.sig_base + self.sig_slope,
self.sig_base + self.sig_off + self.sig_slope]
arrt = [self.sig_base,
self.sig_base,
self.sig_base + self.sig_slope_mean,
self.sig_base + self.sig_slope_mean]
input = np.vstack(arri).T
targ = np.vstack(arrt).T
res = mlab.detrend(input, key='mean', axis=0)
assert_allclose(res, targ,
atol=1e-08)
def test_detrend_str_constant_2D_none_T(self):
arri = [self.sig_off,
self.sig_base + self.sig_off]
arrt = [self.sig_zeros,
self.sig_base]
input = np.vstack(arri).T
targ = np.vstack(arrt)
res = mlab.detrend(input, key='constant', axis=None)
assert_allclose(res.T, targ,
atol=1e-08)
def test_detrend_str_default_2D_axis1(self):
arri = [self.sig_base,
self.sig_base + self.sig_off,
self.sig_base + self.sig_slope,
self.sig_base + self.sig_off + self.sig_slope]
arrt = [self.sig_base,
self.sig_base,
self.sig_base + self.sig_slope_mean,
self.sig_base + self.sig_slope_mean]
input = np.vstack(arri)
targ = np.vstack(arrt)
res = mlab.detrend(input, key='default', axis=1)
assert_allclose(res, targ,
atol=1e-08)
def test_detrend_detrend_mean_2D_axis0(self):
arri = [self.sig_base,
self.sig_base + self.sig_off,
self.sig_base + self.sig_slope,
self.sig_base + self.sig_off + self.sig_slope]
arrt = [self.sig_base,
self.sig_base,
self.sig_base + self.sig_slope_mean,
self.sig_base + self.sig_slope_mean]
input = np.vstack(arri).T
targ = np.vstack(arrt).T
res = mlab.detrend(input, key=mlab.detrend_mean, axis=0)
assert_allclose(res, targ,
atol=1e-08)
def test_detrend_bad_key_str_ValueError(self):
input = self.sig_slope[np.newaxis]
with pytest.raises(ValueError):
mlab.detrend(input, key='spam')
def test_detrend_bad_key_var_ValueError(self):
input = self.sig_slope[np.newaxis]
with pytest.raises(ValueError):
mlab.detrend(input, key=5)
def test_detrend_mean_0D_d0_ValueError(self):
input = 5.5
with pytest.raises(ValueError):
mlab.detrend_mean(input, axis=0)
def test_detrend_0D_d0_ValueError(self):
input = 5.5
with pytest.raises(ValueError):
mlab.detrend(input, axis=0)
def test_detrend_mean_1D_d1_ValueError(self):
input = self.sig_slope
with pytest.raises(ValueError):
mlab.detrend_mean(input, axis=1)
def test_detrend_1D_d1_ValueError(self):
input = self.sig_slope
with pytest.raises(ValueError):
mlab.detrend(input, axis=1)
def test_detrend_mean_2D_d2_ValueError(self):
input = self.sig_slope[np.newaxis]
with pytest.raises(ValueError):
mlab.detrend_mean(input, axis=2)
def test_detrend_2D_d2_ValueError(self):
input = self.sig_slope[np.newaxis]
with pytest.raises(ValueError):
mlab.detrend(input, axis=2)
def test_detrend_linear_0D_zeros(self):
input = 0.
targ = 0.
res = mlab.detrend_linear(input)
assert_almost_equal(res, targ)
def test_detrend_linear_0D_off(self):
input = 5.5
targ = 0.
res = mlab.detrend_linear(input)
assert_almost_equal(res, targ)
def test_detrend_str_linear_0D_off(self):
input = 5.5
targ = 0.
res = mlab.detrend(input, key='linear')
assert_almost_equal(res, targ)
def test_detrend_detrend_linear_0D_off(self):
input = 5.5
targ = 0.
res = mlab.detrend(input, key=mlab.detrend_linear)
assert_almost_equal(res, targ)
def test_detrend_linear_1d_off(self):
input = self.sig_off
targ = self.sig_zeros
res = mlab.detrend_linear(input)
assert_allclose(res, targ, atol=self.atol)
def test_detrend_linear_1d_slope(self):
input = self.sig_slope
targ = self.sig_zeros
res = mlab.detrend_linear(input)
assert_allclose(res, targ, atol=self.atol)
def test_detrend_linear_1d_slope_off(self):
input = self.sig_slope + self.sig_off
targ = self.sig_zeros
res = mlab.detrend_linear(input)
assert_allclose(res, targ, atol=self.atol)
def test_detrend_str_linear_1d_slope_off(self):
input = self.sig_slope + self.sig_off
targ = self.sig_zeros
res = mlab.detrend(input, key='linear')
assert_allclose(res, targ, atol=self.atol)
def test_detrend_detrend_linear_1d_slope_off(self):
input = self.sig_slope + self.sig_off
targ = self.sig_zeros
res = mlab.detrend(input, key=mlab.detrend_linear)
assert_allclose(res, targ, atol=self.atol)
def test_detrend_linear_1d_slope_off_list(self):
input = self.sig_slope + self.sig_off
targ = self.sig_zeros
res = mlab.detrend_linear(input.tolist())
assert_allclose(res, targ, atol=self.atol)
def test_detrend_linear_2D_ValueError(self):
input = self.sig_slope[np.newaxis]
with pytest.raises(ValueError):
mlab.detrend_linear(input)
def test_detrend_str_linear_2d_slope_off_axis0(self):
arri = [self.sig_off,
self.sig_slope,
self.sig_slope + self.sig_off]
arrt = [self.sig_zeros,
self.sig_zeros,
self.sig_zeros]
input = np.vstack(arri).T
targ = np.vstack(arrt).T
res = mlab.detrend(input, key='linear', axis=0)
assert_allclose(res, targ, atol=self.atol)
def test_detrend_detrend_linear_1d_slope_off_axis1(self):
arri = [self.sig_off,
self.sig_slope,
self.sig_slope + self.sig_off]
arrt = [self.sig_zeros,
self.sig_zeros,
self.sig_zeros]
input = np.vstack(arri).T
targ = np.vstack(arrt).T
res = mlab.detrend(input, key=mlab.detrend_linear, axis=0)
assert_allclose(res, targ, atol=self.atol)
def test_detrend_str_linear_2d_slope_off_axis0_notranspose(self):
arri = [self.sig_off,
self.sig_slope,
self.sig_slope + self.sig_off]
arrt = [self.sig_zeros,
self.sig_zeros,
self.sig_zeros]
input = np.vstack(arri)
targ = np.vstack(arrt)
res = mlab.detrend(input, key='linear', axis=1)
assert_allclose(res, targ, atol=self.atol)
def test_detrend_detrend_linear_1d_slope_off_axis1_notranspose(self):
arri = [self.sig_off,
self.sig_slope,
self.sig_slope + self.sig_off]
arrt = [self.sig_zeros,
self.sig_zeros,
self.sig_zeros]
input = np.vstack(arri)
targ = np.vstack(arrt)
res = mlab.detrend(input, key=mlab.detrend_linear, axis=1)
assert_allclose(res, targ, atol=self.atol)
@pytest.mark.parametrize('iscomplex', [False, True],
ids=['real', 'complex'], scope='class')
@pytest.mark.parametrize('sides', ['onesided', 'twosided', 'default'],
scope='class')
@pytest.mark.parametrize(
'fstims,len_x,NFFT_density,nover_density,pad_to_density,pad_to_spectrum',
[
([], None, -1, -1, -1, -1),
([4], None, -1, -1, -1, -1),
([4, 5, 10], None, -1, -1, -1, -1),
([], None, None, -1, -1, None),
([], None, -1, -1, None, None),
([], None, None, -1, None, None),
([], 1024, 512, -1, -1, 128),
([], 256, -1, -1, 33, 257),
([], 255, 33, -1, -1, None),
([], 256, 128, -1, 256, 256),
([], None, -1, 32, -1, -1),
],
ids=[
'nosig',
'Fs4',
'FsAll',
'nosig_noNFFT',
'nosig_nopad_to',
'nosig_noNFFT_no_pad_to',
'nosig_trim',
'nosig_odd',
'nosig_oddlen',
'nosig_stretch',
'nosig_overlap',
],
scope='class')
class TestSpectral:
@pytest.fixture(scope='class', autouse=True)
def stim(self, request, fstims, iscomplex, sides, len_x, NFFT_density,
nover_density, pad_to_density, pad_to_spectrum):
Fs = 100.
x = np.arange(0, 10, 1 / Fs)
if len_x is not None:
x = x[:len_x]
# get the stimulus frequencies, defaulting to None
fstims = [Fs / fstim for fstim in fstims]
# get the constants, default to calculated values
if NFFT_density is None:
NFFT_density_real = 256
elif NFFT_density < 0:
NFFT_density_real = NFFT_density = 100
else:
NFFT_density_real = NFFT_density
if nover_density is None:
nover_density_real = 0
elif nover_density < 0:
nover_density_real = nover_density = NFFT_density_real // 2
else:
nover_density_real = nover_density
if pad_to_density is None:
pad_to_density_real = NFFT_density_real
elif pad_to_density < 0:
pad_to_density = int(2**np.ceil(np.log2(NFFT_density_real)))
pad_to_density_real = pad_to_density
else:
pad_to_density_real = pad_to_density
if pad_to_spectrum is None:
pad_to_spectrum_real = len(x)
elif pad_to_spectrum < 0:
pad_to_spectrum_real = pad_to_spectrum = len(x)
else:
pad_to_spectrum_real = pad_to_spectrum
if pad_to_spectrum is None:
NFFT_spectrum_real = NFFT_spectrum = pad_to_spectrum_real
else:
NFFT_spectrum_real = NFFT_spectrum = len(x)
nover_spectrum = 0
NFFT_specgram = NFFT_density
nover_specgram = nover_density
pad_to_specgram = pad_to_density
NFFT_specgram_real = NFFT_density_real
nover_specgram_real = nover_density_real
if sides == 'onesided' or (sides == 'default' and not iscomplex):
# frequencies for specgram, psd, and csd
# need to handle even and odd differently
if pad_to_density_real % 2:
freqs_density = np.linspace(0, Fs / 2,
num=pad_to_density_real,
endpoint=False)[::2]
else:
freqs_density = np.linspace(0, Fs / 2,
num=pad_to_density_real // 2 + 1)
# frequencies for complex, magnitude, angle, and phase spectrums
# need to handle even and odd differently
if pad_to_spectrum_real % 2:
freqs_spectrum = np.linspace(0, Fs / 2,
num=pad_to_spectrum_real,
endpoint=False)[::2]
else:
freqs_spectrum = np.linspace(0, Fs / 2,
num=pad_to_spectrum_real // 2 + 1)
else:
# frequencies for specgram, psd, and csd
# need to handle even and odd differentl
if pad_to_density_real % 2:
freqs_density = np.linspace(-Fs / 2, Fs / 2,
num=2 * pad_to_density_real,
endpoint=False)[1::2]
else:
freqs_density = np.linspace(-Fs / 2, Fs / 2,
num=pad_to_density_real,
endpoint=False)
# frequencies for complex, magnitude, angle, and phase spectrums
# need to handle even and odd differently
if pad_to_spectrum_real % 2:
freqs_spectrum = np.linspace(-Fs / 2, Fs / 2,
num=2 * pad_to_spectrum_real,
endpoint=False)[1::2]
else:
freqs_spectrum = np.linspace(-Fs / 2, Fs / 2,
num=pad_to_spectrum_real,
endpoint=False)
freqs_specgram = freqs_density
# time points for specgram
t_start = NFFT_specgram_real // 2
t_stop = len(x) - NFFT_specgram_real // 2 + 1
t_step = NFFT_specgram_real - nover_specgram_real
t_specgram = x[t_start:t_stop:t_step]
if NFFT_specgram_real % 2:
t_specgram += 1 / Fs / 2
if len(t_specgram) == 0:
t_specgram = np.array([NFFT_specgram_real / (2 * Fs)])
t_spectrum = np.array([NFFT_spectrum_real / (2 * Fs)])
t_density = t_specgram
y = np.zeros_like(x)
for i, fstim in enumerate(fstims):
y += np.sin(fstim * x * np.pi * 2) * 10**i
if iscomplex:
y = y.astype('complex')
# Interestingly, the instance on which this fixture is called is not
# the same as the one on which a test is run. So we need to modify the
# class itself when using a class-scoped fixture.
cls = request.cls
cls.Fs = Fs
cls.sides = sides
cls.fstims = fstims
cls.NFFT_density = NFFT_density
cls.nover_density = nover_density
cls.pad_to_density = pad_to_density
cls.NFFT_spectrum = NFFT_spectrum
cls.nover_spectrum = nover_spectrum
cls.pad_to_spectrum = pad_to_spectrum
cls.NFFT_specgram = NFFT_specgram
cls.nover_specgram = nover_specgram
cls.pad_to_specgram = pad_to_specgram
cls.t_specgram = t_specgram
cls.t_density = t_density
cls.t_spectrum = t_spectrum
cls.y = y
cls.freqs_density = freqs_density
cls.freqs_spectrum = freqs_spectrum
cls.freqs_specgram = freqs_specgram
cls.NFFT_density_real = NFFT_density_real
def check_freqs(self, vals, targfreqs, resfreqs, fstims):
assert resfreqs.argmin() == 0
assert resfreqs.argmax() == len(resfreqs)-1
assert_allclose(resfreqs, targfreqs, atol=1e-06)
for fstim in fstims:
i = np.abs(resfreqs - fstim).argmin()
assert vals[i] > vals[i+2]
assert vals[i] > vals[i-2]
def check_maxfreq(self, spec, fsp, fstims):
# skip the test if there are no frequencies
if len(fstims) == 0:
return
# if twosided, do the test for each side
if fsp.min() < 0:
fspa = np.abs(fsp)
zeroind = fspa.argmin()
self.check_maxfreq(spec[:zeroind], fspa[:zeroind], fstims)
self.check_maxfreq(spec[zeroind:], fspa[zeroind:], fstims)
return
fstimst = fstims[:]
spect = spec.copy()
# go through each peak and make sure it is correctly the maximum peak
while fstimst:
maxind = spect.argmax()
maxfreq = fsp[maxind]
assert_almost_equal(maxfreq, fstimst[-1])
del fstimst[-1]
spect[maxind-5:maxind+5] = 0
def test_spectral_helper_raises(self):
# We don't use parametrize here to handle ``y = self.y``.
for kwargs in [ # Various error conditions:
{"y": self.y+1, "mode": "complex"}, # Modes requiring ``x is y``.
{"y": self.y+1, "mode": "magnitude"},
{"y": self.y+1, "mode": "angle"},
{"y": self.y+1, "mode": "phase"},
{"mode": "spam"}, # Bad mode.
{"y": self.y, "sides": "eggs"}, # Bad sides.
{"y": self.y, "NFFT": 10, "noverlap": 20}, # noverlap > NFFT.
{"NFFT": 10, "noverlap": 10}, # noverlap == NFFT.
{"y": self.y, "NFFT": 10,
"window": np.ones(9)}, # len(win) != NFFT.
]:
with pytest.raises(ValueError):
mlab._spectral_helper(x=self.y, **kwargs)
@pytest.mark.parametrize('mode', ['default', 'psd'])
def test_single_spectrum_helper_unsupported_modes(self, mode):
with pytest.raises(ValueError):
mlab._single_spectrum_helper(x=self.y, mode=mode)
@pytest.mark.parametrize("mode, case", [
("psd", "density"),
("magnitude", "specgram"),
("magnitude", "spectrum"),
])
def test_spectral_helper_psd(self, mode, case):
freqs = getattr(self, f"freqs_{case}")
spec, fsp, t = mlab._spectral_helper(
x=self.y, y=self.y,
NFFT=getattr(self, f"NFFT_{case}"),
Fs=self.Fs,
noverlap=getattr(self, f"nover_{case}"),
pad_to=getattr(self, f"pad_to_{case}"),
sides=self.sides,
mode=mode)
assert_allclose(fsp, freqs, atol=1e-06)
assert_allclose(t, getattr(self, f"t_{case}"), atol=1e-06)
assert spec.shape[0] == freqs.shape[0]
assert spec.shape[1] == getattr(self, f"t_{case}").shape[0]
def test_csd(self):
freqs = self.freqs_density
spec, fsp = mlab.csd(x=self.y, y=self.y+1,
NFFT=self.NFFT_density,
Fs=self.Fs,
noverlap=self.nover_density,
pad_to=self.pad_to_density,
sides=self.sides)
assert_allclose(fsp, freqs, atol=1e-06)
assert spec.shape == freqs.shape
def test_csd_padding(self):
"""Test zero padding of csd()."""
if self.NFFT_density is None: # for derived classes
return
sargs = dict(x=self.y, y=self.y+1, Fs=self.Fs, window=mlab.window_none,
sides=self.sides)
spec0, _ = mlab.csd(NFFT=self.NFFT_density, **sargs)
spec1, _ = mlab.csd(NFFT=self.NFFT_density*2, **sargs)
assert_almost_equal(np.sum(np.conjugate(spec0)*spec0).real,
np.sum(np.conjugate(spec1/2)*spec1/2).real)
def test_psd(self):
freqs = self.freqs_density
spec, fsp = mlab.psd(x=self.y,
NFFT=self.NFFT_density,
Fs=self.Fs,
noverlap=self.nover_density,
pad_to=self.pad_to_density,
sides=self.sides)
assert spec.shape == freqs.shape
self.check_freqs(spec, freqs, fsp, self.fstims)
@pytest.mark.parametrize(
'make_data, detrend',
[(np.zeros, mlab.detrend_mean), (np.zeros, 'mean'),
(np.arange, mlab.detrend_linear), (np.arange, 'linear')])
def test_psd_detrend(self, make_data, detrend):
if self.NFFT_density is None:
return
ydata = make_data(self.NFFT_density)
ydata1 = ydata+5
ydata2 = ydata+3.3
ydata = np.vstack([ydata1, ydata2])
ydata = np.tile(ydata, (20, 1))
ydatab = ydata.T.flatten()
ydata = ydata.flatten()
ycontrol = np.zeros_like(ydata)
spec_g, fsp_g = mlab.psd(x=ydata,
NFFT=self.NFFT_density,
Fs=self.Fs,
noverlap=0,
sides=self.sides,
detrend=detrend)
spec_b, fsp_b = mlab.psd(x=ydatab,
NFFT=self.NFFT_density,
Fs=self.Fs,
noverlap=0,
sides=self.sides,
detrend=detrend)
spec_c, fsp_c = mlab.psd(x=ycontrol,
NFFT=self.NFFT_density,
Fs=self.Fs,
noverlap=0,
sides=self.sides)
assert_array_equal(fsp_g, fsp_c)
assert_array_equal(fsp_b, fsp_c)
assert_allclose(spec_g, spec_c, atol=1e-08)
# these should not be almost equal
with pytest.raises(AssertionError):
assert_allclose(spec_b, spec_c, atol=1e-08)
def test_psd_window_hanning(self):
if self.NFFT_density is None:
return
ydata = np.arange(self.NFFT_density)
ydata1 = ydata+5
ydata2 = ydata+3.3
ycontrol1, windowVals = _apply_window(ydata1,
mlab.window_hanning,
return_window=True)
ycontrol2 = mlab.window_hanning(ydata2)
ydata = np.vstack([ydata1, ydata2])
ycontrol = np.vstack([ycontrol1, ycontrol2])
ydata = np.tile(ydata, (20, 1))
ycontrol = np.tile(ycontrol, (20, 1))
ydatab = ydata.T.flatten()
ydataf = ydata.flatten()
ycontrol = ycontrol.flatten()
spec_g, fsp_g = mlab.psd(x=ydataf,
NFFT=self.NFFT_density,
Fs=self.Fs,
noverlap=0,
sides=self.sides,
window=mlab.window_hanning)
spec_b, fsp_b = mlab.psd(x=ydatab,
NFFT=self.NFFT_density,
Fs=self.Fs,
noverlap=0,
sides=self.sides,
window=mlab.window_hanning)
spec_c, fsp_c = mlab.psd(x=ycontrol,
NFFT=self.NFFT_density,
Fs=self.Fs,
noverlap=0,
sides=self.sides,
window=mlab.window_none)
spec_c *= len(ycontrol1)/(np.abs(windowVals)**2).sum()
assert_array_equal(fsp_g, fsp_c)
assert_array_equal(fsp_b, fsp_c)
assert_allclose(spec_g, spec_c, atol=1e-08)
# these should not be almost equal
with pytest.raises(AssertionError):
assert_allclose(spec_b, spec_c, atol=1e-08)
def test_psd_window_hanning_detrend_linear(self):
if self.NFFT_density is None:
return
ydata = np.arange(self.NFFT_density)
ycontrol = np.zeros(self.NFFT_density)
ydata1 = ydata+5
ydata2 = ydata+3.3
ycontrol1 = ycontrol
ycontrol2 = ycontrol
ycontrol1, windowVals = _apply_window(ycontrol1,
mlab.window_hanning,
return_window=True)
ycontrol2 = mlab.window_hanning(ycontrol2)
ydata = np.vstack([ydata1, ydata2])
ycontrol = np.vstack([ycontrol1, ycontrol2])
ydata = np.tile(ydata, (20, 1))
ycontrol = np.tile(ycontrol, (20, 1))
ydatab = ydata.T.flatten()
ydataf = ydata.flatten()
ycontrol = ycontrol.flatten()
spec_g, fsp_g = mlab.psd(x=ydataf,
NFFT=self.NFFT_density,
Fs=self.Fs,
noverlap=0,
sides=self.sides,
detrend=mlab.detrend_linear,
window=mlab.window_hanning)
spec_b, fsp_b = mlab.psd(x=ydatab,
NFFT=self.NFFT_density,
Fs=self.Fs,
noverlap=0,
sides=self.sides,
detrend=mlab.detrend_linear,
window=mlab.window_hanning)
spec_c, fsp_c = mlab.psd(x=ycontrol,
NFFT=self.NFFT_density,
Fs=self.Fs,
noverlap=0,
sides=self.sides,
window=mlab.window_none)
spec_c *= len(ycontrol1)/(np.abs(windowVals)**2).sum()
assert_array_equal(fsp_g, fsp_c)
assert_array_equal(fsp_b, fsp_c)
assert_allclose(spec_g, spec_c, atol=1e-08)
# these should not be almost equal
with pytest.raises(AssertionError):
assert_allclose(spec_b, spec_c, atol=1e-08)
def test_psd_windowarray(self):
freqs = self.freqs_density
spec, fsp = mlab.psd(x=self.y,
NFFT=self.NFFT_density,
Fs=self.Fs,
noverlap=self.nover_density,
pad_to=self.pad_to_density,
sides=self.sides,
window=np.ones(self.NFFT_density_real))
assert_allclose(fsp, freqs, atol=1e-06)
assert spec.shape == freqs.shape
def test_psd_windowarray_scale_by_freq(self):
win = mlab.window_hanning(np.ones(self.NFFT_density_real))
spec, fsp = mlab.psd(x=self.y,
NFFT=self.NFFT_density,
Fs=self.Fs,
noverlap=self.nover_density,
pad_to=self.pad_to_density,
sides=self.sides,
window=mlab.window_hanning)
spec_s, fsp_s = mlab.psd(x=self.y,
NFFT=self.NFFT_density,
Fs=self.Fs,
noverlap=self.nover_density,
pad_to=self.pad_to_density,
sides=self.sides,
window=mlab.window_hanning,
scale_by_freq=True)
spec_n, fsp_n = mlab.psd(x=self.y,
NFFT=self.NFFT_density,
Fs=self.Fs,
noverlap=self.nover_density,
pad_to=self.pad_to_density,
sides=self.sides,
window=mlab.window_hanning,
scale_by_freq=False)
assert_array_equal(fsp, fsp_s)
assert_array_equal(fsp, fsp_n)
assert_array_equal(spec, spec_s)
assert_allclose(spec_s*(win**2).sum(),
spec_n/self.Fs*win.sum()**2,
atol=1e-08)
@pytest.mark.parametrize(
"kind", ["complex", "magnitude", "angle", "phase"])
def test_spectrum(self, kind):
freqs = self.freqs_spectrum
spec, fsp = getattr(mlab, f"{kind}_spectrum")(
x=self.y,
Fs=self.Fs, sides=self.sides, pad_to=self.pad_to_spectrum)
assert_allclose(fsp, freqs, atol=1e-06)
assert spec.shape == freqs.shape
if kind == "magnitude":
self.check_maxfreq(spec, fsp, self.fstims)
self.check_freqs(spec, freqs, fsp, self.fstims)
@pytest.mark.parametrize(
'kwargs',
[{}, {'mode': 'default'}, {'mode': 'psd'}, {'mode': 'magnitude'},
{'mode': 'complex'}, {'mode': 'angle'}, {'mode': 'phase'}])
def test_specgram(self, kwargs):
freqs = self.freqs_specgram
spec, fsp, t = mlab.specgram(x=self.y,
NFFT=self.NFFT_specgram,
Fs=self.Fs,
noverlap=self.nover_specgram,
pad_to=self.pad_to_specgram,
sides=self.sides,
**kwargs)
if kwargs.get('mode') == 'complex':
spec = np.abs(spec)
specm = np.mean(spec, axis=1)
assert_allclose(fsp, freqs, atol=1e-06)
assert_allclose(t, self.t_specgram, atol=1e-06)
assert spec.shape[0] == freqs.shape[0]
assert spec.shape[1] == self.t_specgram.shape[0]
if kwargs.get('mode') not in ['complex', 'angle', 'phase']:
# using a single freq, so all time slices should be about the same
if np.abs(spec.max()) != 0:
assert_allclose(
np.diff(spec, axis=1).max() / np.abs(spec.max()), 0,
atol=1e-02)
if kwargs.get('mode') not in ['angle', 'phase']:
self.check_freqs(specm, freqs, fsp, self.fstims)
def test_specgram_warn_only1seg(self):
"""Warning should be raised if len(x) <= NFFT."""
with pytest.warns(UserWarning, match="Only one segment is calculated"):
mlab.specgram(x=self.y, NFFT=len(self.y), Fs=self.Fs)
def test_psd_csd_equal(self):
Pxx, freqsxx = mlab.psd(x=self.y,
NFFT=self.NFFT_density,
Fs=self.Fs,
noverlap=self.nover_density,
pad_to=self.pad_to_density,
sides=self.sides)
Pxy, freqsxy = mlab.csd(x=self.y, y=self.y,
NFFT=self.NFFT_density,
Fs=self.Fs,
noverlap=self.nover_density,
pad_to=self.pad_to_density,
sides=self.sides)
assert_array_almost_equal_nulp(Pxx, Pxy)
assert_array_equal(freqsxx, freqsxy)
@pytest.mark.parametrize("mode", ["default", "psd"])
def test_specgram_auto_default_psd_equal(self, mode):
"""
Test that mlab.specgram without mode and with mode 'default' and 'psd'
are all the same.
"""
speca, freqspeca, ta = mlab.specgram(x=self.y,
NFFT=self.NFFT_specgram,
Fs=self.Fs,
noverlap=self.nover_specgram,
pad_to=self.pad_to_specgram,
sides=self.sides)
specb, freqspecb, tb = mlab.specgram(x=self.y,
NFFT=self.NFFT_specgram,
Fs=self.Fs,
noverlap=self.nover_specgram,
pad_to=self.pad_to_specgram,
sides=self.sides,
mode=mode)
assert_array_equal(speca, specb)
assert_array_equal(freqspeca, freqspecb)
assert_array_equal(ta, tb)
@pytest.mark.parametrize(
"mode, conv", [
("magnitude", np.abs),
("angle", np.angle),
("phase", lambda x: np.unwrap(np.angle(x), axis=0))
])
def test_specgram_complex_equivalent(self, mode, conv):
specc, freqspecc, tc = mlab.specgram(x=self.y,
NFFT=self.NFFT_specgram,
Fs=self.Fs,
noverlap=self.nover_specgram,
pad_to=self.pad_to_specgram,
sides=self.sides,
mode='complex')
specm, freqspecm, tm = mlab.specgram(x=self.y,
NFFT=self.NFFT_specgram,
Fs=self.Fs,
noverlap=self.nover_specgram,
pad_to=self.pad_to_specgram,
sides=self.sides,
mode=mode)
assert_array_equal(freqspecc, freqspecm)
assert_array_equal(tc, tm)
assert_allclose(conv(specc), specm, atol=1e-06)
def test_psd_windowarray_equal(self):
win = mlab.window_hanning(np.ones(self.NFFT_density_real))
speca, fspa = mlab.psd(x=self.y,
NFFT=self.NFFT_density,
Fs=self.Fs,
noverlap=self.nover_density,
pad_to=self.pad_to_density,
sides=self.sides,
window=win)
specb, fspb = mlab.psd(x=self.y,
NFFT=self.NFFT_density,
Fs=self.Fs,
noverlap=self.nover_density,
pad_to=self.pad_to_density,
sides=self.sides)
assert_array_equal(fspa, fspb)
assert_allclose(speca, specb, atol=1e-08)
# extra test for cohere...
def test_cohere():
N = 1024
np.random.seed(19680801)
x = np.random.randn(N)
# phase offset
y = np.roll(x, 20)
# high-freq roll-off
y = np.convolve(y, np.ones(20) / 20., mode='same')
cohsq, f = mlab.cohere(x, y, NFFT=256, Fs=2, noverlap=128)
assert_allclose(np.mean(cohsq), 0.837, atol=1.e-3)
assert np.isreal(np.mean(cohsq))
#*****************************************************************
# These Tests where taken from SCIPY with some minor modifications
# this can be retrieved from:
# https://github.com/scipy/scipy/blob/master/scipy/stats/tests/test_kdeoth.py
#*****************************************************************
class TestGaussianKDE:
def test_kde_integer_input(self):
"""Regression test for #1181."""
x1 = np.arange(5)
kde = mlab.GaussianKDE(x1)
y_expected = [0.13480721, 0.18222869, 0.19514935, 0.18222869,
0.13480721]
np.testing.assert_array_almost_equal(kde(x1), y_expected, decimal=6)
def test_gaussian_kde_covariance_caching(self):
x1 = np.array([-7, -5, 1, 4, 5], dtype=float)
xs = np.linspace(-10, 10, num=5)
# These expected values are from scipy 0.10, before some changes to
# gaussian_kde. They were not compared with any external reference.
y_expected = [0.02463386, 0.04689208, 0.05395444, 0.05337754,
0.01664475]
# set it to the default bandwidth.
kde2 = mlab.GaussianKDE(x1, 'scott')
y2 = kde2(xs)
np.testing.assert_array_almost_equal(y_expected, y2, decimal=7)
def test_kde_bandwidth_method(self):
np.random.seed(8765678)
n_basesample = 50
xn = np.random.randn(n_basesample)
# Default
gkde = mlab.GaussianKDE(xn)
# Supply a callable
gkde2 = mlab.GaussianKDE(xn, 'scott')
# Supply a scalar
gkde3 = mlab.GaussianKDE(xn, bw_method=gkde.factor)
xs = np.linspace(-7, 7, 51)
kdepdf = gkde.evaluate(xs)
kdepdf2 = gkde2.evaluate(xs)
assert kdepdf.all() == kdepdf2.all()
kdepdf3 = gkde3.evaluate(xs)
assert kdepdf.all() == kdepdf3.all()
class TestGaussianKDECustom:
def test_no_data(self):
"""Pass no data into the GaussianKDE class."""
with pytest.raises(ValueError):
mlab.GaussianKDE([])
def test_single_dataset_element(self):
"""Pass a single dataset element into the GaussianKDE class."""
with pytest.raises(ValueError):
mlab.GaussianKDE([42])
def test_silverman_multidim_dataset(self):
"""Test silverman's for a multi-dimensional array."""
x1 = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
with pytest.raises(np.linalg.LinAlgError):
mlab.GaussianKDE(x1, "silverman")
def test_silverman_singledim_dataset(self):
"""Test silverman's output for a single dimension list."""
x1 = np.array([-7, -5, 1, 4, 5])
mygauss = mlab.GaussianKDE(x1, "silverman")
y_expected = 0.76770389927475502
assert_almost_equal(mygauss.covariance_factor(), y_expected, 7)
def test_scott_multidim_dataset(self):
"""Test scott's output for a multi-dimensional array."""
x1 = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
with pytest.raises(np.linalg.LinAlgError):
mlab.GaussianKDE(x1, "scott")
def test_scott_singledim_dataset(self):
"""Test scott's output a single-dimensional array."""
x1 = np.array([-7, -5, 1, 4, 5])
mygauss = mlab.GaussianKDE(x1, "scott")
y_expected = 0.72477966367769553
assert_almost_equal(mygauss.covariance_factor(), y_expected, 7)
def test_scalar_empty_dataset(self):
"""Test the scalar's cov factor for an empty array."""
with pytest.raises(ValueError):
mlab.GaussianKDE([], bw_method=5)
def test_scalar_covariance_dataset(self):
"""Test a scalar's cov factor."""
np.random.seed(8765678)
n_basesample = 50
multidim_data = [np.random.randn(n_basesample) for i in range(5)]
kde = mlab.GaussianKDE(multidim_data, bw_method=0.5)
assert kde.covariance_factor() == 0.5
def test_callable_covariance_dataset(self):
"""Test the callable's cov factor for a multi-dimensional array."""
np.random.seed(8765678)
n_basesample = 50
multidim_data = [np.random.randn(n_basesample) for i in range(5)]
def callable_fun(x):
return 0.55
kde = mlab.GaussianKDE(multidim_data, bw_method=callable_fun)
assert kde.covariance_factor() == 0.55
def test_callable_singledim_dataset(self):
"""Test the callable's cov factor for a single-dimensional array."""
np.random.seed(8765678)
n_basesample = 50
multidim_data = np.random.randn(n_basesample)
kde = mlab.GaussianKDE(multidim_data, bw_method='silverman')
y_expected = 0.48438841363348911
assert_almost_equal(kde.covariance_factor(), y_expected, 7)
def test_wrong_bw_method(self):
"""Test the error message that should be called when bw is invalid."""
np.random.seed(8765678)
n_basesample = 50
data = np.random.randn(n_basesample)
with pytest.raises(ValueError):
mlab.GaussianKDE(data, bw_method="invalid")
class TestGaussianKDEEvaluate:
def test_evaluate_diff_dim(self):
"""
Test the evaluate method when the dim's of dataset and points have
different dimensions.
"""
x1 = np.arange(3, 10, 2)
kde = mlab.GaussianKDE(x1)
x2 = np.arange(3, 12, 2)
y_expected = [
0.08797252, 0.11774109, 0.11774109, 0.08797252, 0.0370153
]
y = kde.evaluate(x2)
np.testing.assert_array_almost_equal(y, y_expected, 7)
def test_evaluate_inv_dim(self):
"""
Invert the dimensions; i.e., for a dataset of dimension 1 [3, 2, 4],
the points should have a dimension of 3 [[3], [2], [4]].
"""
np.random.seed(8765678)
n_basesample = 50
multidim_data = np.random.randn(n_basesample)
kde = mlab.GaussianKDE(multidim_data)
x2 = [[1], [2], [3]]
with pytest.raises(ValueError):
kde.evaluate(x2)
def test_evaluate_dim_and_num(self):
"""Tests if evaluated against a one by one array"""
x1 = np.arange(3, 10, 2)
x2 = np.array([3])
kde = mlab.GaussianKDE(x1)
y_expected = [0.08797252]
y = kde.evaluate(x2)
np.testing.assert_array_almost_equal(y, y_expected, 7)
def test_evaluate_point_dim_not_one(self):
x1 = np.arange(3, 10, 2)
x2 = [np.arange(3, 10, 2), np.arange(3, 10, 2)]
kde = mlab.GaussianKDE(x1)
with pytest.raises(ValueError):
kde.evaluate(x2)
def test_evaluate_equal_dim_and_num_lt(self):
x1 = np.arange(3, 10, 2)
x2 = np.arange(3, 8, 2)
kde = mlab.GaussianKDE(x1)
y_expected = [0.08797252, 0.11774109, 0.11774109]
y = kde.evaluate(x2)
np.testing.assert_array_almost_equal(y, y_expected, 7)
def test_psd_onesided_norm():
u = np.array([0, 1, 2, 3, 1, 2, 1])
dt = 1.0
Su = np.abs(np.fft.fft(u) * dt)**2 / (dt * u.size)
P, f = mlab.psd(u, NFFT=u.size, Fs=1/dt, window=mlab.window_none,
detrend=mlab.detrend_none, noverlap=0, pad_to=None,
scale_by_freq=None,
sides='onesided')
Su_1side = np.append([Su[0]], Su[1:4] + Su[4:][::-1])
assert_allclose(P, Su_1side, atol=1e-06)
def test_psd_oversampling():
"""Test the case len(x) < NFFT for psd()."""
u = np.array([0, 1, 2, 3, 1, 2, 1])
dt = 1.0
Su = np.abs(np.fft.fft(u) * dt)**2 / (dt * u.size)
P, f = mlab.psd(u, NFFT=u.size*2, Fs=1/dt, window=mlab.window_none,
detrend=mlab.detrend_none, noverlap=0, pad_to=None,
scale_by_freq=None,
sides='onesided')
Su_1side = np.append([Su[0]], Su[1:4] + Su[4:][::-1])
assert_almost_equal(np.sum(P), np.sum(Su_1side)) # same energy
| [
"numpy.random.standard_normal",
"matplotlib.mlab.detrend_linear",
"matplotlib.mlab.specgram",
"numpy.iterable",
"numpy.prod",
"matplotlib.mlab._single_spectrum_helper",
"numpy.array",
"pytest.fixture",
"numpy.sin",
"matplotlib.mlab.psd",
"numpy.arange",
"matplotlib.mlab.apply_window",
"numpy... | [((32566, 32661), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""iscomplex"""', '[False, True]'], {'ids': "['real', 'complex']", 'scope': '"""class"""'}), "('iscomplex', [False, True], ids=['real', 'complex'],\n scope='class')\n", (32589, 32661), False, 'import pytest\n'), ((32686, 32775), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""sides"""', "['onesided', 'twosided', 'default']"], {'scope': '"""class"""'}), "('sides', ['onesided', 'twosided', 'default'], scope\n ='class')\n", (32709, 32775), False, 'import pytest\n'), ((32799, 33457), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""fstims,len_x,NFFT_density,nover_density,pad_to_density,pad_to_spectrum"""', '[([], None, -1, -1, -1, -1), ([4], None, -1, -1, -1, -1), ([4, 5, 10], None,\n -1, -1, -1, -1), ([], None, None, -1, -1, None), ([], None, -1, -1,\n None, None), ([], None, None, -1, None, None), ([], 1024, 512, -1, -1, \n 128), ([], 256, -1, -1, 33, 257), ([], 255, 33, -1, -1, None), ([], 256,\n 128, -1, 256, 256), ([], None, -1, 32, -1, -1)]'], {'ids': "['nosig', 'Fs4', 'FsAll', 'nosig_noNFFT', 'nosig_nopad_to',\n 'nosig_noNFFT_no_pad_to', 'nosig_trim', 'nosig_odd', 'nosig_oddlen',\n 'nosig_stretch', 'nosig_overlap']", 'scope': '"""class"""'}), "(\n 'fstims,len_x,NFFT_density,nover_density,pad_to_density,pad_to_spectrum',\n [([], None, -1, -1, -1, -1), ([4], None, -1, -1, -1, -1), ([4, 5, 10],\n None, -1, -1, -1, -1), ([], None, None, -1, -1, None), ([], None, -1, -\n 1, None, None), ([], None, None, -1, None, None), ([], 1024, 512, -1, -\n 1, 128), ([], 256, -1, -1, 33, 257), ([], 255, 33, -1, -1, None), ([], \n 256, 128, -1, 256, 256), ([], None, -1, 32, -1, -1)], ids=['nosig',\n 'Fs4', 'FsAll', 'nosig_noNFFT', 'nosig_nopad_to',\n 'nosig_noNFFT_no_pad_to', 'nosig_trim', 'nosig_odd', 'nosig_oddlen',\n 'nosig_stretch', 'nosig_overlap'], scope='class')\n", (32822, 33457), False, 'import pytest\n'), ((1187, 1252), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""shape"""', '[(), (10, 1)]'], {'ids': "['0D', '2D']"}), "('shape', [(), (10, 1)], ids=['0D', '2D'])\n", (1210, 1252), False, 'import pytest\n'), ((1458, 1643), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""n, noverlap"""', '[(0, None), (11, None), (2, 2), (2, 3)]'], {'ids': "['n less than 1', 'n greater than input', 'noverlap greater than n',\n 'noverlap equal to n']"}), "('n, noverlap', [(0, None), (11, None), (2, 2), (2, \n 3)], ids=['n less than 1', 'n greater than input',\n 'noverlap greater than n', 'noverlap equal to n'])\n", (1481, 1643), False, 'import pytest\n'), ((1954, 2019), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""shape"""', '[(), (10, 1)]'], {'ids': "['0D', '2D']"}), "('shape', [(), (10, 1)], ids=['0D', '2D'])\n", (1977, 2019), False, 'import pytest\n'), ((2219, 2322), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""axis"""', '[-1, 2]'], {'ids': "['axis less than 0', 'axis greater than input shape']"}), "('axis', [-1, 2], ids=['axis less than 0',\n 'axis greater than input shape'])\n", (2242, 2322), False, 'import pytest\n'), ((2714, 2777), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""axis"""', '[0, 1]'], {'ids': "['axis0', 'axis1']"}), "('axis', [0, 1], ids=['axis0', 'axis1'])\n", (2737, 2777), False, 'import pytest\n'), ((2784, 2838), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""n"""', '[1, 5]'], {'ids': "['n1', 'n5']"}), "('n', [1, 5], ids=['n1', 'n5'])\n", (2807, 2838), False, 'import pytest\n'), ((3257, 3320), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""axis"""', '[0, 1]'], {'ids': "['axis0', 'axis1']"}), "('axis', [0, 1], ids=['axis0', 'axis1'])\n", (3280, 3320), False, 'import pytest\n'), ((3327, 3479), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""n, noverlap"""', '[(1, 0), (5, 0), (15, 2), (13, -3)]'], {'ids': "['n1-noverlap0', 'n5-noverlap0', 'n15-noverlap2', 'n13-noverlapn3']"}), "('n, noverlap', [(1, 0), (5, 0), (15, 2), (13, -3)],\n ids=['n1-noverlap0', 'n5-noverlap0', 'n15-noverlap2', 'n13-noverlapn3'])\n", (3350, 3479), False, 'import pytest\n'), ((4092, 4155), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""axis"""', '[0, 1]'], {'ids': "['axis0', 'axis1']"}), "('axis', [0, 1], ids=['axis0', 'axis1'])\n", (4115, 4155), False, 'import pytest\n'), ((33679, 33722), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""class"""', 'autouse': '(True)'}), "(scope='class', autouse=True)\n", (33693, 33722), False, 'import pytest\n'), ((41739, 41790), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""mode"""', "['default', 'psd']"], {}), "('mode', ['default', 'psd'])\n", (41762, 41790), False, 'import pytest\n'), ((41971, 42088), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""mode, case"""', "[('psd', 'density'), ('magnitude', 'specgram'), ('magnitude', 'spectrum')]"], {}), "('mode, case', [('psd', 'density'), ('magnitude',\n 'specgram'), ('magnitude', 'spectrum')])\n", (41994, 42088), False, 'import pytest\n'), ((44262, 44426), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""make_data, detrend"""', "[(np.zeros, mlab.detrend_mean), (np.zeros, 'mean'), (np.arange, mlab.\n detrend_linear), (np.arange, 'linear')]"], {}), "('make_data, detrend', [(np.zeros, mlab.detrend_mean\n ), (np.zeros, 'mean'), (np.arange, mlab.detrend_linear), (np.arange,\n 'linear')])\n", (44285, 44426), False, 'import pytest\n'), ((52417, 52492), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""kind"""', "['complex', 'magnitude', 'angle', 'phase']"], {}), "('kind', ['complex', 'magnitude', 'angle', 'phase'])\n", (52440, 52492), False, 'import pytest\n'), ((52976, 53143), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""kwargs"""', "[{}, {'mode': 'default'}, {'mode': 'psd'}, {'mode': 'magnitude'}, {'mode':\n 'complex'}, {'mode': 'angle'}, {'mode': 'phase'}]"], {}), "('kwargs', [{}, {'mode': 'default'}, {'mode': 'psd'},\n {'mode': 'magnitude'}, {'mode': 'complex'}, {'mode': 'angle'}, {'mode':\n 'phase'}])\n", (52999, 53143), False, 'import pytest\n'), ((55468, 55519), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""mode"""', "['default', 'psd']"], {}), "('mode', ['default', 'psd'])\n", (55491, 55519), False, 'import pytest\n'), ((58972, 58996), 'numpy.random.seed', 'np.random.seed', (['(19680801)'], {}), '(19680801)\n', (58986, 58996), True, 'import numpy as np\n'), ((59006, 59024), 'numpy.random.randn', 'np.random.randn', (['N'], {}), '(N)\n', (59021, 59024), True, 'import numpy as np\n'), ((59054, 59068), 'numpy.roll', 'np.roll', (['x', '(20)'], {}), '(x, 20)\n', (59061, 59068), True, 'import numpy as np\n'), ((59167, 59214), 'matplotlib.mlab.cohere', 'mlab.cohere', (['x', 'y'], {'NFFT': '(256)', 'Fs': '(2)', 'noverlap': '(128)'}), '(x, y, NFFT=256, Fs=2, noverlap=128)\n', (59178, 59214), True, 'import matplotlib.mlab as mlab\n'), ((66412, 66443), 'numpy.array', 'np.array', (['[0, 1, 2, 3, 1, 2, 1]'], {}), '([0, 1, 2, 3, 1, 2, 1])\n', (66420, 66443), True, 'import numpy as np\n'), ((66526, 66686), 'matplotlib.mlab.psd', 'mlab.psd', (['u'], {'NFFT': 'u.size', 'Fs': '(1 / dt)', 'window': 'mlab.window_none', 'detrend': 'mlab.detrend_none', 'noverlap': '(0)', 'pad_to': 'None', 'scale_by_freq': 'None', 'sides': '"""onesided"""'}), "(u, NFFT=u.size, Fs=1 / dt, window=mlab.window_none, detrend=mlab.\n detrend_none, noverlap=0, pad_to=None, scale_by_freq=None, sides='onesided'\n )\n", (66534, 66686), True, 'import matplotlib.mlab as mlab\n'), ((66754, 66796), 'numpy.append', 'np.append', (['[Su[0]]', '(Su[1:4] + Su[4:][::-1])'], {}), '([Su[0]], Su[1:4] + Su[4:][::-1])\n', (66763, 66796), True, 'import numpy as np\n'), ((66802, 66842), 'numpy.testing.assert_allclose', 'assert_allclose', (['P', 'Su_1side'], {'atol': '(1e-06)'}), '(P, Su_1side, atol=1e-06)\n', (66817, 66842), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((66936, 66967), 'numpy.array', 'np.array', (['[0, 1, 2, 3, 1, 2, 1]'], {}), '([0, 1, 2, 3, 1, 2, 1])\n', (66944, 66967), True, 'import numpy as np\n'), ((67050, 67214), 'matplotlib.mlab.psd', 'mlab.psd', (['u'], {'NFFT': '(u.size * 2)', 'Fs': '(1 / dt)', 'window': 'mlab.window_none', 'detrend': 'mlab.detrend_none', 'noverlap': '(0)', 'pad_to': 'None', 'scale_by_freq': 'None', 'sides': '"""onesided"""'}), "(u, NFFT=u.size * 2, Fs=1 / dt, window=mlab.window_none, detrend=\n mlab.detrend_none, noverlap=0, pad_to=None, scale_by_freq=None, sides=\n 'onesided')\n", (67058, 67214), True, 'import matplotlib.mlab as mlab\n'), ((67280, 67322), 'numpy.append', 'np.append', (['[Su[0]]', '(Su[1:4] + Su[4:][::-1])'], {}), '([Su[0]], Su[1:4] + Su[4:][::-1])\n', (67289, 67322), True, 'import numpy as np\n'), ((337, 379), 'pytest.warns', 'pytest.warns', (['MatplotlibDeprecationWarning'], {}), '(MatplotlibDeprecationWarning)\n', (349, 379), False, 'import pytest\n'), ((397, 432), 'matplotlib.mlab.stride_repeat', 'mlab.stride_repeat', (['*args'], {}), '(*args, **kwargs)\n', (415, 432), True, 'import matplotlib.mlab as mlab\n'), ((965, 984), 'numpy.zeros', 'np.zeros', (['(NFFT, n)'], {}), '((NFFT, n))\n', (973, 984), True, 'import numpy as np\n'), ((1842, 1855), 'numpy.arange', 'np.arange', (['(10)'], {}), '(10)\n', (1851, 1855), True, 'import numpy as np\n'), ((2451, 2462), 'numpy.array', 'np.array', (['(0)'], {}), '(0)\n', (2459, 2462), True, 'import numpy as np\n'), ((2617, 2630), 'numpy.arange', 'np.arange', (['(10)'], {}), '(10)\n', (2626, 2630), True, 'import numpy as np\n'), ((2896, 2909), 'numpy.arange', 'np.arange', (['(10)'], {}), '(10)\n', (2905, 2909), True, 'import numpy as np\n'), ((3136, 3161), 'numpy.testing.assert_array_equal', 'assert_array_equal', (['yr', 'y'], {}), '(yr, y)\n', (3154, 3161), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((3639, 3653), 'numpy.arange', 'np.arange', (['(100)'], {}), '(100)\n', (3648, 3653), True, 'import numpy as np\n'), ((3667, 3722), 'matplotlib.mlab.stride_windows', 'mlab.stride_windows', (['x', 'n'], {'noverlap': 'noverlap', 'axis': 'axis'}), '(x, n, noverlap=noverlap, axis=axis)\n', (3686, 3722), True, 'import matplotlib.mlab as mlab\n'), ((3971, 3996), 'numpy.testing.assert_array_equal', 'assert_array_equal', (['yt', 'y'], {}), '(yt, y)\n', (3989, 3996), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((4290, 4309), 'numpy.tile', 'np.tile', (['x', '(21, 1)'], {}), '(x, (21, 1))\n', (4297, 4309), True, 'import numpy as np\n'), ((4350, 4387), 'matplotlib.mlab.stride_windows', 'mlab.stride_windows', (['x2', 'n'], {'axis': 'axis'}), '(x2, n, axis=axis)\n', (4369, 4387), True, 'import matplotlib.mlab as mlab\n'), ((4481, 4506), 'numpy.testing.assert_array_equal', 'assert_array_equal', (['y', 'x1'], {}), '(y, x1)\n', (4499, 4506), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((4587, 4610), 'numpy.full', 'np.full', (['(N + 20)', 'np.nan'], {}), '(N + 20, np.nan)\n', (4594, 4610), True, 'import numpy as np\n'), ((4727, 4769), 'matplotlib.mlab.stride_windows', 'mlab.stride_windows', (['y'], {'n': '(33)', 'noverlap': '(0.6)'}), '(y, n=33, noverlap=0.6)\n', (4746, 4769), True, 'import matplotlib.mlab as mlab\n'), ((4779, 4813), 'numpy.testing.assert_array_equal', 'assert_array_equal', (['y_strided', '(0.3)'], {}), '(y_strided, 0.3)\n', (4797, 4813), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((4887, 4929), 'matplotlib.mlab.stride_windows', 'mlab.stride_windows', (['y'], {'n': '(33.3)', 'noverlap': '(0)'}), '(y, n=33.3, noverlap=0)\n', (4906, 4929), True, 'import matplotlib.mlab as mlab\n'), ((4939, 4973), 'numpy.testing.assert_array_equal', 'assert_array_equal', (['y_strided', '(0.3)'], {}), '(y_strided, 0.3)\n', (4957, 4973), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((5189, 5223), 'numpy.testing.assert_array_equal', 'assert_array_equal', (['y_strided', '(0.3)'], {}), '(y_strided, 0.3)\n', (5207, 5223), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((5275, 5317), 'pytest.warns', 'pytest.warns', (['MatplotlibDeprecationWarning'], {}), '(MatplotlibDeprecationWarning)\n', (5287, 5317), False, 'import pytest\n'), ((5335, 5369), 'matplotlib.mlab.apply_window', 'mlab.apply_window', (['*args'], {}), '(*args, **kwargs)\n', (5352, 5369), True, 'import matplotlib.mlab as mlab\n'), ((5424, 5441), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (5438, 5441), True, 'import numpy as np\n'), ((5548, 5558), 'numpy.ones', 'np.ones', (['n'], {}), '(n)\n', (5555, 5558), True, 'import numpy as np\n'), ((5954, 5973), 'numpy.zeros', 'np.zeros', (['(NFFT, n)'], {}), '((NFFT, n))\n', (5962, 5973), True, 'import numpy as np\n'), ((5988, 6007), 'numpy.iterable', 'np.iterable', (['window'], {}), '(window)\n', (5999, 6007), True, 'import numpy as np\n'), ((6322, 6353), 'matplotlib.mlab.window_none', 'mlab.window_none', (['self.sig_ones'], {}), '(self.sig_ones)\n', (6338, 6353), True, 'import matplotlib.mlab as mlab\n'), ((6363, 6401), 'numpy.testing.assert_array_equal', 'assert_array_equal', (['res', 'self.sig_ones'], {}), '(res, self.sig_ones)\n', (6381, 6401), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((6457, 6488), 'matplotlib.mlab.window_none', 'mlab.window_none', (['self.sig_rand'], {}), '(self.sig_rand)\n', (6473, 6488), True, 'import matplotlib.mlab as mlab\n'), ((6498, 6536), 'numpy.testing.assert_array_equal', 'assert_array_equal', (['res', 'self.sig_rand'], {}), '(res, self.sig_rand)\n', (6516, 6536), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((6658, 6692), 'matplotlib.mlab.window_hanning', 'mlab.window_hanning', (['self.sig_rand'], {}), '(self.sig_rand)\n', (6677, 6692), True, 'import matplotlib.mlab as mlab\n'), ((6704, 6742), 'numpy.testing.assert_allclose', 'assert_allclose', (['targ', 'res'], {'atol': '(1e-06)'}), '(targ, res, atol=1e-06)\n', (6719, 6742), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((6848, 6882), 'matplotlib.mlab.window_hanning', 'mlab.window_hanning', (['self.sig_ones'], {}), '(self.sig_ones)\n', (6867, 6882), True, 'import matplotlib.mlab as mlab\n'), ((6894, 6932), 'numpy.testing.assert_allclose', 'assert_allclose', (['targ', 'res'], {'atol': '(1e-06)'}), '(targ, res, atol=1e-06)\n', (6909, 6932), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((7456, 7467), 'numpy.array', 'np.array', (['(0)'], {}), '(0)\n', (7464, 7467), True, 'import numpy as np\n'), ((8204, 8238), 'numpy.testing.assert_allclose', 'assert_allclose', (['yt', 'y'], {'atol': '(1e-06)'}), '(yt, y, atol=1e-06)\n', (8219, 8238), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((8248, 8284), 'numpy.testing.assert_array_equal', 'assert_array_equal', (['window1', 'window2'], {}), '(window1, window2)\n', (8266, 8284), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((8574, 8608), 'numpy.testing.assert_allclose', 'assert_allclose', (['yt', 'y'], {'atol': '(1e-06)'}), '(yt, y, atol=1e-06)\n', (8589, 8608), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((8963, 8997), 'numpy.testing.assert_allclose', 'assert_allclose', (['yt', 'y'], {'atol': '(1e-06)'}), '(yt, y, atol=1e-06)\n', (8978, 8997), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((9228, 9244), 'numpy.zeros_like', 'np.zeros_like', (['x'], {}), '(x)\n', (9241, 9244), True, 'import numpy as np\n'), ((9402, 9436), 'numpy.testing.assert_allclose', 'assert_allclose', (['yt', 'y'], {'atol': '(1e-06)'}), '(yt, y, atol=1e-06)\n', (9417, 9436), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((9732, 9748), 'numpy.zeros_like', 'np.zeros_like', (['x'], {}), '(x)\n', (9745, 9748), True, 'import numpy as np\n'), ((9907, 9941), 'numpy.testing.assert_allclose', 'assert_allclose', (['yt', 'y'], {'atol': '(1e-06)'}), '(yt, y, atol=1e-06)\n', (9922, 9941), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((10245, 10261), 'numpy.zeros_like', 'np.zeros_like', (['x'], {}), '(x)\n', (10258, 10261), True, 'import numpy as np\n'), ((10419, 10453), 'numpy.testing.assert_allclose', 'assert_allclose', (['yt', 'y'], {'atol': '(1e-06)'}), '(yt, y, atol=1e-06)\n', (10434, 10453), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((10463, 10499), 'numpy.testing.assert_array_equal', 'assert_array_equal', (['window1', 'window2'], {}), '(window1, window2)\n', (10481, 10499), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((10938, 10972), 'numpy.testing.assert_allclose', 'assert_allclose', (['yt', 'y'], {'atol': '(1e-06)'}), '(yt, y, atol=1e-06)\n', (10953, 10972), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((10982, 11018), 'numpy.testing.assert_array_equal', 'assert_array_equal', (['window1', 'window2'], {}), '(window1, window2)\n', (11000, 11018), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((11249, 11265), 'numpy.zeros_like', 'np.zeros_like', (['x'], {}), '(x)\n', (11262, 11265), True, 'import numpy as np\n'), ((11423, 11457), 'numpy.testing.assert_allclose', 'assert_allclose', (['yt', 'y'], {'atol': '(1e-06)'}), '(yt, y, atol=1e-06)\n', (11438, 11457), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((11753, 11769), 'numpy.zeros_like', 'np.zeros_like', (['x'], {}), '(x)\n', (11766, 11769), True, 'import numpy as np\n'), ((11928, 11962), 'numpy.testing.assert_allclose', 'assert_allclose', (['yt', 'y'], {'atol': '(1e-06)'}), '(yt, y, atol=1e-06)\n', (11943, 11962), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((12266, 12282), 'numpy.zeros_like', 'np.zeros_like', (['x'], {}), '(x)\n', (12279, 12282), True, 'import numpy as np\n'), ((12442, 12476), 'numpy.testing.assert_allclose', 'assert_allclose', (['yt', 'y'], {'atol': '(1e-06)'}), '(yt, y, atol=1e-06)\n', (12457, 12476), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((12486, 12522), 'numpy.testing.assert_array_equal', 'assert_array_equal', (['window1', 'window2'], {}), '(window1, window2)\n', (12504, 12522), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((12953, 12987), 'numpy.testing.assert_allclose', 'assert_allclose', (['yt', 'y'], {'atol': '(1e-06)'}), '(yt, y, atol=1e-06)\n', (12968, 12987), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((13150, 13198), 'matplotlib.mlab.stride_windows', 'mlab.stride_windows', (['x'], {'n': '(13)', 'noverlap': '(2)', 'axis': '(0)'}), '(x, n=13, noverlap=2, axis=0)\n', (13169, 13198), True, 'import matplotlib.mlab as mlab\n'), ((13410, 13444), 'numpy.testing.assert_allclose', 'assert_allclose', (['yt', 'y'], {'atol': '(1e-06)'}), '(yt, y, atol=1e-06)\n', (13425, 13444), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((13521, 13534), 'numpy.arange', 'np.arange', (['(32)'], {}), '(32)\n', (13530, 13534), True, 'import numpy as np\n'), ((13674, 13701), 'matplotlib.mlab.window_hanning', 'mlab.window_hanning', (['ydata2'], {}), '(ydata2)\n', (13693, 13701), True, 'import matplotlib.mlab as mlab\n'), ((13719, 13746), 'numpy.vstack', 'np.vstack', (['[ydata1, ydata2]'], {}), '([ydata1, ydata2])\n', (13728, 13746), True, 'import numpy as np\n'), ((13767, 13800), 'numpy.vstack', 'np.vstack', (['[ycontrol1, ycontrol2]'], {}), '([ycontrol1, ycontrol2])\n', (13776, 13800), True, 'import numpy as np\n'), ((13818, 13841), 'numpy.tile', 'np.tile', (['ydata', '(20, 1)'], {}), '(ydata, (20, 1))\n', (13825, 13841), True, 'import numpy as np\n'), ((13862, 13888), 'numpy.tile', 'np.tile', (['ycontrol', '(20, 1)'], {}), '(ycontrol, (20, 1))\n', (13869, 13888), True, 'import numpy as np\n'), ((14019, 14064), 'numpy.testing.assert_allclose', 'assert_allclose', (['ycontrol', 'result'], {'atol': '(1e-08)'}), '(ycontrol, result, atol=1e-08)\n', (14034, 14064), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((14149, 14162), 'numpy.arange', 'np.arange', (['(32)'], {}), '(32)\n', (14158, 14162), True, 'import numpy as np\n'), ((14302, 14329), 'matplotlib.mlab.window_hanning', 'mlab.window_hanning', (['ydata2'], {}), '(ydata2)\n', (14321, 14329), True, 'import matplotlib.mlab as mlab\n'), ((14347, 14374), 'numpy.vstack', 'np.vstack', (['[ydata1, ydata2]'], {}), '([ydata1, ydata2])\n', (14356, 14374), True, 'import numpy as np\n'), ((14395, 14428), 'numpy.vstack', 'np.vstack', (['[ycontrol1, ycontrol2]'], {}), '([ycontrol1, ycontrol2])\n', (14404, 14428), True, 'import numpy as np\n'), ((14446, 14469), 'numpy.tile', 'np.tile', (['ydata', '(20, 1)'], {}), '(ydata, (20, 1))\n', (14453, 14469), True, 'import numpy as np\n'), ((14490, 14516), 'numpy.tile', 'np.tile', (['ycontrol', '(20, 1)'], {}), '(ycontrol, (20, 1))\n', (14497, 14516), True, 'import numpy as np\n'), ((14647, 14692), 'numpy.testing.assert_allclose', 'assert_allclose', (['ycontrol', 'result'], {'atol': '(1e-08)'}), '(ycontrol, result, atol=1e-08)\n', (14662, 14692), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((14803, 14815), 'numpy.arange', 'np.arange', (['n'], {}), '(n)\n', (14812, 14815), True, 'import numpy as np\n'), ((14955, 14982), 'matplotlib.mlab.window_hanning', 'mlab.window_hanning', (['ydata2'], {}), '(ydata2)\n', (14974, 14982), True, 'import matplotlib.mlab as mlab\n'), ((15000, 15027), 'numpy.vstack', 'np.vstack', (['[ydata1, ydata2]'], {}), '([ydata1, ydata2])\n', (15009, 15027), True, 'import numpy as np\n'), ((15048, 15081), 'numpy.vstack', 'np.vstack', (['[ycontrol1, ycontrol2]'], {}), '([ycontrol1, ycontrol2])\n', (15057, 15081), True, 'import numpy as np\n'), ((15099, 15122), 'numpy.tile', 'np.tile', (['ydata', '(20, 1)'], {}), '(ydata, (20, 1))\n', (15106, 15122), True, 'import numpy as np\n'), ((15143, 15169), 'numpy.tile', 'np.tile', (['ycontrol', '(20, 1)'], {}), '(ycontrol, (20, 1))\n', (15150, 15169), True, 'import numpy as np\n'), ((15221, 15271), 'matplotlib.mlab.stride_windows', 'mlab.stride_windows', (['ydata', '(32)'], {'noverlap': '(0)', 'axis': '(0)'}), '(ydata, 32, noverlap=0, axis=0)\n', (15240, 15271), True, 'import matplotlib.mlab as mlab\n'), ((15403, 15450), 'numpy.testing.assert_allclose', 'assert_allclose', (['ycontrol.T', 'result'], {'atol': '(1e-08)'}), '(ycontrol.T, result, atol=1e-08)\n', (15418, 15450), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((15506, 15523), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (15520, 15523), True, 'import numpy as np\n'), ((15555, 15579), 'numpy.linspace', 'np.linspace', (['(0.0)', '(100)', 'n'], {}), '(0.0, 100, n)\n', (15566, 15579), True, 'import numpy as np\n'), ((15607, 15618), 'numpy.zeros', 'np.zeros', (['n'], {}), '(n)\n', (15615, 15618), True, 'import numpy as np\n'), ((15693, 15720), 'numpy.linspace', 'np.linspace', (['(-10.0)', '(90.0)', 'n'], {}), '(-10.0, 90.0, n)\n', (15704, 15720), True, 'import numpy as np\n'), ((15787, 15815), 'numpy.random.standard_normal', 'np.random.standard_normal', (['n'], {}), '(n)\n', (15812, 15815), True, 'import numpy as np\n'), ((15835, 15868), 'numpy.sin', 'np.sin', (['(x * 2 * np.pi / (n / 100))'], {}), '(x * 2 * np.pi / (n / 100))\n', (15841, 15868), True, 'import numpy as np\n'), ((16106, 16130), 'matplotlib.mlab.detrend_none', 'mlab.detrend_none', (['input'], {}), '(input)\n', (16123, 16130), True, 'import matplotlib.mlab as mlab\n'), ((16263, 16295), 'matplotlib.mlab.detrend_none', 'mlab.detrend_none', (['input'], {'axis': '(1)'}), '(input, axis=1)\n', (16280, 16295), True, 'import matplotlib.mlab as mlab\n'), ((16426, 16457), 'matplotlib.mlab.detrend', 'mlab.detrend', (['input'], {'key': '"""none"""'}), "(input, key='none')\n", (16438, 16457), True, 'import matplotlib.mlab as mlab\n'), ((16592, 16634), 'matplotlib.mlab.detrend', 'mlab.detrend', (['input'], {'key': 'mlab.detrend_none'}), '(input, key=mlab.detrend_none)\n', (16604, 16634), True, 'import matplotlib.mlab as mlab\n'), ((16760, 16784), 'matplotlib.mlab.detrend_none', 'mlab.detrend_none', (['input'], {}), '(input)\n', (16777, 16784), True, 'import matplotlib.mlab as mlab\n'), ((16925, 16949), 'matplotlib.mlab.detrend_none', 'mlab.detrend_none', (['input'], {}), '(input)\n', (16942, 16949), True, 'import matplotlib.mlab as mlab\n'), ((16959, 16988), 'numpy.testing.assert_array_equal', 'assert_array_equal', (['res', 'targ'], {}), '(res, targ)\n', (16977, 16988), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((17103, 17127), 'matplotlib.mlab.detrend_none', 'mlab.detrend_none', (['input'], {}), '(input)\n', (17120, 17127), True, 'import matplotlib.mlab as mlab\n'), ((17137, 17166), 'numpy.testing.assert_array_equal', 'assert_array_equal', (['res', 'targ'], {}), '(res, targ)\n', (17155, 17166), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((17279, 17303), 'matplotlib.mlab.detrend_none', 'mlab.detrend_none', (['input'], {}), '(input)\n', (17296, 17303), True, 'import matplotlib.mlab as mlab\n'), ((17313, 17342), 'numpy.testing.assert_array_equal', 'assert_array_equal', (['res', 'targ'], {}), '(res, targ)\n', (17331, 17342), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((17821, 17836), 'numpy.vstack', 'np.vstack', (['arri'], {}), '(arri)\n', (17830, 17836), True, 'import numpy as np\n'), ((17874, 17898), 'matplotlib.mlab.detrend_none', 'mlab.detrend_none', (['input'], {}), '(input)\n', (17891, 17898), True, 'import matplotlib.mlab as mlab\n'), ((17908, 17937), 'numpy.testing.assert_array_equal', 'assert_array_equal', (['res', 'targ'], {}), '(res, targ)\n', (17926, 17937), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((18188, 18203), 'numpy.vstack', 'np.vstack', (['arri'], {}), '(arri)\n', (18197, 18203), True, 'import numpy as np\n'), ((18241, 18267), 'matplotlib.mlab.detrend_none', 'mlab.detrend_none', (['input.T'], {}), '(input.T)\n', (18258, 18267), True, 'import matplotlib.mlab as mlab\n'), ((18277, 18308), 'numpy.testing.assert_array_equal', 'assert_array_equal', (['res.T', 'targ'], {}), '(res.T, targ)\n', (18295, 18308), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((18408, 18432), 'matplotlib.mlab.detrend_mean', 'mlab.detrend_mean', (['input'], {}), '(input)\n', (18425, 18432), True, 'import matplotlib.mlab as mlab\n'), ((18442, 18472), 'numpy.testing.assert_almost_equal', 'assert_almost_equal', (['res', 'targ'], {}), '(res, targ)\n', (18461, 18472), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((18576, 18607), 'matplotlib.mlab.detrend', 'mlab.detrend', (['input'], {'key': '"""mean"""'}), "(input, key='mean')\n", (18588, 18607), True, 'import matplotlib.mlab as mlab\n'), ((18617, 18647), 'numpy.testing.assert_almost_equal', 'assert_almost_equal', (['res', 'targ'], {}), '(res, targ)\n', (18636, 18647), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((18755, 18797), 'matplotlib.mlab.detrend', 'mlab.detrend', (['input'], {'key': 'mlab.detrend_mean'}), '(input, key=mlab.detrend_mean)\n', (18767, 18797), True, 'import matplotlib.mlab as mlab\n'), ((18807, 18837), 'numpy.testing.assert_almost_equal', 'assert_almost_equal', (['res', 'targ'], {}), '(res, targ)\n', (18826, 18837), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((18936, 18960), 'matplotlib.mlab.detrend_mean', 'mlab.detrend_mean', (['input'], {}), '(input)\n', (18953, 18960), True, 'import matplotlib.mlab as mlab\n'), ((18970, 19000), 'numpy.testing.assert_almost_equal', 'assert_almost_equal', (['res', 'targ'], {}), '(res, targ)\n', (18989, 19000), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((19103, 19134), 'matplotlib.mlab.detrend', 'mlab.detrend', (['input'], {'key': '"""mean"""'}), "(input, key='mean')\n", (19115, 19134), True, 'import matplotlib.mlab as mlab\n'), ((19144, 19174), 'numpy.testing.assert_almost_equal', 'assert_almost_equal', (['res', 'targ'], {}), '(res, targ)\n', (19163, 19174), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((19281, 19323), 'matplotlib.mlab.detrend', 'mlab.detrend', (['input'], {'key': 'mlab.detrend_mean'}), '(input, key=mlab.detrend_mean)\n', (19293, 19323), True, 'import matplotlib.mlab as mlab\n'), ((19333, 19363), 'numpy.testing.assert_almost_equal', 'assert_almost_equal', (['res', 'targ'], {}), '(res, targ)\n', (19352, 19363), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((19487, 19511), 'matplotlib.mlab.detrend_mean', 'mlab.detrend_mean', (['input'], {}), '(input)\n', (19504, 19511), True, 'import matplotlib.mlab as mlab\n'), ((19521, 19563), 'numpy.testing.assert_allclose', 'assert_allclose', (['res', 'targ'], {'atol': 'self.atol'}), '(res, targ, atol=self.atol)\n', (19536, 19563), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((19684, 19708), 'matplotlib.mlab.detrend_mean', 'mlab.detrend_mean', (['input'], {}), '(input)\n', (19701, 19708), True, 'import matplotlib.mlab as mlab\n'), ((19718, 19760), 'numpy.testing.assert_allclose', 'assert_allclose', (['res', 'targ'], {'atol': 'self.atol'}), '(res, targ, atol=self.atol)\n', (19733, 19760), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((19900, 19924), 'matplotlib.mlab.detrend_mean', 'mlab.detrend_mean', (['input'], {}), '(input)\n', (19917, 19924), True, 'import matplotlib.mlab as mlab\n'), ((19934, 19976), 'numpy.testing.assert_allclose', 'assert_allclose', (['res', 'targ'], {'atol': 'self.atol'}), '(res, targ, atol=self.atol)\n', (19949, 19976), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((20142, 20166), 'matplotlib.mlab.detrend_mean', 'mlab.detrend_mean', (['input'], {}), '(input)\n', (20159, 20166), True, 'import matplotlib.mlab as mlab\n'), ((20176, 20218), 'numpy.testing.assert_allclose', 'assert_allclose', (['res', 'targ'], {'atol': 'self.atol'}), '(res, targ, atol=self.atol)\n', (20191, 20218), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((20403, 20427), 'matplotlib.mlab.detrend_mean', 'mlab.detrend_mean', (['input'], {}), '(input)\n', (20420, 20427), True, 'import matplotlib.mlab as mlab\n'), ((20437, 20475), 'numpy.testing.assert_allclose', 'assert_allclose', (['res', 'targ'], {'atol': '(1e-08)'}), '(res, targ, atol=1e-08)\n', (20452, 20475), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((20666, 20698), 'matplotlib.mlab.detrend_mean', 'mlab.detrend_mean', (['input'], {'axis': '(0)'}), '(input, axis=0)\n', (20683, 20698), True, 'import matplotlib.mlab as mlab\n'), ((20708, 20746), 'numpy.testing.assert_allclose', 'assert_allclose', (['res', 'targ'], {'atol': '(1e-08)'}), '(res, targ, atol=1e-08)\n', (20723, 20746), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((20979, 21017), 'numpy.testing.assert_allclose', 'assert_allclose', (['res', 'targ'], {'atol': '(1e-08)'}), '(res, targ, atol=1e-08)\n', (20994, 21017), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((21264, 21302), 'numpy.testing.assert_allclose', 'assert_allclose', (['res', 'targ'], {'atol': '(1e-08)'}), '(res, targ, atol=1e-08)\n', (21279, 21302), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((21510, 21525), 'numpy.vstack', 'np.vstack', (['arri'], {}), '(arri)\n', (21519, 21525), True, 'import numpy as np\n'), ((21542, 21557), 'numpy.vstack', 'np.vstack', (['arrt'], {}), '(arrt)\n', (21551, 21557), True, 'import numpy as np\n'), ((21573, 21597), 'matplotlib.mlab.detrend_mean', 'mlab.detrend_mean', (['input'], {}), '(input)\n', (21590, 21597), True, 'import matplotlib.mlab as mlab\n'), ((21607, 21645), 'numpy.testing.assert_allclose', 'assert_allclose', (['res', 'targ'], {'atol': '(1e-08)'}), '(res, targ, atol=1e-08)\n', (21622, 21645), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((21850, 21865), 'numpy.vstack', 'np.vstack', (['arri'], {}), '(arri)\n', (21859, 21865), True, 'import numpy as np\n'), ((21882, 21897), 'numpy.vstack', 'np.vstack', (['arrt'], {}), '(arrt)\n', (21891, 21897), True, 'import numpy as np\n'), ((21913, 21948), 'matplotlib.mlab.detrend_mean', 'mlab.detrend_mean', (['input'], {'axis': 'None'}), '(input, axis=None)\n', (21930, 21948), True, 'import matplotlib.mlab as mlab\n'), ((21958, 21996), 'numpy.testing.assert_allclose', 'assert_allclose', (['res', 'targ'], {'atol': '(1e-08)'}), '(res, targ, atol=1e-08)\n', (21973, 21996), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((22262, 22277), 'numpy.vstack', 'np.vstack', (['arrt'], {}), '(arrt)\n', (22271, 22277), True, 'import numpy as np\n'), ((22293, 22328), 'matplotlib.mlab.detrend_mean', 'mlab.detrend_mean', (['input'], {'axis': 'None'}), '(input, axis=None)\n', (22310, 22328), True, 'import matplotlib.mlab as mlab\n'), ((22338, 22378), 'numpy.testing.assert_allclose', 'assert_allclose', (['res.T', 'targ'], {'atol': '(1e-08)'}), '(res.T, targ, atol=1e-08)\n', (22353, 22378), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((22897, 22929), 'matplotlib.mlab.detrend_mean', 'mlab.detrend_mean', (['input'], {'axis': '(0)'}), '(input, axis=0)\n', (22914, 22929), True, 'import matplotlib.mlab as mlab\n'), ((22939, 22977), 'numpy.testing.assert_allclose', 'assert_allclose', (['res', 'targ'], {'atol': '(1e-08)'}), '(res, targ, atol=1e-08)\n', (22954, 22977), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((23429, 23444), 'numpy.vstack', 'np.vstack', (['arri'], {}), '(arri)\n', (23438, 23444), True, 'import numpy as np\n'), ((23461, 23476), 'numpy.vstack', 'np.vstack', (['arrt'], {}), '(arrt)\n', (23470, 23476), True, 'import numpy as np\n'), ((23492, 23524), 'matplotlib.mlab.detrend_mean', 'mlab.detrend_mean', (['input'], {'axis': '(1)'}), '(input, axis=1)\n', (23509, 23524), True, 'import matplotlib.mlab as mlab\n'), ((23534, 23572), 'numpy.testing.assert_allclose', 'assert_allclose', (['res', 'targ'], {'atol': '(1e-08)'}), '(res, targ, atol=1e-08)\n', (23549, 23572), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((24025, 24040), 'numpy.vstack', 'np.vstack', (['arri'], {}), '(arri)\n', (24034, 24040), True, 'import numpy as np\n'), ((24057, 24072), 'numpy.vstack', 'np.vstack', (['arrt'], {}), '(arrt)\n', (24066, 24072), True, 'import numpy as np\n'), ((24088, 24121), 'matplotlib.mlab.detrend_mean', 'mlab.detrend_mean', (['input'], {'axis': '(-1)'}), '(input, axis=-1)\n', (24105, 24121), True, 'import matplotlib.mlab as mlab\n'), ((24131, 24169), 'numpy.testing.assert_allclose', 'assert_allclose', (['res', 'targ'], {'atol': '(1e-08)'}), '(res, targ, atol=1e-08)\n', (24146, 24169), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((24397, 24412), 'numpy.vstack', 'np.vstack', (['arri'], {}), '(arri)\n', (24406, 24412), True, 'import numpy as np\n'), ((24429, 24444), 'numpy.vstack', 'np.vstack', (['arrt'], {}), '(arrt)\n', (24438, 24444), True, 'import numpy as np\n'), ((24460, 24479), 'matplotlib.mlab.detrend', 'mlab.detrend', (['input'], {}), '(input)\n', (24472, 24479), True, 'import matplotlib.mlab as mlab\n'), ((24489, 24527), 'numpy.testing.assert_allclose', 'assert_allclose', (['res', 'targ'], {'atol': '(1e-08)'}), '(res, targ, atol=1e-08)\n', (24504, 24527), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((24727, 24742), 'numpy.vstack', 'np.vstack', (['arri'], {}), '(arri)\n', (24736, 24742), True, 'import numpy as np\n'), ((24759, 24774), 'numpy.vstack', 'np.vstack', (['arrt'], {}), '(arrt)\n', (24768, 24774), True, 'import numpy as np\n'), ((24790, 24820), 'matplotlib.mlab.detrend', 'mlab.detrend', (['input'], {'axis': 'None'}), '(input, axis=None)\n', (24802, 24820), True, 'import matplotlib.mlab as mlab\n'), ((24830, 24868), 'numpy.testing.assert_allclose', 'assert_allclose', (['res', 'targ'], {'atol': '(1e-08)'}), '(res, targ, atol=1e-08)\n', (24845, 24868), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((25366, 25405), 'matplotlib.mlab.detrend', 'mlab.detrend', (['input'], {'key': '"""mean"""', 'axis': '(0)'}), "(input, key='mean', axis=0)\n", (25378, 25405), True, 'import matplotlib.mlab as mlab\n'), ((25415, 25453), 'numpy.testing.assert_allclose', 'assert_allclose', (['res', 'targ'], {'atol': '(1e-08)'}), '(res, targ, atol=1e-08)\n', (25430, 25453), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((25727, 25742), 'numpy.vstack', 'np.vstack', (['arrt'], {}), '(arrt)\n', (25736, 25742), True, 'import numpy as np\n'), ((25758, 25804), 'matplotlib.mlab.detrend', 'mlab.detrend', (['input'], {'key': '"""constant"""', 'axis': 'None'}), "(input, key='constant', axis=None)\n", (25770, 25804), True, 'import matplotlib.mlab as mlab\n'), ((25814, 25854), 'numpy.testing.assert_allclose', 'assert_allclose', (['res.T', 'targ'], {'atol': '(1e-08)'}), '(res.T, targ, atol=1e-08)\n', (25829, 25854), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((26313, 26328), 'numpy.vstack', 'np.vstack', (['arri'], {}), '(arri)\n', (26322, 26328), True, 'import numpy as np\n'), ((26345, 26360), 'numpy.vstack', 'np.vstack', (['arrt'], {}), '(arrt)\n', (26354, 26360), True, 'import numpy as np\n'), ((26376, 26418), 'matplotlib.mlab.detrend', 'mlab.detrend', (['input'], {'key': '"""default"""', 'axis': '(1)'}), "(input, key='default', axis=1)\n", (26388, 26418), True, 'import matplotlib.mlab as mlab\n'), ((26428, 26466), 'numpy.testing.assert_allclose', 'assert_allclose', (['res', 'targ'], {'atol': '(1e-08)'}), '(res, targ, atol=1e-08)\n', (26443, 26466), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((26993, 27043), 'matplotlib.mlab.detrend', 'mlab.detrend', (['input'], {'key': 'mlab.detrend_mean', 'axis': '(0)'}), '(input, key=mlab.detrend_mean, axis=0)\n', (27005, 27043), True, 'import matplotlib.mlab as mlab\n'), ((27053, 27091), 'numpy.testing.assert_allclose', 'assert_allclose', (['res', 'targ'], {'atol': '(1e-08)'}), '(res, targ, atol=1e-08)\n', (27068, 27091), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((28585, 28611), 'matplotlib.mlab.detrend_linear', 'mlab.detrend_linear', (['input'], {}), '(input)\n', (28604, 28611), True, 'import matplotlib.mlab as mlab\n'), ((28621, 28651), 'numpy.testing.assert_almost_equal', 'assert_almost_equal', (['res', 'targ'], {}), '(res, targ)\n', (28640, 28651), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((28752, 28778), 'matplotlib.mlab.detrend_linear', 'mlab.detrend_linear', (['input'], {}), '(input)\n', (28771, 28778), True, 'import matplotlib.mlab as mlab\n'), ((28788, 28818), 'numpy.testing.assert_almost_equal', 'assert_almost_equal', (['res', 'targ'], {}), '(res, targ)\n', (28807, 28818), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((28923, 28956), 'matplotlib.mlab.detrend', 'mlab.detrend', (['input'], {'key': '"""linear"""'}), "(input, key='linear')\n", (28935, 28956), True, 'import matplotlib.mlab as mlab\n'), ((28966, 28996), 'numpy.testing.assert_almost_equal', 'assert_almost_equal', (['res', 'targ'], {}), '(res, targ)\n', (28985, 28996), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((29105, 29149), 'matplotlib.mlab.detrend', 'mlab.detrend', (['input'], {'key': 'mlab.detrend_linear'}), '(input, key=mlab.detrend_linear)\n', (29117, 29149), True, 'import matplotlib.mlab as mlab\n'), ((29159, 29189), 'numpy.testing.assert_almost_equal', 'assert_almost_equal', (['res', 'targ'], {}), '(res, targ)\n', (29178, 29189), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((29311, 29337), 'matplotlib.mlab.detrend_linear', 'mlab.detrend_linear', (['input'], {}), '(input)\n', (29330, 29337), True, 'import matplotlib.mlab as mlab\n'), ((29347, 29389), 'numpy.testing.assert_allclose', 'assert_allclose', (['res', 'targ'], {'atol': 'self.atol'}), '(res, targ, atol=self.atol)\n', (29362, 29389), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((29515, 29541), 'matplotlib.mlab.detrend_linear', 'mlab.detrend_linear', (['input'], {}), '(input)\n', (29534, 29541), True, 'import matplotlib.mlab as mlab\n'), ((29551, 29593), 'numpy.testing.assert_allclose', 'assert_allclose', (['res', 'targ'], {'atol': 'self.atol'}), '(res, targ, atol=self.atol)\n', (29566, 29593), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((29738, 29764), 'matplotlib.mlab.detrend_linear', 'mlab.detrend_linear', (['input'], {}), '(input)\n', (29757, 29764), True, 'import matplotlib.mlab as mlab\n'), ((29774, 29816), 'numpy.testing.assert_allclose', 'assert_allclose', (['res', 'targ'], {'atol': 'self.atol'}), '(res, targ, atol=self.atol)\n', (29789, 29816), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((29965, 29998), 'matplotlib.mlab.detrend', 'mlab.detrend', (['input'], {'key': '"""linear"""'}), "(input, key='linear')\n", (29977, 29998), True, 'import matplotlib.mlab as mlab\n'), ((30008, 30050), 'numpy.testing.assert_allclose', 'assert_allclose', (['res', 'targ'], {'atol': 'self.atol'}), '(res, targ, atol=self.atol)\n', (30023, 30050), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((30203, 30247), 'matplotlib.mlab.detrend', 'mlab.detrend', (['input'], {'key': 'mlab.detrend_linear'}), '(input, key=mlab.detrend_linear)\n', (30215, 30247), True, 'import matplotlib.mlab as mlab\n'), ((30257, 30299), 'numpy.testing.assert_allclose', 'assert_allclose', (['res', 'targ'], {'atol': 'self.atol'}), '(res, targ, atol=self.atol)\n', (30272, 30299), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((30494, 30536), 'numpy.testing.assert_allclose', 'assert_allclose', (['res', 'targ'], {'atol': 'self.atol'}), '(res, targ, atol=self.atol)\n', (30509, 30536), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((31070, 31111), 'matplotlib.mlab.detrend', 'mlab.detrend', (['input'], {'key': '"""linear"""', 'axis': '(0)'}), "(input, key='linear', axis=0)\n", (31082, 31111), True, 'import matplotlib.mlab as mlab\n'), ((31121, 31163), 'numpy.testing.assert_allclose', 'assert_allclose', (['res', 'targ'], {'atol': 'self.atol'}), '(res, targ, atol=self.atol)\n', (31136, 31163), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((31524, 31576), 'matplotlib.mlab.detrend', 'mlab.detrend', (['input'], {'key': 'mlab.detrend_linear', 'axis': '(0)'}), '(input, key=mlab.detrend_linear, axis=0)\n', (31536, 31576), True, 'import matplotlib.mlab as mlab\n'), ((31586, 31628), 'numpy.testing.assert_allclose', 'assert_allclose', (['res', 'targ'], {'atol': 'self.atol'}), '(res, targ, atol=self.atol)\n', (31601, 31628), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((31930, 31945), 'numpy.vstack', 'np.vstack', (['arri'], {}), '(arri)\n', (31939, 31945), True, 'import numpy as np\n'), ((31962, 31977), 'numpy.vstack', 'np.vstack', (['arrt'], {}), '(arrt)\n', (31971, 31977), True, 'import numpy as np\n'), ((31993, 32034), 'matplotlib.mlab.detrend', 'mlab.detrend', (['input'], {'key': '"""linear"""', 'axis': '(1)'}), "(input, key='linear', axis=1)\n", (32005, 32034), True, 'import matplotlib.mlab as mlab\n'), ((32044, 32086), 'numpy.testing.assert_allclose', 'assert_allclose', (['res', 'targ'], {'atol': 'self.atol'}), '(res, targ, atol=self.atol)\n', (32059, 32086), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((32392, 32407), 'numpy.vstack', 'np.vstack', (['arri'], {}), '(arri)\n', (32401, 32407), True, 'import numpy as np\n'), ((32424, 32439), 'numpy.vstack', 'np.vstack', (['arrt'], {}), '(arrt)\n', (32433, 32439), True, 'import numpy as np\n'), ((32455, 32507), 'matplotlib.mlab.detrend', 'mlab.detrend', (['input'], {'key': 'mlab.detrend_linear', 'axis': '(1)'}), '(input, key=mlab.detrend_linear, axis=1)\n', (32467, 32507), True, 'import matplotlib.mlab as mlab\n'), ((32517, 32559), 'numpy.testing.assert_allclose', 'assert_allclose', (['res', 'targ'], {'atol': 'self.atol'}), '(res, targ, atol=self.atol)\n', (32532, 32559), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((33896, 33920), 'numpy.arange', 'np.arange', (['(0)', '(10)', '(1 / Fs)'], {}), '(0, 10, 1 / Fs)\n', (33905, 33920), True, 'import numpy as np\n'), ((38362, 38403), 'numpy.array', 'np.array', (['[NFFT_spectrum_real / (2 * Fs)]'], {}), '([NFFT_spectrum_real / (2 * Fs)])\n', (38370, 38403), True, 'import numpy as np\n'), ((38451, 38467), 'numpy.zeros_like', 'np.zeros_like', (['x'], {}), '(x)\n', (38464, 38467), True, 'import numpy as np\n'), ((39844, 39892), 'numpy.testing.assert_allclose', 'assert_allclose', (['resfreqs', 'targfreqs'], {'atol': '(1e-06)'}), '(resfreqs, targfreqs, atol=1e-06)\n', (39859, 39892), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((42548, 42587), 'numpy.testing.assert_allclose', 'assert_allclose', (['fsp', 'freqs'], {'atol': '(1e-06)'}), '(fsp, freqs, atol=1e-06)\n', (42563, 42587), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((42857, 43004), 'matplotlib.mlab.csd', 'mlab.csd', ([], {'x': 'self.y', 'y': '(self.y + 1)', 'NFFT': 'self.NFFT_density', 'Fs': 'self.Fs', 'noverlap': 'self.nover_density', 'pad_to': 'self.pad_to_density', 'sides': 'self.sides'}), '(x=self.y, y=self.y + 1, NFFT=self.NFFT_density, Fs=self.Fs,\n noverlap=self.nover_density, pad_to=self.pad_to_density, sides=self.sides)\n', (42865, 43004), True, 'import matplotlib.mlab as mlab\n'), ((43158, 43197), 'numpy.testing.assert_allclose', 'assert_allclose', (['fsp', 'freqs'], {'atol': '(1e-06)'}), '(fsp, freqs, atol=1e-06)\n', (43173, 43197), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((43543, 43584), 'matplotlib.mlab.csd', 'mlab.csd', ([], {'NFFT': 'self.NFFT_density'}), '(NFFT=self.NFFT_density, **sargs)\n', (43551, 43584), True, 'import matplotlib.mlab as mlab\n'), ((43605, 43650), 'matplotlib.mlab.csd', 'mlab.csd', ([], {'NFFT': '(self.NFFT_density * 2)'}), '(NFFT=self.NFFT_density * 2, **sargs)\n', (43613, 43650), True, 'import matplotlib.mlab as mlab\n'), ((43875, 44009), 'matplotlib.mlab.psd', 'mlab.psd', ([], {'x': 'self.y', 'NFFT': 'self.NFFT_density', 'Fs': 'self.Fs', 'noverlap': 'self.nover_density', 'pad_to': 'self.pad_to_density', 'sides': 'self.sides'}), '(x=self.y, NFFT=self.NFFT_density, Fs=self.Fs, noverlap=self.\n nover_density, pad_to=self.pad_to_density, sides=self.sides)\n', (43883, 44009), True, 'import matplotlib.mlab as mlab\n'), ((44676, 44703), 'numpy.vstack', 'np.vstack', (['[ydata1, ydata2]'], {}), '([ydata1, ydata2])\n', (44685, 44703), True, 'import numpy as np\n'), ((44721, 44744), 'numpy.tile', 'np.tile', (['ydata', '(20, 1)'], {}), '(ydata, (20, 1))\n', (44728, 44744), True, 'import numpy as np\n'), ((44834, 44854), 'numpy.zeros_like', 'np.zeros_like', (['ydata'], {}), '(ydata)\n', (44847, 44854), True, 'import numpy as np\n'), ((44880, 44985), 'matplotlib.mlab.psd', 'mlab.psd', ([], {'x': 'ydata', 'NFFT': 'self.NFFT_density', 'Fs': 'self.Fs', 'noverlap': '(0)', 'sides': 'self.sides', 'detrend': 'detrend'}), '(x=ydata, NFFT=self.NFFT_density, Fs=self.Fs, noverlap=0, sides=\n self.sides, detrend=detrend)\n', (44888, 44985), True, 'import matplotlib.mlab as mlab\n'), ((45176, 45282), 'matplotlib.mlab.psd', 'mlab.psd', ([], {'x': 'ydatab', 'NFFT': 'self.NFFT_density', 'Fs': 'self.Fs', 'noverlap': '(0)', 'sides': 'self.sides', 'detrend': 'detrend'}), '(x=ydatab, NFFT=self.NFFT_density, Fs=self.Fs, noverlap=0, sides=\n self.sides, detrend=detrend)\n', (45184, 45282), True, 'import matplotlib.mlab as mlab\n'), ((45473, 45564), 'matplotlib.mlab.psd', 'mlab.psd', ([], {'x': 'ycontrol', 'NFFT': 'self.NFFT_density', 'Fs': 'self.Fs', 'noverlap': '(0)', 'sides': 'self.sides'}), '(x=ycontrol, NFFT=self.NFFT_density, Fs=self.Fs, noverlap=0, sides=\n self.sides)\n', (45481, 45564), True, 'import matplotlib.mlab as mlab\n'), ((45705, 45737), 'numpy.testing.assert_array_equal', 'assert_array_equal', (['fsp_g', 'fsp_c'], {}), '(fsp_g, fsp_c)\n', (45723, 45737), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((45747, 45779), 'numpy.testing.assert_array_equal', 'assert_array_equal', (['fsp_b', 'fsp_c'], {}), '(fsp_b, fsp_c)\n', (45765, 45779), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((45789, 45832), 'numpy.testing.assert_allclose', 'assert_allclose', (['spec_g', 'spec_c'], {'atol': '(1e-08)'}), '(spec_g, spec_c, atol=1e-08)\n', (45804, 45832), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((46097, 46125), 'numpy.arange', 'np.arange', (['self.NFFT_density'], {}), '(self.NFFT_density)\n', (46106, 46125), True, 'import numpy as np\n'), ((46391, 46418), 'matplotlib.mlab.window_hanning', 'mlab.window_hanning', (['ydata2'], {}), '(ydata2)\n', (46410, 46418), True, 'import matplotlib.mlab as mlab\n'), ((46436, 46463), 'numpy.vstack', 'np.vstack', (['[ydata1, ydata2]'], {}), '([ydata1, ydata2])\n', (46445, 46463), True, 'import numpy as np\n'), ((46484, 46517), 'numpy.vstack', 'np.vstack', (['[ycontrol1, ycontrol2]'], {}), '([ycontrol1, ycontrol2])\n', (46493, 46517), True, 'import numpy as np\n'), ((46535, 46558), 'numpy.tile', 'np.tile', (['ydata', '(20, 1)'], {}), '(ydata, (20, 1))\n', (46542, 46558), True, 'import numpy as np\n'), ((46579, 46605), 'numpy.tile', 'np.tile', (['ycontrol', '(20, 1)'], {}), '(ycontrol, (20, 1))\n', (46586, 46605), True, 'import numpy as np\n'), ((46740, 46857), 'matplotlib.mlab.psd', 'mlab.psd', ([], {'x': 'ydataf', 'NFFT': 'self.NFFT_density', 'Fs': 'self.Fs', 'noverlap': '(0)', 'sides': 'self.sides', 'window': 'mlab.window_hanning'}), '(x=ydataf, NFFT=self.NFFT_density, Fs=self.Fs, noverlap=0, sides=\n self.sides, window=mlab.window_hanning)\n', (46748, 46857), True, 'import matplotlib.mlab as mlab\n'), ((47048, 47165), 'matplotlib.mlab.psd', 'mlab.psd', ([], {'x': 'ydatab', 'NFFT': 'self.NFFT_density', 'Fs': 'self.Fs', 'noverlap': '(0)', 'sides': 'self.sides', 'window': 'mlab.window_hanning'}), '(x=ydatab, NFFT=self.NFFT_density, Fs=self.Fs, noverlap=0, sides=\n self.sides, window=mlab.window_hanning)\n', (47056, 47165), True, 'import matplotlib.mlab as mlab\n'), ((47356, 47472), 'matplotlib.mlab.psd', 'mlab.psd', ([], {'x': 'ycontrol', 'NFFT': 'self.NFFT_density', 'Fs': 'self.Fs', 'noverlap': '(0)', 'sides': 'self.sides', 'window': 'mlab.window_none'}), '(x=ycontrol, NFFT=self.NFFT_density, Fs=self.Fs, noverlap=0, sides=\n self.sides, window=mlab.window_none)\n', (47364, 47472), True, 'import matplotlib.mlab as mlab\n'), ((47711, 47743), 'numpy.testing.assert_array_equal', 'assert_array_equal', (['fsp_g', 'fsp_c'], {}), '(fsp_g, fsp_c)\n', (47729, 47743), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((47753, 47785), 'numpy.testing.assert_array_equal', 'assert_array_equal', (['fsp_b', 'fsp_c'], {}), '(fsp_b, fsp_c)\n', (47771, 47785), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((47795, 47838), 'numpy.testing.assert_allclose', 'assert_allclose', (['spec_g', 'spec_c'], {'atol': '(1e-08)'}), '(spec_g, spec_c, atol=1e-08)\n', (47810, 47838), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((48118, 48146), 'numpy.arange', 'np.arange', (['self.NFFT_density'], {}), '(self.NFFT_density)\n', (48127, 48146), True, 'import numpy as np\n'), ((48167, 48194), 'numpy.zeros', 'np.zeros', (['self.NFFT_density'], {}), '(self.NFFT_density)\n', (48175, 48194), True, 'import numpy as np\n'), ((48523, 48553), 'matplotlib.mlab.window_hanning', 'mlab.window_hanning', (['ycontrol2'], {}), '(ycontrol2)\n', (48542, 48553), True, 'import matplotlib.mlab as mlab\n'), ((48571, 48598), 'numpy.vstack', 'np.vstack', (['[ydata1, ydata2]'], {}), '([ydata1, ydata2])\n', (48580, 48598), True, 'import numpy as np\n'), ((48619, 48652), 'numpy.vstack', 'np.vstack', (['[ycontrol1, ycontrol2]'], {}), '([ycontrol1, ycontrol2])\n', (48628, 48652), True, 'import numpy as np\n'), ((48670, 48693), 'numpy.tile', 'np.tile', (['ydata', '(20, 1)'], {}), '(ydata, (20, 1))\n', (48677, 48693), True, 'import numpy as np\n'), ((48714, 48740), 'numpy.tile', 'np.tile', (['ycontrol', '(20, 1)'], {}), '(ycontrol, (20, 1))\n', (48721, 48740), True, 'import numpy as np\n'), ((48875, 49021), 'matplotlib.mlab.psd', 'mlab.psd', ([], {'x': 'ydataf', 'NFFT': 'self.NFFT_density', 'Fs': 'self.Fs', 'noverlap': '(0)', 'sides': 'self.sides', 'detrend': 'mlab.detrend_linear', 'window': 'mlab.window_hanning'}), '(x=ydataf, NFFT=self.NFFT_density, Fs=self.Fs, noverlap=0, sides=\n self.sides, detrend=mlab.detrend_linear, window=mlab.window_hanning)\n', (48883, 49021), True, 'import matplotlib.mlab as mlab\n'), ((49246, 49392), 'matplotlib.mlab.psd', 'mlab.psd', ([], {'x': 'ydatab', 'NFFT': 'self.NFFT_density', 'Fs': 'self.Fs', 'noverlap': '(0)', 'sides': 'self.sides', 'detrend': 'mlab.detrend_linear', 'window': 'mlab.window_hanning'}), '(x=ydatab, NFFT=self.NFFT_density, Fs=self.Fs, noverlap=0, sides=\n self.sides, detrend=mlab.detrend_linear, window=mlab.window_hanning)\n', (49254, 49392), True, 'import matplotlib.mlab as mlab\n'), ((49617, 49733), 'matplotlib.mlab.psd', 'mlab.psd', ([], {'x': 'ycontrol', 'NFFT': 'self.NFFT_density', 'Fs': 'self.Fs', 'noverlap': '(0)', 'sides': 'self.sides', 'window': 'mlab.window_none'}), '(x=ycontrol, NFFT=self.NFFT_density, Fs=self.Fs, noverlap=0, sides=\n self.sides, window=mlab.window_none)\n', (49625, 49733), True, 'import matplotlib.mlab as mlab\n'), ((49972, 50004), 'numpy.testing.assert_array_equal', 'assert_array_equal', (['fsp_g', 'fsp_c'], {}), '(fsp_g, fsp_c)\n', (49990, 50004), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((50014, 50046), 'numpy.testing.assert_array_equal', 'assert_array_equal', (['fsp_b', 'fsp_c'], {}), '(fsp_b, fsp_c)\n', (50032, 50046), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((50056, 50099), 'numpy.testing.assert_allclose', 'assert_allclose', (['spec_g', 'spec_c'], {'atol': '(1e-08)'}), '(spec_g, spec_c, atol=1e-08)\n', (50071, 50099), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((50701, 50740), 'numpy.testing.assert_allclose', 'assert_allclose', (['fsp', 'freqs'], {'atol': '(1e-06)'}), '(fsp, freqs, atol=1e-06)\n', (50716, 50740), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((50927, 51094), 'matplotlib.mlab.psd', 'mlab.psd', ([], {'x': 'self.y', 'NFFT': 'self.NFFT_density', 'Fs': 'self.Fs', 'noverlap': 'self.nover_density', 'pad_to': 'self.pad_to_density', 'sides': 'self.sides', 'window': 'mlab.window_hanning'}), '(x=self.y, NFFT=self.NFFT_density, Fs=self.Fs, noverlap=self.\n nover_density, pad_to=self.pad_to_density, sides=self.sides, window=\n mlab.window_hanning)\n', (50935, 51094), True, 'import matplotlib.mlab as mlab\n'), ((51290, 51477), 'matplotlib.mlab.psd', 'mlab.psd', ([], {'x': 'self.y', 'NFFT': 'self.NFFT_density', 'Fs': 'self.Fs', 'noverlap': 'self.nover_density', 'pad_to': 'self.pad_to_density', 'sides': 'self.sides', 'window': 'mlab.window_hanning', 'scale_by_freq': '(True)'}), '(x=self.y, NFFT=self.NFFT_density, Fs=self.Fs, noverlap=self.\n nover_density, pad_to=self.pad_to_density, sides=self.sides, window=\n mlab.window_hanning, scale_by_freq=True)\n', (51298, 51477), True, 'import matplotlib.mlab as mlab\n'), ((51731, 51919), 'matplotlib.mlab.psd', 'mlab.psd', ([], {'x': 'self.y', 'NFFT': 'self.NFFT_density', 'Fs': 'self.Fs', 'noverlap': 'self.nover_density', 'pad_to': 'self.pad_to_density', 'sides': 'self.sides', 'window': 'mlab.window_hanning', 'scale_by_freq': '(False)'}), '(x=self.y, NFFT=self.NFFT_density, Fs=self.Fs, noverlap=self.\n nover_density, pad_to=self.pad_to_density, sides=self.sides, window=\n mlab.window_hanning, scale_by_freq=False)\n', (51739, 51919), True, 'import matplotlib.mlab as mlab\n'), ((52157, 52187), 'numpy.testing.assert_array_equal', 'assert_array_equal', (['fsp', 'fsp_s'], {}), '(fsp, fsp_s)\n', (52175, 52187), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((52197, 52227), 'numpy.testing.assert_array_equal', 'assert_array_equal', (['fsp', 'fsp_n'], {}), '(fsp, fsp_n)\n', (52215, 52227), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((52237, 52269), 'numpy.testing.assert_array_equal', 'assert_array_equal', (['spec', 'spec_s'], {}), '(spec, spec_s)\n', (52255, 52269), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((52736, 52775), 'numpy.testing.assert_allclose', 'assert_allclose', (['fsp', 'freqs'], {'atol': '(1e-06)'}), '(fsp, freqs, atol=1e-06)\n', (52751, 52775), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((53264, 53416), 'matplotlib.mlab.specgram', 'mlab.specgram', ([], {'x': 'self.y', 'NFFT': 'self.NFFT_specgram', 'Fs': 'self.Fs', 'noverlap': 'self.nover_specgram', 'pad_to': 'self.pad_to_specgram', 'sides': 'self.sides'}), '(x=self.y, NFFT=self.NFFT_specgram, Fs=self.Fs, noverlap=self.\n nover_specgram, pad_to=self.pad_to_specgram, sides=self.sides, **kwargs)\n', (53277, 53416), True, 'import matplotlib.mlab as mlab\n'), ((53735, 53756), 'numpy.mean', 'np.mean', (['spec'], {'axis': '(1)'}), '(spec, axis=1)\n', (53742, 53756), True, 'import numpy as np\n'), ((53768, 53807), 'numpy.testing.assert_allclose', 'assert_allclose', (['fsp', 'freqs'], {'atol': '(1e-06)'}), '(fsp, freqs, atol=1e-06)\n', (53783, 53807), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((53817, 53864), 'numpy.testing.assert_allclose', 'assert_allclose', (['t', 'self.t_specgram'], {'atol': '(1e-06)'}), '(t, self.t_specgram, atol=1e-06)\n', (53832, 53864), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((54740, 54874), 'matplotlib.mlab.psd', 'mlab.psd', ([], {'x': 'self.y', 'NFFT': 'self.NFFT_density', 'Fs': 'self.Fs', 'noverlap': 'self.nover_density', 'pad_to': 'self.pad_to_density', 'sides': 'self.sides'}), '(x=self.y, NFFT=self.NFFT_density, Fs=self.Fs, noverlap=self.\n nover_density, pad_to=self.pad_to_density, sides=self.sides)\n', (54748, 54874), True, 'import matplotlib.mlab as mlab\n'), ((55059, 55203), 'matplotlib.mlab.csd', 'mlab.csd', ([], {'x': 'self.y', 'y': 'self.y', 'NFFT': 'self.NFFT_density', 'Fs': 'self.Fs', 'noverlap': 'self.nover_density', 'pad_to': 'self.pad_to_density', 'sides': 'self.sides'}), '(x=self.y, y=self.y, NFFT=self.NFFT_density, Fs=self.Fs, noverlap=\n self.nover_density, pad_to=self.pad_to_density, sides=self.sides)\n', (55067, 55203), True, 'import matplotlib.mlab as mlab\n'), ((55373, 55413), 'numpy.testing.assert_array_almost_equal_nulp', 'assert_array_almost_equal_nulp', (['Pxx', 'Pxy'], {}), '(Pxx, Pxy)\n', (55403, 55413), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((55423, 55459), 'numpy.testing.assert_array_equal', 'assert_array_equal', (['freqsxx', 'freqsxy'], {}), '(freqsxx, freqsxy)\n', (55441, 55459), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((55744, 55886), 'matplotlib.mlab.specgram', 'mlab.specgram', ([], {'x': 'self.y', 'NFFT': 'self.NFFT_specgram', 'Fs': 'self.Fs', 'noverlap': 'self.nover_specgram', 'pad_to': 'self.pad_to_specgram', 'sides': 'self.sides'}), '(x=self.y, NFFT=self.NFFT_specgram, Fs=self.Fs, noverlap=self.\n nover_specgram, pad_to=self.pad_to_specgram, sides=self.sides)\n', (55757, 55886), True, 'import matplotlib.mlab as mlab\n'), ((56144, 56297), 'matplotlib.mlab.specgram', 'mlab.specgram', ([], {'x': 'self.y', 'NFFT': 'self.NFFT_specgram', 'Fs': 'self.Fs', 'noverlap': 'self.nover_specgram', 'pad_to': 'self.pad_to_specgram', 'sides': 'self.sides', 'mode': 'mode'}), '(x=self.y, NFFT=self.NFFT_specgram, Fs=self.Fs, noverlap=self.\n nover_specgram, pad_to=self.pad_to_specgram, sides=self.sides, mode=mode)\n', (56157, 56297), True, 'import matplotlib.mlab as mlab\n'), ((56578, 56610), 'numpy.testing.assert_array_equal', 'assert_array_equal', (['speca', 'specb'], {}), '(speca, specb)\n', (56596, 56610), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((56620, 56660), 'numpy.testing.assert_array_equal', 'assert_array_equal', (['freqspeca', 'freqspecb'], {}), '(freqspeca, freqspecb)\n', (56638, 56660), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((56670, 56696), 'numpy.testing.assert_array_equal', 'assert_array_equal', (['ta', 'tb'], {}), '(ta, tb)\n', (56688, 56696), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((56995, 57158), 'matplotlib.mlab.specgram', 'mlab.specgram', ([], {'x': 'self.y', 'NFFT': 'self.NFFT_specgram', 'Fs': 'self.Fs', 'noverlap': 'self.nover_specgram', 'pad_to': 'self.pad_to_specgram', 'sides': 'self.sides', 'mode': '"""complex"""'}), "(x=self.y, NFFT=self.NFFT_specgram, Fs=self.Fs, noverlap=self.\n nover_specgram, pad_to=self.pad_to_specgram, sides=self.sides, mode=\n 'complex')\n", (57008, 57158), True, 'import matplotlib.mlab as mlab\n'), ((57457, 57610), 'matplotlib.mlab.specgram', 'mlab.specgram', ([], {'x': 'self.y', 'NFFT': 'self.NFFT_specgram', 'Fs': 'self.Fs', 'noverlap': 'self.nover_specgram', 'pad_to': 'self.pad_to_specgram', 'sides': 'self.sides', 'mode': 'mode'}), '(x=self.y, NFFT=self.NFFT_specgram, Fs=self.Fs, noverlap=self.\n nover_specgram, pad_to=self.pad_to_specgram, sides=self.sides, mode=mode)\n', (57470, 57610), True, 'import matplotlib.mlab as mlab\n'), ((57893, 57933), 'numpy.testing.assert_array_equal', 'assert_array_equal', (['freqspecc', 'freqspecm'], {}), '(freqspecc, freqspecm)\n', (57911, 57933), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((57943, 57969), 'numpy.testing.assert_array_equal', 'assert_array_equal', (['tc', 'tm'], {}), '(tc, tm)\n', (57961, 57969), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((58163, 58309), 'matplotlib.mlab.psd', 'mlab.psd', ([], {'x': 'self.y', 'NFFT': 'self.NFFT_density', 'Fs': 'self.Fs', 'noverlap': 'self.nover_density', 'pad_to': 'self.pad_to_density', 'sides': 'self.sides', 'window': 'win'}), '(x=self.y, NFFT=self.NFFT_density, Fs=self.Fs, noverlap=self.\n nover_density, pad_to=self.pad_to_density, sides=self.sides, window=win)\n', (58171, 58309), True, 'import matplotlib.mlab as mlab\n'), ((58520, 58654), 'matplotlib.mlab.psd', 'mlab.psd', ([], {'x': 'self.y', 'NFFT': 'self.NFFT_density', 'Fs': 'self.Fs', 'noverlap': 'self.nover_density', 'pad_to': 'self.pad_to_density', 'sides': 'self.sides'}), '(x=self.y, NFFT=self.NFFT_density, Fs=self.Fs, noverlap=self.\n nover_density, pad_to=self.pad_to_density, sides=self.sides)\n', (58528, 58654), True, 'import matplotlib.mlab as mlab\n'), ((58819, 58849), 'numpy.testing.assert_array_equal', 'assert_array_equal', (['fspa', 'fspb'], {}), '(fspa, fspb)\n', (58837, 58849), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((58859, 58900), 'numpy.testing.assert_allclose', 'assert_allclose', (['speca', 'specb'], {'atol': '(1e-08)'}), '(speca, specb, atol=1e-08)\n', (58874, 58900), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((59236, 59250), 'numpy.mean', 'np.mean', (['cohsq'], {}), '(cohsq)\n', (59243, 59250), True, 'import numpy as np\n'), ((59293, 59307), 'numpy.mean', 'np.mean', (['cohsq'], {}), '(cohsq)\n', (59300, 59307), True, 'import numpy as np\n'), ((59750, 59762), 'numpy.arange', 'np.arange', (['(5)'], {}), '(5)\n', (59759, 59762), True, 'import numpy as np\n'), ((59778, 59798), 'matplotlib.mlab.GaussianKDE', 'mlab.GaussianKDE', (['x1'], {}), '(x1)\n', (59794, 59798), True, 'import matplotlib.mlab as mlab\n'), ((60052, 60092), 'numpy.array', 'np.array', (['[-7, -5, 1, 4, 5]'], {'dtype': 'float'}), '([-7, -5, 1, 4, 5], dtype=float)\n', (60060, 60092), True, 'import numpy as np\n'), ((60107, 60134), 'numpy.linspace', 'np.linspace', (['(-10)', '(10)'], {'num': '(5)'}), '(-10, 10, num=5)\n', (60118, 60134), True, 'import numpy as np\n'), ((60457, 60486), 'matplotlib.mlab.GaussianKDE', 'mlab.GaussianKDE', (['x1', '"""scott"""'], {}), "(x1, 'scott')\n", (60473, 60486), True, 'import matplotlib.mlab as mlab\n'), ((60521, 60584), 'numpy.testing.assert_array_almost_equal', 'np.testing.assert_array_almost_equal', (['y_expected', 'y2'], {'decimal': '(7)'}), '(y_expected, y2, decimal=7)\n', (60557, 60584), True, 'import numpy as np\n'), ((60640, 60663), 'numpy.random.seed', 'np.random.seed', (['(8765678)'], {}), '(8765678)\n', (60654, 60663), True, 'import numpy as np\n'), ((60705, 60734), 'numpy.random.randn', 'np.random.randn', (['n_basesample'], {}), '(n_basesample)\n', (60720, 60734), True, 'import numpy as np\n'), ((60772, 60792), 'matplotlib.mlab.GaussianKDE', 'mlab.GaussianKDE', (['xn'], {}), '(xn)\n', (60788, 60792), True, 'import matplotlib.mlab as mlab\n'), ((60839, 60868), 'matplotlib.mlab.GaussianKDE', 'mlab.GaussianKDE', (['xn', '"""scott"""'], {}), "(xn, 'scott')\n", (60855, 60868), True, 'import matplotlib.mlab as mlab\n'), ((60913, 60956), 'matplotlib.mlab.GaussianKDE', 'mlab.GaussianKDE', (['xn'], {'bw_method': 'gkde.factor'}), '(xn, bw_method=gkde.factor)\n', (60929, 60956), True, 'import matplotlib.mlab as mlab\n'), ((60973, 60995), 'numpy.linspace', 'np.linspace', (['(-7)', '(7)', '(51)'], {}), '(-7, 7, 51)\n', (60984, 60995), True, 'import numpy as np\n'), ((61717, 61760), 'numpy.array', 'np.array', (['[[1, 2, 3], [4, 5, 6], [7, 8, 9]]'], {}), '([[1, 2, 3], [4, 5, 6], [7, 8, 9]])\n', (61725, 61760), True, 'import numpy as np\n'), ((61993, 62020), 'numpy.array', 'np.array', (['[-7, -5, 1, 4, 5]'], {}), '([-7, -5, 1, 4, 5])\n', (62001, 62020), True, 'import numpy as np\n'), ((62040, 62073), 'matplotlib.mlab.GaussianKDE', 'mlab.GaussianKDE', (['x1', '"""silverman"""'], {}), "(x1, 'silverman')\n", (62056, 62073), True, 'import matplotlib.mlab as mlab\n'), ((62315, 62358), 'numpy.array', 'np.array', (['[[1, 2, 3], [4, 5, 6], [7, 8, 9]]'], {}), '([[1, 2, 3], [4, 5, 6], [7, 8, 9]])\n', (62323, 62358), True, 'import numpy as np\n'), ((62578, 62605), 'numpy.array', 'np.array', (['[-7, -5, 1, 4, 5]'], {}), '([-7, -5, 1, 4, 5])\n', (62586, 62605), True, 'import numpy as np\n'), ((62625, 62654), 'matplotlib.mlab.GaussianKDE', 'mlab.GaussianKDE', (['x1', '"""scott"""'], {}), "(x1, 'scott')\n", (62641, 62654), True, 'import matplotlib.mlab as mlab\n'), ((63067, 63090), 'numpy.random.seed', 'np.random.seed', (['(8765678)'], {}), '(8765678)\n', (63081, 63090), True, 'import numpy as np\n'), ((63210, 63256), 'matplotlib.mlab.GaussianKDE', 'mlab.GaussianKDE', (['multidim_data'], {'bw_method': '(0.5)'}), '(multidim_data, bw_method=0.5)\n', (63226, 63256), True, 'import matplotlib.mlab as mlab\n'), ((63441, 63464), 'numpy.random.seed', 'np.random.seed', (['(8765678)'], {}), '(8765678)\n', (63455, 63464), True, 'import numpy as np\n'), ((63639, 63694), 'matplotlib.mlab.GaussianKDE', 'mlab.GaussianKDE', (['multidim_data'], {'bw_method': 'callable_fun'}), '(multidim_data, bw_method=callable_fun)\n', (63655, 63694), True, 'import matplotlib.mlab as mlab\n'), ((63880, 63903), 'numpy.random.seed', 'np.random.seed', (['(8765678)'], {}), '(8765678)\n', (63894, 63903), True, 'import numpy as np\n'), ((63956, 63985), 'numpy.random.randn', 'np.random.randn', (['n_basesample'], {}), '(n_basesample)\n', (63971, 63985), True, 'import numpy as np\n'), ((64003, 64057), 'matplotlib.mlab.GaussianKDE', 'mlab.GaussianKDE', (['multidim_data'], {'bw_method': '"""silverman"""'}), "(multidim_data, bw_method='silverman')\n", (64019, 64057), True, 'import matplotlib.mlab as mlab\n'), ((64297, 64320), 'numpy.random.seed', 'np.random.seed', (['(8765678)'], {}), '(8765678)\n', (64311, 64320), True, 'import numpy as np\n'), ((64364, 64393), 'numpy.random.randn', 'np.random.randn', (['n_basesample'], {}), '(n_basesample)\n', (64379, 64393), True, 'import numpy as np\n'), ((64716, 64735), 'numpy.arange', 'np.arange', (['(3)', '(10)', '(2)'], {}), '(3, 10, 2)\n', (64725, 64735), True, 'import numpy as np\n'), ((64751, 64771), 'matplotlib.mlab.GaussianKDE', 'mlab.GaussianKDE', (['x1'], {}), '(x1)\n', (64767, 64771), True, 'import matplotlib.mlab as mlab\n'), ((64786, 64805), 'numpy.arange', 'np.arange', (['(3)', '(12)', '(2)'], {}), '(3, 12, 2)\n', (64795, 64805), True, 'import numpy as np\n'), ((64951, 65005), 'numpy.testing.assert_array_almost_equal', 'np.testing.assert_array_almost_equal', (['y', 'y_expected', '(7)'], {}), '(y, y_expected, 7)\n', (64987, 65005), True, 'import numpy as np\n'), ((65225, 65248), 'numpy.random.seed', 'np.random.seed', (['(8765678)'], {}), '(8765678)\n', (65239, 65248), True, 'import numpy as np\n'), ((65301, 65330), 'numpy.random.randn', 'np.random.randn', (['n_basesample'], {}), '(n_basesample)\n', (65316, 65330), True, 'import numpy as np\n'), ((65346, 65377), 'matplotlib.mlab.GaussianKDE', 'mlab.GaussianKDE', (['multidim_data'], {}), '(multidim_data)\n', (65362, 65377), True, 'import matplotlib.mlab as mlab\n'), ((65598, 65617), 'numpy.arange', 'np.arange', (['(3)', '(10)', '(2)'], {}), '(3, 10, 2)\n', (65607, 65617), True, 'import numpy as np\n'), ((65632, 65645), 'numpy.array', 'np.array', (['[3]'], {}), '([3])\n', (65640, 65645), True, 'import numpy as np\n'), ((65661, 65681), 'matplotlib.mlab.GaussianKDE', 'mlab.GaussianKDE', (['x1'], {}), '(x1)\n', (65677, 65681), True, 'import matplotlib.mlab as mlab\n'), ((65756, 65810), 'numpy.testing.assert_array_almost_equal', 'np.testing.assert_array_almost_equal', (['y', 'y_expected', '(7)'], {}), '(y, y_expected, 7)\n', (65792, 65810), True, 'import numpy as np\n'), ((65875, 65894), 'numpy.arange', 'np.arange', (['(3)', '(10)', '(2)'], {}), '(3, 10, 2)\n', (65884, 65894), True, 'import numpy as np\n'), ((65967, 65987), 'matplotlib.mlab.GaussianKDE', 'mlab.GaussianKDE', (['x1'], {}), '(x1)\n', (65983, 65987), True, 'import matplotlib.mlab as mlab\n'), ((66126, 66145), 'numpy.arange', 'np.arange', (['(3)', '(10)', '(2)'], {}), '(3, 10, 2)\n', (66135, 66145), True, 'import numpy as np\n'), ((66160, 66178), 'numpy.arange', 'np.arange', (['(3)', '(8)', '(2)'], {}), '(3, 8, 2)\n', (66169, 66178), True, 'import numpy as np\n'), ((66194, 66214), 'matplotlib.mlab.GaussianKDE', 'mlab.GaussianKDE', (['x1'], {}), '(x1)\n', (66210, 66214), True, 'import matplotlib.mlab as mlab\n'), ((66313, 66367), 'numpy.testing.assert_array_almost_equal', 'np.testing.assert_array_almost_equal', (['y', 'y_expected', '(7)'], {}), '(y, y_expected, 7)\n', (66349, 66367), True, 'import numpy as np\n'), ((67348, 67357), 'numpy.sum', 'np.sum', (['P'], {}), '(P)\n', (67354, 67357), True, 'import numpy as np\n'), ((67359, 67375), 'numpy.sum', 'np.sum', (['Su_1side'], {}), '(Su_1side)\n', (67365, 67375), True, 'import numpy as np\n'), ((1384, 1409), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (1397, 1409), False, 'import pytest\n'), ((1424, 1449), 'matplotlib.mlab.stride_windows', 'mlab.stride_windows', (['x', '(5)'], {}), '(x, 5)\n', (1443, 1449), True, 'import matplotlib.mlab as mlab\n'), ((1870, 1895), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (1883, 1895), False, 'import pytest\n'), ((1910, 1945), 'matplotlib.mlab.stride_windows', 'mlab.stride_windows', (['x', 'n', 'noverlap'], {}), '(x, n, noverlap)\n', (1929, 1945), True, 'import matplotlib.mlab as mlab\n'), ((2150, 2175), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (2163, 2175), False, 'import pytest\n'), ((2477, 2502), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (2490, 2502), False, 'import pytest\n'), ((2645, 2670), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (2658, 2670), False, 'import pytest\n'), ((3050, 3073), 'numpy.expand_dims', 'np.expand_dims', (['x', 'axis'], {}), '(x, axis)\n', (3064, 3073), True, 'import numpy as np\n'), ((4251, 4263), 'numpy.arange', 'np.arange', (['n'], {}), '(n)\n', (4260, 4263), True, 'import numpy as np\n'), ((5487, 5515), 'numpy.random.standard_normal', 'np.random.standard_normal', (['n'], {}), '(n)\n', (5512, 5515), True, 'import numpy as np\n'), ((7068, 7093), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (7081, 7093), False, 'import pytest\n'), ((7291, 7314), 'numpy.ones', 'np.ones', (['(x.shape[0] - 1)'], {}), '(x.shape[0] - 1)\n', (7298, 7314), True, 'import numpy as np\n'), ((7328, 7353), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (7341, 7353), False, 'import pytest\n'), ((7520, 7545), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (7533, 7545), False, 'import pytest\n'), ((7767, 7792), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (7780, 7792), False, 'import pytest\n'), ((8012, 8031), 'numpy.ones', 'np.ones', (['x.shape[0]'], {}), '(x.shape[0])\n', (8019, 8031), True, 'import numpy as np\n'), ((8731, 8750), 'numpy.ones', 'np.ones', (['x.shape[0]'], {}), '(x.shape[0])\n', (8738, 8750), True, 'import numpy as np\n'), ((9064, 9101), 'numpy.random.standard_normal', 'np.random.standard_normal', (['[1000, 10]'], {}), '([1000, 10])\n', (9089, 9101), True, 'import numpy as np\n'), ((9508, 9545), 'numpy.random.standard_normal', 'np.random.standard_normal', (['[1000, 10]'], {}), '([1000, 10])\n', (9533, 9545), True, 'import numpy as np\n'), ((9591, 9610), 'numpy.ones', 'np.ones', (['x.shape[0]'], {}), '(x.shape[0])\n', (9598, 9610), True, 'import numpy as np\n'), ((10013, 10050), 'numpy.random.standard_normal', 'np.random.standard_normal', (['[1000, 10]'], {}), '([1000, 10])\n', (10038, 10050), True, 'import numpy as np\n'), ((10135, 10154), 'numpy.ones', 'np.ones', (['x.shape[0]'], {}), '(x.shape[0])\n', (10142, 10154), True, 'import numpy as np\n'), ((10571, 10608), 'numpy.random.standard_normal', 'np.random.standard_normal', (['[1000, 10]'], {}), '([1000, 10])\n', (10596, 10608), True, 'import numpy as np\n'), ((10693, 10712), 'numpy.ones', 'np.ones', (['x.shape[0]'], {}), '(x.shape[0])\n', (10700, 10712), True, 'import numpy as np\n'), ((11085, 11122), 'numpy.random.standard_normal', 'np.random.standard_normal', (['[10, 1000]'], {}), '([10, 1000])\n', (11110, 11122), True, 'import numpy as np\n'), ((11529, 11566), 'numpy.random.standard_normal', 'np.random.standard_normal', (['[10, 1000]'], {}), '([10, 1000])\n', (11554, 11566), True, 'import numpy as np\n'), ((11612, 11631), 'numpy.ones', 'np.ones', (['x.shape[1]'], {}), '(x.shape[1])\n', (11619, 11631), True, 'import numpy as np\n'), ((12034, 12071), 'numpy.random.standard_normal', 'np.random.standard_normal', (['[10, 1000]'], {}), '([10, 1000])\n', (12059, 12071), True, 'import numpy as np\n'), ((12156, 12175), 'numpy.ones', 'np.ones', (['x.shape[1]'], {}), '(x.shape[1])\n', (12163, 12175), True, 'import numpy as np\n'), ((12594, 12631), 'numpy.random.standard_normal', 'np.random.standard_normal', (['[10, 1000]'], {}), '([10, 1000])\n', (12619, 12631), True, 'import numpy as np\n'), ((12716, 12735), 'numpy.ones', 'np.ones', (['x.shape[1]'], {}), '(x.shape[1])\n', (12723, 12735), True, 'import numpy as np\n'), ((22228, 22243), 'numpy.vstack', 'np.vstack', (['arri'], {}), '(arri)\n', (22237, 22243), True, 'import numpy as np\n'), ((22830, 22845), 'numpy.vstack', 'np.vstack', (['arri'], {}), '(arri)\n', (22839, 22845), True, 'import numpy as np\n'), ((22864, 22879), 'numpy.vstack', 'np.vstack', (['arrt'], {}), '(arrt)\n', (22873, 22879), True, 'import numpy as np\n'), ((25299, 25314), 'numpy.vstack', 'np.vstack', (['arri'], {}), '(arri)\n', (25308, 25314), True, 'import numpy as np\n'), ((25333, 25348), 'numpy.vstack', 'np.vstack', (['arrt'], {}), '(arrt)\n', (25342, 25348), True, 'import numpy as np\n'), ((25693, 25708), 'numpy.vstack', 'np.vstack', (['arri'], {}), '(arri)\n', (25702, 25708), True, 'import numpy as np\n'), ((26926, 26941), 'numpy.vstack', 'np.vstack', (['arri'], {}), '(arri)\n', (26935, 26941), True, 'import numpy as np\n'), ((26960, 26975), 'numpy.vstack', 'np.vstack', (['arrt'], {}), '(arrt)\n', (26969, 26975), True, 'import numpy as np\n'), ((27229, 27254), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (27242, 27254), False, 'import pytest\n'), ((27269, 27300), 'matplotlib.mlab.detrend', 'mlab.detrend', (['input'], {'key': '"""spam"""'}), "(input, key='spam')\n", (27281, 27300), True, 'import matplotlib.mlab as mlab\n'), ((27413, 27438), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (27426, 27438), False, 'import pytest\n'), ((27453, 27479), 'matplotlib.mlab.detrend', 'mlab.detrend', (['input'], {'key': '(5)'}), '(input, key=5)\n', (27465, 27479), True, 'import matplotlib.mlab as mlab\n'), ((27568, 27593), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (27581, 27593), False, 'import pytest\n'), ((27608, 27640), 'matplotlib.mlab.detrend_mean', 'mlab.detrend_mean', (['input'], {'axis': '(0)'}), '(input, axis=0)\n', (27625, 27640), True, 'import matplotlib.mlab as mlab\n'), ((27724, 27749), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (27737, 27749), False, 'import pytest\n'), ((27764, 27791), 'matplotlib.mlab.detrend', 'mlab.detrend', (['input'], {'axis': '(0)'}), '(input, axis=0)\n', (27776, 27791), True, 'import matplotlib.mlab as mlab\n'), ((27891, 27916), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (27904, 27916), False, 'import pytest\n'), ((27931, 27963), 'matplotlib.mlab.detrend_mean', 'mlab.detrend_mean', (['input'], {'axis': '(1)'}), '(input, axis=1)\n', (27948, 27963), True, 'import matplotlib.mlab as mlab\n'), ((28058, 28083), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (28071, 28083), False, 'import pytest\n'), ((28098, 28125), 'matplotlib.mlab.detrend', 'mlab.detrend', (['input'], {'axis': '(1)'}), '(input, axis=1)\n', (28110, 28125), True, 'import matplotlib.mlab as mlab\n'), ((28237, 28262), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (28250, 28262), False, 'import pytest\n'), ((28277, 28309), 'matplotlib.mlab.detrend_mean', 'mlab.detrend_mean', (['input'], {'axis': '(2)'}), '(input, axis=2)\n', (28294, 28309), True, 'import matplotlib.mlab as mlab\n'), ((28416, 28441), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (28429, 28441), False, 'import pytest\n'), ((28456, 28483), 'matplotlib.mlab.detrend', 'mlab.detrend', (['input'], {'axis': '(2)'}), '(input, axis=2)\n', (28468, 28483), True, 'import matplotlib.mlab as mlab\n'), ((30647, 30672), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (30660, 30672), False, 'import pytest\n'), ((30687, 30713), 'matplotlib.mlab.detrend_linear', 'mlab.detrend_linear', (['input'], {}), '(input)\n', (30706, 30713), True, 'import matplotlib.mlab as mlab\n'), ((31003, 31018), 'numpy.vstack', 'np.vstack', (['arri'], {}), '(arri)\n', (31012, 31018), True, 'import numpy as np\n'), ((31037, 31052), 'numpy.vstack', 'np.vstack', (['arrt'], {}), '(arrt)\n', (31046, 31052), True, 'import numpy as np\n'), ((31457, 31472), 'numpy.vstack', 'np.vstack', (['arri'], {}), '(arri)\n', (31466, 31472), True, 'import numpy as np\n'), ((31491, 31506), 'numpy.vstack', 'np.vstack', (['arrt'], {}), '(arrt)\n', (31500, 31506), True, 'import numpy as np\n'), ((38298, 38339), 'numpy.array', 'np.array', (['[NFFT_specgram_real / (2 * Fs)]'], {}), '([NFFT_specgram_real / (2 * Fs)])\n', (38306, 38339), True, 'import numpy as np\n'), ((40307, 40318), 'numpy.abs', 'np.abs', (['fsp'], {}), '(fsp)\n', (40313, 40318), True, 'import numpy as np\n'), ((40770, 40811), 'numpy.testing.assert_almost_equal', 'assert_almost_equal', (['maxfreq', 'fstimst[-1]'], {}), '(maxfreq, fstimst[-1])\n', (40789, 40811), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((41873, 41898), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (41886, 41898), False, 'import pytest\n'), ((41913, 41962), 'matplotlib.mlab._single_spectrum_helper', 'mlab._single_spectrum_helper', ([], {'x': 'self.y', 'mode': 'mode'}), '(x=self.y, mode=mode)\n', (41941, 41962), True, 'import matplotlib.mlab as mlab\n'), ((45891, 45920), 'pytest.raises', 'pytest.raises', (['AssertionError'], {}), '(AssertionError)\n', (45904, 45920), False, 'import pytest\n'), ((45935, 45978), 'numpy.testing.assert_allclose', 'assert_allclose', (['spec_b', 'spec_c'], {'atol': '(1e-08)'}), '(spec_b, spec_c, atol=1e-08)\n', (45950, 45978), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((47897, 47926), 'pytest.raises', 'pytest.raises', (['AssertionError'], {}), '(AssertionError)\n', (47910, 47926), False, 'import pytest\n'), ((47941, 47984), 'numpy.testing.assert_allclose', 'assert_allclose', (['spec_b', 'spec_c'], {'atol': '(1e-08)'}), '(spec_b, spec_c, atol=1e-08)\n', (47956, 47984), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((50158, 50187), 'pytest.raises', 'pytest.raises', (['AssertionError'], {}), '(AssertionError)\n', (50171, 50187), False, 'import pytest\n'), ((50202, 50245), 'numpy.testing.assert_allclose', 'assert_allclose', (['spec_b', 'spec_c'], {'atol': '(1e-08)'}), '(spec_b, spec_c, atol=1e-08)\n', (50217, 50245), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp\n'), ((50871, 50902), 'numpy.ones', 'np.ones', (['self.NFFT_density_real'], {}), '(self.NFFT_density_real)\n', (50878, 50902), True, 'import numpy as np\n'), ((53705, 53717), 'numpy.abs', 'np.abs', (['spec'], {}), '(spec)\n', (53711, 53717), True, 'import numpy as np\n'), ((54545, 54610), 'pytest.warns', 'pytest.warns', (['UserWarning'], {'match': '"""Only one segment is calculated"""'}), "(UserWarning, match='Only one segment is calculated')\n", (54557, 54610), False, 'import pytest\n'), ((58107, 58138), 'numpy.ones', 'np.ones', (['self.NFFT_density_real'], {}), '(self.NFFT_density_real)\n', (58114, 58138), True, 'import numpy as np\n'), ((59119, 59130), 'numpy.ones', 'np.ones', (['(20)'], {}), '(20)\n', (59126, 59130), True, 'import numpy as np\n'), ((61333, 61358), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (61346, 61358), False, 'import pytest\n'), ((61373, 61393), 'matplotlib.mlab.GaussianKDE', 'mlab.GaussianKDE', (['[]'], {}), '([])\n', (61389, 61393), True, 'import matplotlib.mlab as mlab\n'), ((61527, 61552), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (61540, 61552), False, 'import pytest\n'), ((61567, 61589), 'matplotlib.mlab.GaussianKDE', 'mlab.GaussianKDE', (['[42]'], {}), '([42])\n', (61583, 61589), True, 'import matplotlib.mlab as mlab\n'), ((61775, 61811), 'pytest.raises', 'pytest.raises', (['np.linalg.LinAlgError'], {}), '(np.linalg.LinAlgError)\n', (61788, 61811), False, 'import pytest\n'), ((61826, 61859), 'matplotlib.mlab.GaussianKDE', 'mlab.GaussianKDE', (['x1', '"""silverman"""'], {}), "(x1, 'silverman')\n", (61842, 61859), True, 'import matplotlib.mlab as mlab\n'), ((62373, 62409), 'pytest.raises', 'pytest.raises', (['np.linalg.LinAlgError'], {}), '(np.linalg.LinAlgError)\n', (62386, 62409), False, 'import pytest\n'), ((62424, 62453), 'matplotlib.mlab.GaussianKDE', 'mlab.GaussianKDE', (['x1', '"""scott"""'], {}), "(x1, 'scott')\n", (62440, 62453), True, 'import matplotlib.mlab as mlab\n'), ((62892, 62917), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (62905, 62917), False, 'import pytest\n'), ((62932, 62965), 'matplotlib.mlab.GaussianKDE', 'mlab.GaussianKDE', (['[]'], {'bw_method': '(5)'}), '([], bw_method=5)\n', (62948, 62965), True, 'import matplotlib.mlab as mlab\n'), ((63144, 63173), 'numpy.random.randn', 'np.random.randn', (['n_basesample'], {}), '(n_basesample)\n', (63159, 63173), True, 'import numpy as np\n'), ((63518, 63547), 'numpy.random.randn', 'np.random.randn', (['n_basesample'], {}), '(n_basesample)\n', (63533, 63547), True, 'import numpy as np\n'), ((64408, 64433), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (64421, 64433), False, 'import pytest\n'), ((64448, 64491), 'matplotlib.mlab.GaussianKDE', 'mlab.GaussianKDE', (['data'], {'bw_method': '"""invalid"""'}), "(data, bw_method='invalid')\n", (64464, 64491), True, 'import matplotlib.mlab as mlab\n'), ((65422, 65447), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (65435, 65447), False, 'import pytest\n'), ((65910, 65929), 'numpy.arange', 'np.arange', (['(3)', '(10)', '(2)'], {}), '(3, 10, 2)\n', (65919, 65929), True, 'import numpy as np\n'), ((65931, 65950), 'numpy.arange', 'np.arange', (['(3)', '(10)', '(2)'], {}), '(3, 10, 2)\n', (65940, 65950), True, 'import numpy as np\n'), ((66002, 66027), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (66015, 66027), False, 'import pytest\n'), ((6090, 6112), 'numpy.ones', 'np.ones', (['NFFT', 'x.dtype'], {}), '(NFFT, x.dtype)\n', (6097, 6112), True, 'import numpy as np\n'), ((36071, 36127), 'numpy.linspace', 'np.linspace', (['(0)', '(Fs / 2)'], {'num': '(pad_to_density_real // 2 + 1)'}), '(0, Fs / 2, num=pad_to_density_real // 2 + 1)\n', (36082, 36127), True, 'import numpy as np\n'), ((36599, 36656), 'numpy.linspace', 'np.linspace', (['(0)', '(Fs / 2)'], {'num': '(pad_to_spectrum_real // 2 + 1)'}), '(0, Fs / 2, num=pad_to_spectrum_real // 2 + 1)\n', (36610, 36656), True, 'import numpy as np\n'), ((37122, 37191), 'numpy.linspace', 'np.linspace', (['(-Fs / 2)', '(Fs / 2)'], {'num': 'pad_to_density_real', 'endpoint': '(False)'}), '(-Fs / 2, Fs / 2, num=pad_to_density_real, endpoint=False)\n', (37133, 37191), True, 'import numpy as np\n'), ((37719, 37789), 'numpy.linspace', 'np.linspace', (['(-Fs / 2)', '(Fs / 2)'], {'num': 'pad_to_spectrum_real', 'endpoint': '(False)'}), '(-Fs / 2, Fs / 2, num=pad_to_spectrum_real, endpoint=False)\n', (37730, 37789), True, 'import numpy as np\n'), ((38530, 38559), 'numpy.sin', 'np.sin', (['(fstim * x * np.pi * 2)'], {}), '(fstim * x * np.pi * 2)\n', (38536, 38559), True, 'import numpy as np\n'), ((41581, 41591), 'numpy.ones', 'np.ones', (['(9)'], {}), '(9)\n', (41588, 41591), True, 'import numpy as np\n'), ((41645, 41670), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (41658, 41670), False, 'import pytest\n'), ((41689, 41730), 'matplotlib.mlab._spectral_helper', 'mlab._spectral_helper', ([], {'x': 'self.y'}), '(x=self.y, **kwargs)\n', (41710, 41730), True, 'import matplotlib.mlab as mlab\n'), ((50659, 50690), 'numpy.ones', 'np.ones', (['self.NFFT_density_real'], {}), '(self.NFFT_density_real)\n', (50666, 50690), True, 'import numpy as np\n'), ((1339, 1353), 'numpy.prod', 'np.prod', (['shape'], {}), '(shape)\n', (1346, 1353), True, 'import numpy as np\n'), ((2105, 2119), 'numpy.prod', 'np.prod', (['shape'], {}), '(shape)\n', (2112, 2119), True, 'import numpy as np\n'), ((35860, 35923), 'numpy.linspace', 'np.linspace', (['(0)', '(Fs / 2)'], {'num': 'pad_to_density_real', 'endpoint': '(False)'}), '(0, Fs / 2, num=pad_to_density_real, endpoint=False)\n', (35871, 35923), True, 'import numpy as np\n'), ((36384, 36448), 'numpy.linspace', 'np.linspace', (['(0)', '(Fs / 2)'], {'num': 'pad_to_spectrum_real', 'endpoint': '(False)'}), '(0, Fs / 2, num=pad_to_spectrum_real, endpoint=False)\n', (36395, 36448), True, 'import numpy as np\n'), ((36900, 36973), 'numpy.linspace', 'np.linspace', (['(-Fs / 2)', '(Fs / 2)'], {'num': '(2 * pad_to_density_real)', 'endpoint': '(False)'}), '(-Fs / 2, Fs / 2, num=2 * pad_to_density_real, endpoint=False)\n', (36911, 36973), True, 'import numpy as np\n'), ((37493, 37567), 'numpy.linspace', 'np.linspace', (['(-Fs / 2)', '(Fs / 2)'], {'num': '(2 * pad_to_spectrum_real)', 'endpoint': '(False)'}), '(-Fs / 2, Fs / 2, num=2 * pad_to_spectrum_real, endpoint=False)\n', (37504, 37567), True, 'import numpy as np\n'), ((39940, 39964), 'numpy.abs', 'np.abs', (['(resfreqs - fstim)'], {}), '(resfreqs - fstim)\n', (39946, 39964), True, 'import numpy as np\n'), ((66475, 66488), 'numpy.fft.fft', 'np.fft.fft', (['u'], {}), '(u)\n', (66485, 66488), True, 'import numpy as np\n'), ((66999, 67012), 'numpy.fft.fft', 'np.fft.fft', (['u'], {}), '(u)\n', (67009, 67012), True, 'import numpy as np\n'), ((43685, 43704), 'numpy.conjugate', 'np.conjugate', (['spec0'], {}), '(spec0)\n', (43697, 43704), True, 'import numpy as np\n'), ((47673, 47691), 'numpy.abs', 'np.abs', (['windowVals'], {}), '(windowVals)\n', (47679, 47691), True, 'import numpy as np\n'), ((49934, 49952), 'numpy.abs', 'np.abs', (['windowVals'], {}), '(windowVals)\n', (49940, 49952), True, 'import numpy as np\n'), ((56868, 56879), 'numpy.angle', 'np.angle', (['x'], {}), '(x)\n', (56876, 56879), True, 'import numpy as np\n'), ((34781, 34807), 'numpy.log2', 'np.log2', (['NFFT_density_real'], {}), '(NFFT_density_real)\n', (34788, 34807), True, 'import numpy as np\n'), ((43754, 43777), 'numpy.conjugate', 'np.conjugate', (['(spec1 / 2)'], {}), '(spec1 / 2)\n', (43766, 43777), True, 'import numpy as np\n'), ((54220, 54241), 'numpy.diff', 'np.diff', (['spec'], {'axis': '(1)'}), '(spec, axis=1)\n', (54227, 54241), True, 'import numpy as np\n')] |
# @Author: Ivan
# @LastEdit: 2020/9/25
import os
import random
import cv2 # install
import numpy as np # install
def load_img_from_folder(root, nb_classes, nb_per_class, width, height, depth, train_proportion, valid_proportion,
test_proportion, shuffle=True, rescale=True, normalize=True):
"""function of loading image dataset from folder.
* image dataset's root folder must contain each class's children class folder.
example:
folder 'dataset' contains 'dog' and 'cat' folder.
each children class folder has corresponding images,'dog' folder has 'dog1.jpg','dog2.jpg'.
root/dog/1.png
root/dog/2.png
root/dog/3.png
...
root/cat/1.png
root/cat/2.png
root/cat/3.png
* file path name and image name better be named by english.
Args:
root: image dataset's root path
nb_classes: number of image classes
nb_per_class: number of each class's image
width: width of output image
height: height of output image
depth: depth of image,1 for gray,3 for clolr
train_proportion: the proportion of train dataset
valid_proportion: the proportion of valid dataset
test_proportion: the proportion of test dataset
normalize: images whether need normalized
Returns:
rval:
(train_data, train_label): train data and label
(valid_data, valid_label): valid data and label
(test_data, test_label): test data and label
"""
train_per_class = int(train_proportion * nb_per_class)
valid_per_class = int(valid_proportion * nb_per_class)
test_per_class = int(test_proportion * nb_per_class)
train_number = train_per_class * nb_classes # number of train set
valid_number = valid_per_class * nb_classes # number of valid set
test_number = test_per_class * nb_classes # number of test set
classes = [] # images classes list
dataset = [] # dataset list,including image and label sequences
print('Image classes:')
img_classes = os.listdir(root)
for c, img_class in enumerate(img_classes):
# stop loading dataset when class number is enough
if c == nb_classes:
break
img_class_path = os.path.join(root, img_class)
# skip if not folder
if not os.path.isdir(img_class_path):
continue
print(img_class)
classes.append(img_class)
imgs = os.listdir(img_class_path)
for img in imgs:
# stop loading dataset when image number of each class is enough
if len(dataset) == (c+1)*nb_per_class:
break
img_path = os.path.join(img_class_path, img)
# read image
if depth == 3:
image = cv2.imdecode(np.fromfile(
img_path, dtype=np.uint8), cv2.IMREAD_COLOR) # chinese path color
elif depth == 1:
image = cv2.imdecode(np.fromfile(
img_path, dtype=np.uint8), cv2.cv2.IMREAD_GRAYSCALE) # chinese path gray
# scaling and filtering
try:
# default interpolation = cv2.INTER_LINEAR - Bilinear Interpolation
image = cv2.resize(image, (width, height))
if rescale:
image = cv2.medianBlur(image, 3) # filtering
except:
print(img_path, 'failed to resize!')
# os.remove(img_path)
# print(img_path+' has been deleted!')
continue
if normalize:
image_ndarray = np.asarray(image, dtype='float64') / 255
else:
image_ndarray = np.asarray(image, dtype='float64')
# add single data(including data and label) to dataset array
dataset.append([np.ndarray.flatten(image_ndarray), c])
# image not enough
if len(dataset) < (c+1)*nb_per_class:
print(img_class, 'Image number insufficient!')
raise Exception('Image number insufficient!')
# shuffle the whole dataset
if shuffle:
random.shuffle(dataset)
# construct data set and label set
train_data = [data[0] for data in dataset[:train_number]]
train_label = [data[1] for data in dataset[:train_number]]
train_data = np.array(train_data, dtype='float32')
train_label = np.array(train_label, dtype='uint8')
valid_data = [data[0]
for data in dataset[train_number:train_number + valid_number]]
valid_label = [data[1]
for data in dataset[train_number:train_number + valid_number]]
valid_data = np.array(valid_data, dtype='float32')
valid_label = np.array(valid_label, dtype='uint8')
test_data = [data[0] for data in dataset[train_number + valid_number:]]
test_label = [data[1] for data in dataset[train_number + valid_number:]]
test_data = np.array(test_data, dtype='float32')
test_label = np.array(test_label, dtype='uint8')
# write all classes into 'classes.txt' file
with open('./cfg/classes.cfg', 'w', encoding='utf-8') as f:
for idx, class_ in enumerate(classes):
if idx+1 == len(classes):
f.write(class_ + ' ' + str(idx))
else:
f.write(class_ + ' ' + str(idx) + '\n')
rval = [(train_data, train_label), (valid_data, valid_label),
(test_data, test_label)]
return rval
def img_normalize(path, width, height, gray=True):
"""function of normalizing images.
* resize images and convert to gray.
* image dataset folder must contain each class's children class folder.
example:
folder 'vehicle' contains 'car','train' and 'bicycle' folder,each children class
folder has corresponding images,'car' folder has 'car1.jpg','car2.jpg'.
* file path name and image name better be named by english.
* when detecting faces,'aarcascade_frontalface_default.xml' shoud be included.
Args:
path: images path
width: width of output image
height: height of output image
gray: whether need convert to gray,default need
"""
img_classes = os.listdir(path)
for img_class in img_classes:
img_class_path = os.path.join(path, img_class)
if os.path.isdir(img_class_path):
imgs = os.listdir(img_class_path)
for img in imgs:
img_path = os.path.join(img_class_path, img)
image = cv2.imread(img_path)
# resize
try:
image = cv2.resize(image, (width, height),
interpolation=cv2.INTER_CUBIC)
except:
print(img_path + ' failed to resize!')
os.remove(img_path)
print(img_path + ' has been deleted!')
continue
# convert to gray
if gray:
image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# rewrite image
cv2.imwrite(img_path, image)
print(img_path, 'normalized successfully!')
print('All images normalized successfully!')
def img_rename(path):
"""function of renaming and sorting images.
* traversal folder,rename all images.
example:
'xxx.jpg','xxx.jpg' -> '1.jpg','2.jpg'
Args:
path: images path
"""
classes = os.listdir(path)
for class_ in classes:
number = 1
class_path = os.path.join(path, class_)
imgs = os.listdir(class_path)
for img in imgs:
img_path = os.path.join(class_path, img)
new_img_path = os.path.join(class_path, str(number) + '.jpg')
os.rename(img_path, new_img_path)
print(img_path + '--->' + new_img_path)
number = number + 1
print('All images renamed successfully!')
def main():
pass
if __name__ == '__main__':
main()
| [
"cv2.imwrite",
"numpy.fromfile",
"os.listdir",
"random.shuffle",
"os.rename",
"os.path.join",
"numpy.asarray",
"cv2.medianBlur",
"numpy.array",
"numpy.ndarray.flatten",
"os.path.isdir",
"cv2.cvtColor",
"cv2.resize",
"cv2.imread",
"os.remove"
] | [((2090, 2106), 'os.listdir', 'os.listdir', (['root'], {}), '(root)\n', (2100, 2106), False, 'import os\n'), ((4370, 4407), 'numpy.array', 'np.array', (['train_data'], {'dtype': '"""float32"""'}), "(train_data, dtype='float32')\n", (4378, 4407), True, 'import numpy as np\n'), ((4426, 4462), 'numpy.array', 'np.array', (['train_label'], {'dtype': '"""uint8"""'}), "(train_label, dtype='uint8')\n", (4434, 4462), True, 'import numpy as np\n'), ((4697, 4734), 'numpy.array', 'np.array', (['valid_data'], {'dtype': '"""float32"""'}), "(valid_data, dtype='float32')\n", (4705, 4734), True, 'import numpy as np\n'), ((4753, 4789), 'numpy.array', 'np.array', (['valid_label'], {'dtype': '"""uint8"""'}), "(valid_label, dtype='uint8')\n", (4761, 4789), True, 'import numpy as np\n'), ((4960, 4996), 'numpy.array', 'np.array', (['test_data'], {'dtype': '"""float32"""'}), "(test_data, dtype='float32')\n", (4968, 4996), True, 'import numpy as np\n'), ((5014, 5049), 'numpy.array', 'np.array', (['test_label'], {'dtype': '"""uint8"""'}), "(test_label, dtype='uint8')\n", (5022, 5049), True, 'import numpy as np\n'), ((6226, 6242), 'os.listdir', 'os.listdir', (['path'], {}), '(path)\n', (6236, 6242), False, 'import os\n'), ((7492, 7508), 'os.listdir', 'os.listdir', (['path'], {}), '(path)\n', (7502, 7508), False, 'import os\n'), ((2286, 2315), 'os.path.join', 'os.path.join', (['root', 'img_class'], {}), '(root, img_class)\n', (2298, 2315), False, 'import os\n'), ((2487, 2513), 'os.listdir', 'os.listdir', (['img_class_path'], {}), '(img_class_path)\n', (2497, 2513), False, 'import os\n'), ((4164, 4187), 'random.shuffle', 'random.shuffle', (['dataset'], {}), '(dataset)\n', (4178, 4187), False, 'import random\n'), ((6302, 6331), 'os.path.join', 'os.path.join', (['path', 'img_class'], {}), '(path, img_class)\n', (6314, 6331), False, 'import os\n'), ((6343, 6372), 'os.path.isdir', 'os.path.isdir', (['img_class_path'], {}), '(img_class_path)\n', (6356, 6372), False, 'import os\n'), ((7576, 7602), 'os.path.join', 'os.path.join', (['path', 'class_'], {}), '(path, class_)\n', (7588, 7602), False, 'import os\n'), ((7618, 7640), 'os.listdir', 'os.listdir', (['class_path'], {}), '(class_path)\n', (7628, 7640), False, 'import os\n'), ((2360, 2389), 'os.path.isdir', 'os.path.isdir', (['img_class_path'], {}), '(img_class_path)\n', (2373, 2389), False, 'import os\n'), ((2713, 2746), 'os.path.join', 'os.path.join', (['img_class_path', 'img'], {}), '(img_class_path, img)\n', (2725, 2746), False, 'import os\n'), ((6393, 6419), 'os.listdir', 'os.listdir', (['img_class_path'], {}), '(img_class_path)\n', (6403, 6419), False, 'import os\n'), ((7689, 7718), 'os.path.join', 'os.path.join', (['class_path', 'img'], {}), '(class_path, img)\n', (7701, 7718), False, 'import os\n'), ((7805, 7838), 'os.rename', 'os.rename', (['img_path', 'new_img_path'], {}), '(img_path, new_img_path)\n', (7814, 7838), False, 'import os\n'), ((3270, 3304), 'cv2.resize', 'cv2.resize', (['image', '(width, height)'], {}), '(image, (width, height))\n', (3280, 3304), False, 'import cv2\n'), ((3740, 3774), 'numpy.asarray', 'np.asarray', (['image'], {'dtype': '"""float64"""'}), "(image, dtype='float64')\n", (3750, 3774), True, 'import numpy as np\n'), ((6476, 6509), 'os.path.join', 'os.path.join', (['img_class_path', 'img'], {}), '(img_class_path, img)\n', (6488, 6509), False, 'import os\n'), ((6534, 6554), 'cv2.imread', 'cv2.imread', (['img_path'], {}), '(img_path)\n', (6544, 6554), False, 'import cv2\n'), ((7120, 7148), 'cv2.imwrite', 'cv2.imwrite', (['img_path', 'image'], {}), '(img_path, image)\n', (7131, 7148), False, 'import cv2\n'), ((2836, 2873), 'numpy.fromfile', 'np.fromfile', (['img_path'], {'dtype': 'np.uint8'}), '(img_path, dtype=np.uint8)\n', (2847, 2873), True, 'import numpy as np\n'), ((3361, 3385), 'cv2.medianBlur', 'cv2.medianBlur', (['image', '(3)'], {}), '(image, 3)\n', (3375, 3385), False, 'import cv2\n'), ((3649, 3683), 'numpy.asarray', 'np.asarray', (['image'], {'dtype': '"""float64"""'}), "(image, dtype='float64')\n", (3659, 3683), True, 'import numpy as np\n'), ((3877, 3910), 'numpy.ndarray.flatten', 'np.ndarray.flatten', (['image_ndarray'], {}), '(image_ndarray)\n', (3895, 3910), True, 'import numpy as np\n'), ((6629, 6694), 'cv2.resize', 'cv2.resize', (['image', '(width, height)'], {'interpolation': 'cv2.INTER_CUBIC'}), '(image, (width, height), interpolation=cv2.INTER_CUBIC)\n', (6639, 6694), False, 'import cv2\n'), ((7032, 7071), 'cv2.cvtColor', 'cv2.cvtColor', (['image', 'cv2.COLOR_BGR2GRAY'], {}), '(image, cv2.COLOR_BGR2GRAY)\n', (7044, 7071), False, 'import cv2\n'), ((3002, 3039), 'numpy.fromfile', 'np.fromfile', (['img_path'], {'dtype': 'np.uint8'}), '(img_path, dtype=np.uint8)\n', (3013, 3039), True, 'import numpy as np\n'), ((6837, 6856), 'os.remove', 'os.remove', (['img_path'], {}), '(img_path)\n', (6846, 6856), False, 'import os\n')] |
import numpy as np
import scipy.signal as signal
import matplotlib.pyplot as plt
alpha = 0.5
beta = 0.2
b = np.array( [ 1 - alpha, 0, -( 1 - alpha ) ] )
a = np.array( [ 2, -2 * beta * ( 1 + alpha ), 2 * alpha ] )
w, H = signal.freqz( b, a )
H1 = abs( H )
alpha = 0.5
beta = 0.5
b = np.array( [ 1 - alpha, 0, -( 1 - alpha ) ] )
a = np.array( [ 2, -2 * beta * ( 1 + alpha ), 2 * alpha ] )
w, H = signal.freqz( b, a )
H2 = abs( H )
alpha = 0.5
beta = 0.8
b = np.array( [ 1 - alpha, 0, -( 1 - alpha ) ] )
a = np.array( [ 2, -2 * beta * ( 1 + alpha ), 2 * alpha ] )
w, H = signal.freqz( b, a )
H3 = abs( H )
plt.plot( w, H1, '-', label = r'$\beta$ = 0.2' )
plt.plot( w, H2, '--', label = r'$\beta$ = 0.5' )
plt.plot( w, H3, '-.', label = r'$\beta$ = 0.8' )
plt.legend( loc = 'upper right' )
plt.xlabel( r'$\omega$' )
plt.ylabel( 'Magnitude' )
plt.show( ) | [
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"numpy.array",
"scipy.signal.freqz",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.show"
] | [((109, 147), 'numpy.array', 'np.array', (['[1 - alpha, 0, -(1 - alpha)]'], {}), '([1 - alpha, 0, -(1 - alpha)])\n', (117, 147), True, 'import numpy as np\n'), ((158, 207), 'numpy.array', 'np.array', (['[2, -2 * beta * (1 + alpha), 2 * alpha]'], {}), '([2, -2 * beta * (1 + alpha), 2 * alpha])\n', (166, 207), True, 'import numpy as np\n'), ((221, 239), 'scipy.signal.freqz', 'signal.freqz', (['b', 'a'], {}), '(b, a)\n', (233, 239), True, 'import scipy.signal as signal\n'), ((284, 322), 'numpy.array', 'np.array', (['[1 - alpha, 0, -(1 - alpha)]'], {}), '([1 - alpha, 0, -(1 - alpha)])\n', (292, 322), True, 'import numpy as np\n'), ((333, 382), 'numpy.array', 'np.array', (['[2, -2 * beta * (1 + alpha), 2 * alpha]'], {}), '([2, -2 * beta * (1 + alpha), 2 * alpha])\n', (341, 382), True, 'import numpy as np\n'), ((396, 414), 'scipy.signal.freqz', 'signal.freqz', (['b', 'a'], {}), '(b, a)\n', (408, 414), True, 'import scipy.signal as signal\n'), ((459, 497), 'numpy.array', 'np.array', (['[1 - alpha, 0, -(1 - alpha)]'], {}), '([1 - alpha, 0, -(1 - alpha)])\n', (467, 497), True, 'import numpy as np\n'), ((508, 557), 'numpy.array', 'np.array', (['[2, -2 * beta * (1 + alpha), 2 * alpha]'], {}), '([2, -2 * beta * (1 + alpha), 2 * alpha])\n', (516, 557), True, 'import numpy as np\n'), ((571, 589), 'scipy.signal.freqz', 'signal.freqz', (['b', 'a'], {}), '(b, a)\n', (583, 589), True, 'import scipy.signal as signal\n'), ((607, 651), 'matplotlib.pyplot.plot', 'plt.plot', (['w', 'H1', '"""-"""'], {'label': '"""$\\\\beta$ = 0.2"""'}), "(w, H1, '-', label='$\\\\beta$ = 0.2')\n", (615, 651), True, 'import matplotlib.pyplot as plt\n'), ((656, 701), 'matplotlib.pyplot.plot', 'plt.plot', (['w', 'H2', '"""--"""'], {'label': '"""$\\\\beta$ = 0.5"""'}), "(w, H2, '--', label='$\\\\beta$ = 0.5')\n", (664, 701), True, 'import matplotlib.pyplot as plt\n'), ((706, 751), 'matplotlib.pyplot.plot', 'plt.plot', (['w', 'H3', '"""-."""'], {'label': '"""$\\\\beta$ = 0.8"""'}), "(w, H3, '-.', label='$\\\\beta$ = 0.8')\n", (714, 751), True, 'import matplotlib.pyplot as plt\n'), ((757, 786), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""upper right"""'}), "(loc='upper right')\n", (767, 786), True, 'import matplotlib.pyplot as plt\n'), ((791, 814), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""$\\\\omega$"""'], {}), "('$\\\\omega$')\n", (801, 814), True, 'import matplotlib.pyplot as plt\n'), ((817, 840), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Magnitude"""'], {}), "('Magnitude')\n", (827, 840), True, 'import matplotlib.pyplot as plt\n'), ((844, 854), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (852, 854), True, 'import matplotlib.pyplot as plt\n')] |
# USAGE
# python quantize_example.py
# import the necessary packages
from __future__ import print_function
from ir import BagOfVisualWords
from sklearn.metrics import pairwise
import numpy as np
# randomly generate the vocabulary/cluster centers along with the feature
# vectors -- we'll generate 10 feature vectos containing 6 real-valued
# entries, along with a codebook containing 3 'visual words'
np.random.seed(42)
vocab = np.random.uniform(size=(3, 6))
features = np.random.uniform(size=(10, 6))
print("[INFO] vocabulary:\n{}\n".format(vocab))
print("[INFO] features:\n{}\n".format(features))
# initialize our bag of visual words histogram -- it will contain 3 entries,
# one for each of the possible visual words
hist = np.zeros((3,), dtype="int32")
# loop over the inidividual feature vectors
for (i, f) in enumerate(features):
# compute the Euclidean distance between the current feature vector
# and the 3 visual words; then, find the index of the visual word
# with the smallest distance
D = pairwise.euclidean_distances(f.reshape(1, -1), Y=vocab)
j = np.argmin(D)
print("[INFO] Closest visual word to feature #{}: {}".format(i, j))
hist[j] += 1
print("[INFO] Updated histogram: {}".format(hist))
# this apply our `BagOfVisualWords` class and make this process super
# speedy
bovw = BagOfVisualWords(vocab, sparse=False)
hist = bovw.describe(features)
print("[INFO] BOVW histogram: {}".format(hist)) | [
"ir.BagOfVisualWords",
"numpy.zeros",
"numpy.random.seed",
"numpy.random.uniform",
"numpy.argmin"
] | [((403, 421), 'numpy.random.seed', 'np.random.seed', (['(42)'], {}), '(42)\n', (417, 421), True, 'import numpy as np\n'), ((430, 460), 'numpy.random.uniform', 'np.random.uniform', ([], {'size': '(3, 6)'}), '(size=(3, 6))\n', (447, 460), True, 'import numpy as np\n'), ((472, 503), 'numpy.random.uniform', 'np.random.uniform', ([], {'size': '(10, 6)'}), '(size=(10, 6))\n', (489, 503), True, 'import numpy as np\n'), ((730, 759), 'numpy.zeros', 'np.zeros', (['(3,)'], {'dtype': '"""int32"""'}), "((3,), dtype='int32')\n", (738, 759), True, 'import numpy as np\n'), ((1308, 1345), 'ir.BagOfVisualWords', 'BagOfVisualWords', (['vocab'], {'sparse': '(False)'}), '(vocab, sparse=False)\n', (1324, 1345), False, 'from ir import BagOfVisualWords\n'), ((1072, 1084), 'numpy.argmin', 'np.argmin', (['D'], {}), '(D)\n', (1081, 1084), True, 'import numpy as np\n')] |
"""
Copyright (c) 2018-2020 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
from copy import deepcopy
from pathlib import Path
import warnings
import numpy as np
from .annotation_converters import BaseFormatConverter, save_annotation, make_subset, analyze_dataset
from .config import (
ConfigValidator,
StringField,
PathField,
ListField,
DictField,
BaseField,
NumberField,
ConfigError,
BoolField
)
from .utils import JSONDecoderWithAutoConversion, read_json, get_path, contains_all, set_image_metadata, OrderedSet
from .representation import (
BaseRepresentation, ReIdentificationClassificationAnnotation, ReIdentificationAnnotation, PlaceRecognitionAnnotation
)
from .data_readers import DataReaderField, REQUIRES_ANNOTATIONS
from .logging import print_info
class DatasetConfig(ConfigValidator):
"""
Specifies configuration structure for dataset
"""
name = StringField()
annotation = PathField(optional=True, check_exists=False)
data_source = PathField(optional=True, check_exists=False)
dataset_meta = PathField(optional=True, check_exists=False)
metrics = ListField(allow_empty=False, optional=True)
postprocessing = ListField(allow_empty=False, optional=True)
preprocessing = ListField(allow_empty=False, optional=True)
reader = DataReaderField(optional=True)
annotation_conversion = DictField(optional=True)
subsample_size = BaseField(optional=True)
shuffle = BoolField(optional=True)
subsample_seed = NumberField(value_type=int, min_value=0, optional=True)
analyze_dataset = BaseField(optional=True)
segmentation_masks_source = PathField(is_directory=True, optional=True)
additional_data_source = PathField(is_directory=True, optional=True)
batch = NumberField(value_type=int, min_value=1, optional=True)
_profile = BoolField(optional=True, default=False)
_report_type = StringField(optional=True, choices=['json', 'csv'])
_ie_preprocessing = BoolField(optional=True, default=False)
class Dataset:
def __init__(self, config_entry, delayed_annotation_loading=False):
self._config = config_entry
self.batch = self.config.get('batch')
self.iteration = 0
dataset_config = DatasetConfig('Dataset')
dataset_config.validate(self._config)
if not delayed_annotation_loading:
self._load_annotation()
def _load_annotation(self):
annotation, meta = None, None
use_converted_annotation = True
if 'annotation' in self._config:
annotation_file = Path(self._config['annotation'])
if annotation_file.exists():
print_info('Annotation for {dataset_name} dataset will be loaded from {file}'.format(
dataset_name=self._config['name'], file=annotation_file))
annotation = read_annotation(get_path(annotation_file))
meta = self._load_meta()
use_converted_annotation = False
if not annotation and 'annotation_conversion' in self._config:
print_info("Annotation conversion for {dataset_name} dataset has been started".format(
dataset_name=self._config['name']))
print_info("Parameters to be used for conversion:")
for key, value in self._config['annotation_conversion'].items():
print_info('{key}: {value}'.format(key=key, value=value))
annotation, meta = self._convert_annotation()
if annotation:
print_info("Annotation conversion for {dataset_name} dataset has been finished".format(
dataset_name=self._config['name']))
if not annotation:
raise ConfigError('path to converted annotation or data for conversion should be specified')
subsample_size = self._config.get('subsample_size')
if subsample_size is not None:
subsample_seed = self._config.get('subsample_seed', 666)
shuffle = self._config.get('shuffle', True)
annotation = create_subset(annotation, subsample_size, subsample_seed, shuffle)
if self._config.get('analyze_dataset', False):
if self._config.get('segmentation_masks_source'):
meta['segmentation_masks_source'] = self._config.get('segmentation_masks_source')
meta = analyze_dataset(annotation, meta)
if meta.get('segmentation_masks_source'):
del meta['segmentation_masks_source']
if use_converted_annotation and contains_all(self._config, ['annotation', 'annotation_conversion']):
annotation_name = self._config['annotation']
meta_name = self._config.get('dataset_meta')
if meta_name:
meta_name = Path(meta_name)
print_info("{dataset_name} dataset metadata will be saved to {file}".format(
dataset_name=self._config['name'], file=meta_name))
print_info('Converted annotation for {dataset_name} dataset will be saved to {file}'.format(
dataset_name=self._config['name'], file=Path(annotation_name)))
save_annotation(annotation, meta, Path(annotation_name), meta_name)
self._annotation = annotation
self._meta = meta or {}
self.name = self._config.get('name')
self.subset = None
@property
def annotation(self):
return self._annotation
@property
def config(self):
return deepcopy(self._config) #read-only
@property
def identifiers(self):
return [ann.identifier for ann in self.annotation]
def __len__(self):
if self.subset:
return len(self.subset)
return len(self._annotation)
@property
def metadata(self):
return deepcopy(self._meta) #read-only
@property
def labels(self):
return self._meta.get('label_map', {})
@property
def size(self):
return self.__len__()
@property
def full_size(self):
return len(self._annotation)
def __getitem__(self, item):
if self.batch is None:
self.batch = 1
if self.size <= item * self.batch:
raise IndexError
batch_start = item * self.batch
batch_end = min(self.size, batch_start + self.batch)
if self.subset:
batch_ids = self.subset[batch_start:batch_end]
return batch_ids, [self._annotation[idx] for idx in batch_ids]
batch_ids = range(batch_start, batch_end)
return batch_ids, self._annotation[batch_start:batch_end]
def make_subset(self, ids=None, start=0, step=1, end=None, accept_pairs=False):
pairwise_subset = isinstance(
self._annotation[0], (
ReIdentificationAnnotation, ReIdentificationClassificationAnnotation, PlaceRecognitionAnnotation
)
)
if ids:
self.subset = ids if not pairwise_subset else self._make_subset_pairwise(ids, accept_pairs)
return
if not end:
end = self.size
ids = range(start, end, step)
self.subset = ids if not pairwise_subset else self._make_subset_pairwise(ids, accept_pairs)
def _make_subset_pairwise(self, ids, add_pairs=False):
def reid_pairwise_subset(pairs_set, subsample_set, ids):
identifier_to_index = {annotation.identifier: index for index, annotation in enumerate(self._annotation)}
for idx in ids:
subsample_set.add(idx)
current_annotation = self._annotation[idx]
positive_pairs = [
identifier_to_index[pair_identifier] for pair_identifier in current_annotation.positive_pairs
]
pairs_set |= positive_pairs
negative_pairs = [
identifier_to_index[pair_identifier] for pair_identifier in current_annotation.positive_pairs
]
pairs_set |= negative_pairs
return pairs_set, subsample_set
def reid_subset(pairs_set, subsample_set, ids):
for idx in ids:
subsample_set.add(idx)
selected_annotation = self._annotation[idx]
if not selected_annotation.query:
query_for_person = [
idx for idx, annotation in enumerate(self._annotation)
if annotation.person_id == selected_annotation.person_id and annotation.query
]
pairs_set |= OrderedSet(query_for_person)
else:
gallery_for_person = [
idx for idx, annotation in enumerate(self._annotation)
if annotation.person_id == selected_annotation.person_id and not annotation.query
]
pairs_set |= OrderedSet(gallery_for_person)
return pairs_set, subsample_set
def ibl_subset(pairs_set, subsample_set, ids):
queries_ids = [idx for idx, ann in enumerate(self._annotation) if ann.query]
gallery_ids = [idx for idx, ann in enumerate(self._annotation) if not ann.query]
subset_id_to_q_id = {s_id: idx for idx, s_id in enumerate(queries_ids)}
subset_id_to_g_id = {s_id: idx for idx, s_id in enumerate(gallery_ids)}
queries_loc = [ann.coords for ann in self._annotation if ann.query]
gallery_loc = [ann.coords for ann in self._annotation if not ann.query]
dist_mat = np.zeros((len(queries_ids), len(gallery_ids)))
for idx, query_loc in enumerate(queries_loc):
dist_mat[idx] = np.linalg.norm(np.array(query_loc) - np.array(gallery_loc), axis=1)
for idx in ids:
if idx in subset_id_to_q_id:
pair = gallery_ids[np.argmin(dist_mat[subset_id_to_q_id[idx]])]
else:
pair = queries_ids[np.argmin(dist_mat[:, subset_id_to_g_id[idx]])]
subsample_set.add(idx)
pairs_set.add(pair)
return pairs_set, subsample_set
realisation = [
(PlaceRecognitionAnnotation, ibl_subset),
(ReIdentificationClassificationAnnotation, reid_pairwise_subset),
(ReIdentificationAnnotation, reid_subset),
]
subsample_set = OrderedSet()
pairs_set = OrderedSet()
for (dtype, func) in realisation:
if isinstance(self._annotation[0], dtype):
pairs_set, subsample_set = func(pairs_set, subsample_set, ids)
break
if add_pairs:
subsample_set |= pairs_set
return list(subsample_set)
def set_annotation_metadata(self, annotation, image, data_source):
set_image_metadata(annotation, image)
annotation.set_data_source(data_source)
segmentation_mask_source = self.config.get('segmentation_masks_source')
annotation.set_segmentation_mask_source(segmentation_mask_source)
annotation.set_additional_data_source(self.config.get('additional_data_source'))
annotation.set_dataset_metadata(self.metadata)
def _load_meta(self):
meta = None
meta_data_file = self._config.get('dataset_meta')
if meta_data_file:
print_info('{dataset_name} dataset metadata will be loaded from {file}'.format(
dataset_name=self._config['name'], file=meta_data_file))
meta = read_json(meta_data_file, cls=JSONDecoderWithAutoConversion)
return meta
def _convert_annotation(self):
conversion_params = self._config.get('annotation_conversion')
converter = conversion_params['converter']
annotation_converter = BaseFormatConverter.provide(converter, conversion_params)
results = annotation_converter.convert()
annotation = results.annotations
meta = results.meta
errors = results.content_check_errors
if errors:
warnings.warn('Following problems were found during conversion:\n{}'.format('\n'.join(errors)))
return annotation, meta
def reset(self, reload_annotation=False):
self.subset = None
if reload_annotation:
self._load_annotation()
def set_annotation(self, annotation):
subsample_size = self._config.get('subsample_size')
if subsample_size is not None:
subsample_seed = self._config.get('subsample_seed', 666)
annotation = create_subset(annotation, subsample_size, subsample_seed)
if self._config.get('analyze_dataset', False):
if self._config.get('segmentation_masks_source'):
self.metadata['segmentation_masks_source'] = self._config.get('segmentation_masks_source')
self.metadata = analyze_dataset(annotation, self.metadata)
if self.metadata.get('segmentation_masks_source'):
del self.metadata['segmentation_masks_source']
self._annotation = annotation
self.name = self._config.get('name')
self.subset = None
def provide_data_info(self, reader, annotations):
for ann in annotations:
input_data = reader(ann.identifier)
self.set_annotation_metadata(ann, input_data, reader.data_source)
return annotations
def read_annotation(annotation_file: Path):
annotation_file = get_path(annotation_file)
result = []
with annotation_file.open('rb') as file:
while True:
try:
result.append(BaseRepresentation.load(file))
except EOFError:
break
return result
def create_subset(annotation, subsample_size, subsample_seed, shuffle=True):
if isinstance(subsample_size, str):
if subsample_size.endswith('%'):
try:
subsample_size = float(subsample_size[:-1])
except ValueError:
raise ConfigError('invalid value for subsample_size: {}'.format(subsample_size))
if subsample_size <= 0:
raise ConfigError('subsample_size should be > 0')
subsample_size *= len(annotation) / 100
subsample_size = int(subsample_size) or 1
try:
subsample_size = int(subsample_size)
except ValueError:
raise ConfigError('invalid value for subsample_size: {}'.format(subsample_size))
if subsample_size < 1:
raise ConfigError('subsample_size should be > 0')
return make_subset(annotation, subsample_size, subsample_seed, shuffle)
class DatasetWrapper:
def __init__(self, data_reader, annotation_reader=None, tag='', dataset_config=None):
self.tag = tag
self.data_reader = data_reader
self.annotation_reader = annotation_reader
self._batch = 1 if not annotation_reader else annotation_reader.batch
self.subset = None
self.dataset_config = dataset_config or {}
if not annotation_reader:
self._identifiers = [file.name for file in self.data_reader.data_source.glob('*')]
def __getitem__(self, item):
if self.batch is None:
self.batch = 1
if self.size <= item * self.batch:
raise IndexError
batch_annotation = []
if self.annotation_reader:
batch_annotation_ids, batch_annotation = self.annotation_reader[item]
batch_identifiers = [annotation.identifier for annotation in batch_annotation]
batch_input = [self.data_reader(identifier=identifier) for identifier in batch_identifiers]
for annotation, input_data in zip(batch_annotation, batch_input):
set_image_metadata(annotation, input_data)
annotation.set_data_source(self.data_reader.data_source)
segmentation_mask_source = self.annotation_reader.config.get('segmentation_masks_source')
annotation.set_segmentation_mask_source(segmentation_mask_source)
annotation.set_additional_data_source(self.annotation_reader.config.get('additional_data_source'))
return batch_annotation_ids, batch_annotation, batch_input, batch_identifiers
batch_start = item * self.batch
batch_end = min(self.size, batch_start + self.batch)
batch_input_ids = self.subset[batch_start:batch_end] if self.subset else range(batch_start, batch_end)
batch_identifiers = [self._identifiers[idx] for idx in batch_input_ids]
batch_input = [self.data_reader(identifier=identifier) for identifier in batch_identifiers]
return batch_input_ids, batch_annotation, batch_input, batch_identifiers
def __len__(self):
if self.annotation_reader:
return self.annotation_reader.size
if self.subset:
return len(self.subset)
return len(self._identifiers)
def make_subset(self, ids=None, start=0, step=1, end=None, accept_pairs=False):
if self.annotation_reader:
self.annotation_reader.make_subset(ids, start, step, end, accept_pairs)
if ids:
self.subset = ids
return
if not end:
end = self.size
self.subset = range(start, end, step)
if self.data_reader.name in REQUIRES_ANNOTATIONS:
self.data_reader.subset = self.subset
@property
def batch(self):
return self._batch
@batch.setter
def batch(self, batch):
if self.annotation_reader:
self.annotation_reader.batch = batch
self._batch = batch
def reset(self, reload_annotation=False):
if self.subset:
self.subset = None
if self.annotation_reader:
self.annotation_reader.reset(reload_annotation)
self.data_reader.reset()
@property
def full_size(self):
if self.annotation_reader:
return self.annotation_reader.full_size
return len(self._identifiers)
@property
def size(self):
return self.__len__()
@property
def multi_infer(self):
return getattr(self.data_reader, 'multi_infer', False)
| [
"numpy.argmin",
"numpy.array",
"pathlib.Path",
"copy.deepcopy"
] | [((5995, 6017), 'copy.deepcopy', 'deepcopy', (['self._config'], {}), '(self._config)\n', (6003, 6017), False, 'from copy import deepcopy\n'), ((6305, 6325), 'copy.deepcopy', 'deepcopy', (['self._meta'], {}), '(self._meta)\n', (6313, 6325), False, 'from copy import deepcopy\n'), ((3077, 3109), 'pathlib.Path', 'Path', (["self._config['annotation']"], {}), "(self._config['annotation'])\n", (3081, 3109), False, 'from pathlib import Path\n'), ((5281, 5296), 'pathlib.Path', 'Path', (['meta_name'], {}), '(meta_name)\n', (5285, 5296), False, 'from pathlib import Path\n'), ((5693, 5714), 'pathlib.Path', 'Path', (['annotation_name'], {}), '(annotation_name)\n', (5697, 5714), False, 'from pathlib import Path\n'), ((5623, 5644), 'pathlib.Path', 'Path', (['annotation_name'], {}), '(annotation_name)\n', (5627, 5644), False, 'from pathlib import Path\n'), ((10224, 10243), 'numpy.array', 'np.array', (['query_loc'], {}), '(query_loc)\n', (10232, 10243), True, 'import numpy as np\n'), ((10246, 10267), 'numpy.array', 'np.array', (['gallery_loc'], {}), '(gallery_loc)\n', (10254, 10267), True, 'import numpy as np\n'), ((10389, 10432), 'numpy.argmin', 'np.argmin', (['dist_mat[subset_id_to_q_id[idx]]'], {}), '(dist_mat[subset_id_to_q_id[idx]])\n', (10398, 10432), True, 'import numpy as np\n'), ((10495, 10541), 'numpy.argmin', 'np.argmin', (['dist_mat[:, subset_id_to_g_id[idx]]'], {}), '(dist_mat[:, subset_id_to_g_id[idx]])\n', (10504, 10541), True, 'import numpy as np\n')] |
import os
import math
import torch
import numpy as np
class EvaluationSinhalaSongsDataset(torch.utils.data.Dataset):
def __init__(self, root_dir, trim_seconds=10, indexing=False):
self.dir = root_dir
self.feature_list = sorted(os.listdir(self.dir))
self.trim_seconds = trim_seconds
self.indexing = indexing
self.divisor = 1 if indexing else 10
length = len(self.feature_list)
block_1 = math.floor((length/5.0) * 0.6) * 5 # 60% of originals
block_2 = math.floor((length/5.0) * 0.8) * 5 # 80% of originals
start_index = block_1
end_index = block_2
self.feature_list = self.feature_list[start_index:end_index]
def __len__(self):
return len(self.feature_list) * self.divisor
def __getitem__(self, idx):
if torch.is_tensor(idx):
idx = idx.tolist()
file_id = idx // self.divisor
song_id = self.feature_list[file_id].split(".")[0]
offset_id = idx % self.divisor
song_path = os.path.join(self.dir, self.feature_list[file_id])
_, features = np.load(song_path, allow_pickle=True)
# mfccs = torch.from_numpy(np.load(song_path))
trim_frames = self.trim_seconds * 100
# mfccs = mfccs[:, :trim_frames] # trim song to given number of seconds
all_mfccs = []
features = [features[offset_id]]
for mfccs in features:
# trim song to given number of seconds
mfccs = torch.from_numpy(mfccs[:, :trim_frames])
# converting to shape [M_number_of_mfcc_coefficients, I_MFCC_blocks, T_number_of_steps]
mfccs = mfccs.view(13, -1, 100)
# converting to shape [I_MFCC_blocks, T_number_of_steps, M_number_of_mfcc_coefficients]
mfccs = mfccs.permute(1, 2, 0)
all_mfccs.append(mfccs)
return int(song_id), torch.cat(all_mfccs).float()
| [
"os.listdir",
"math.floor",
"os.path.join",
"torch.from_numpy",
"torch.is_tensor",
"numpy.load",
"torch.cat"
] | [((828, 848), 'torch.is_tensor', 'torch.is_tensor', (['idx'], {}), '(idx)\n', (843, 848), False, 'import torch\n'), ((1039, 1089), 'os.path.join', 'os.path.join', (['self.dir', 'self.feature_list[file_id]'], {}), '(self.dir, self.feature_list[file_id])\n', (1051, 1089), False, 'import os\n'), ((1112, 1149), 'numpy.load', 'np.load', (['song_path'], {'allow_pickle': '(True)'}), '(song_path, allow_pickle=True)\n', (1119, 1149), True, 'import numpy as np\n'), ((249, 269), 'os.listdir', 'os.listdir', (['self.dir'], {}), '(self.dir)\n', (259, 269), False, 'import os\n'), ((450, 480), 'math.floor', 'math.floor', (['(length / 5.0 * 0.6)'], {}), '(length / 5.0 * 0.6)\n', (460, 480), False, 'import math\n'), ((523, 553), 'math.floor', 'math.floor', (['(length / 5.0 * 0.8)'], {}), '(length / 5.0 * 0.8)\n', (533, 553), False, 'import math\n'), ((1502, 1542), 'torch.from_numpy', 'torch.from_numpy', (['mfccs[:, :trim_frames]'], {}), '(mfccs[:, :trim_frames])\n', (1518, 1542), False, 'import torch\n'), ((1897, 1917), 'torch.cat', 'torch.cat', (['all_mfccs'], {}), '(all_mfccs)\n', (1906, 1917), False, 'import torch\n')] |
import os
import numpy as np
from utils.utils import json_from_file, get_files_from_dir, get_module_attr
# get list of themes (excluding python system files)
def get_themes(dir):
theme_dir = 'themes/{dir}'.format(dir=dir)
themes = get_files_from_dir(theme_dir)
return themes
# pick random theme from a libraries theme list
def get_random_theme(dir):
themes = get_themes(dir)
theme_file_name = np.random.choice(themes)
return theme_file_name
# read in a theme from a libraries theme directory
def get_theme_object(file_path, dir):
file_name, file_extension = os.path.splitext(file_path)
theme = {}
# json theme objects
if file_extension == '.json':
theme = json_from_file('themes/{dir}/{file_path}'.format(file_path=file_path, dir=dir))
# class-based themes
elif file_extension == '.py':
theme_class = get_module_attr('themes.{dir}.{file_name}'.format(dir=dir, file_name=file_name), 'Theme')
theme = theme_class
return theme
| [
"numpy.random.choice",
"os.path.splitext",
"utils.utils.get_files_from_dir"
] | [((240, 269), 'utils.utils.get_files_from_dir', 'get_files_from_dir', (['theme_dir'], {}), '(theme_dir)\n', (258, 269), False, 'from utils.utils import json_from_file, get_files_from_dir, get_module_attr\n'), ((415, 439), 'numpy.random.choice', 'np.random.choice', (['themes'], {}), '(themes)\n', (431, 439), True, 'import numpy as np\n'), ((589, 616), 'os.path.splitext', 'os.path.splitext', (['file_path'], {}), '(file_path)\n', (605, 616), False, 'import os\n')] |
# This artist can be used to deal with the sampling of the data as well as any
# RGB blending.
from __future__ import absolute_import
import numpy as np
from glue.utils import view_shape
from matplotlib.colors import ColorConverter, Colormap
from astropy.visualization import (LinearStretch, SqrtStretch, AsinhStretch,
LogStretch, ManualInterval, ContrastBiasStretch)
__all__ = ['CompositeArray']
COLOR_CONVERTER = ColorConverter()
STRETCHES = {
'linear': LinearStretch,
'sqrt': SqrtStretch,
'arcsinh': AsinhStretch,
'log': LogStretch
}
class CompositeArray(object):
def __init__(self, **kwargs):
# We keep a dictionary of layers. The key should be the UUID of the
# layer artist, and the values should be dictionaries that contain
# 'zorder', 'visible', 'array', 'color', and 'alpha'.
self.layers = {}
self._first = True
def allocate(self, uuid):
self.layers[uuid] = {'zorder': 0,
'visible': True,
'array': None,
'shape': None,
'color': '0.5',
'alpha': 1,
'clim': (0, 1),
'contrast': 1,
'bias': 0.5,
'stretch': 'linear'}
def deallocate(self, uuid):
self.layers.pop(uuid)
def set(self, uuid, **kwargs):
for key, value in kwargs.items():
if key not in self.layers[uuid]:
raise KeyError("Unknown key: {0}".format(key))
else:
self.layers[uuid][key] = value
@property
def shape(self):
for layer in self.layers.values():
if callable(layer['shape']):
shape = layer['shape']()
elif layer['shape'] is not None:
shape = layer['shape']
elif callable(layer['array']):
array = layer['array']()
if array is None:
return None
else:
shape = array.shape
else:
shape = layer['array'].shape
if shape is not None:
return shape
return None
def __getitem__(self, view):
img = None
visible_layers = 0
for uuid in sorted(self.layers, key=lambda x: self.layers[x]['zorder']):
layer = self.layers[uuid]
if not layer['visible']:
continue
interval = ManualInterval(*layer['clim'])
contrast_bias = ContrastBiasStretch(layer['contrast'], layer['bias'])
if callable(layer['array']):
array = layer['array'](view=view)
else:
array = layer['array']
if array is None:
continue
if not callable(layer['array']):
array = array[view]
if np.isscalar(array):
scalar = True
array = np.atleast_2d(array)
else:
scalar = False
data = STRETCHES[layer['stretch']]()(contrast_bias(interval(array)))
if isinstance(layer['color'], Colormap):
if img is None:
img = np.ones(data.shape + (4,))
# Compute colormapped image
plane = layer['color'](data)
alpha_plane = layer['alpha'] * plane[:, :, 3]
# Use traditional alpha compositing
plane[:, :, 0] = plane[:, :, 0] * alpha_plane
plane[:, :, 1] = plane[:, :, 1] * alpha_plane
plane[:, :, 2] = plane[:, :, 2] * alpha_plane
img[:, :, 0] *= (1 - alpha_plane)
img[:, :, 1] *= (1 - alpha_plane)
img[:, :, 2] *= (1 - alpha_plane)
img[:, :, 3] = 1
else:
if img is None:
img = np.zeros(data.shape + (4,))
# Get color and pre-multiply by alpha values
color = COLOR_CONVERTER.to_rgba_array(layer['color'])[0]
color *= layer['alpha']
# We should treat NaN values as zero (post-stretch), which means
# that those pixels don't contribute towards the final image.
reset = np.isnan(data)
if np.any(reset):
data[reset] = 0.
plane = data[:, :, np.newaxis] * color
plane[:, :, 3] = 1
visible_layers += 1
if scalar:
plane = plane[0, 0]
img += plane
if img is None:
if self.shape is None:
return None
else:
img = np.zeros(view_shape(self.shape, view) + (4,))
else:
img = np.clip(img, 0, 1)
return img
@property
def dtype(self):
return np.float
@property
def ndim(self):
return 2
@property
def size(self):
return np.product(self.shape)
def __contains__(self, item):
return item in self.layers
| [
"numpy.product",
"numpy.clip",
"matplotlib.colors.ColorConverter",
"numpy.atleast_2d",
"astropy.visualization.ContrastBiasStretch",
"numpy.isscalar",
"numpy.ones",
"numpy.any",
"glue.utils.view_shape",
"numpy.zeros",
"numpy.isnan",
"astropy.visualization.ManualInterval"
] | [((457, 473), 'matplotlib.colors.ColorConverter', 'ColorConverter', ([], {}), '()\n', (471, 473), False, 'from matplotlib.colors import ColorConverter, Colormap\n'), ((5140, 5162), 'numpy.product', 'np.product', (['self.shape'], {}), '(self.shape)\n', (5150, 5162), True, 'import numpy as np\n'), ((2610, 2640), 'astropy.visualization.ManualInterval', 'ManualInterval', (["*layer['clim']"], {}), "(*layer['clim'])\n", (2624, 2640), False, 'from astropy.visualization import LinearStretch, SqrtStretch, AsinhStretch, LogStretch, ManualInterval, ContrastBiasStretch\n'), ((2669, 2722), 'astropy.visualization.ContrastBiasStretch', 'ContrastBiasStretch', (["layer['contrast']", "layer['bias']"], {}), "(layer['contrast'], layer['bias'])\n", (2688, 2722), False, 'from astropy.visualization import LinearStretch, SqrtStretch, AsinhStretch, LogStretch, ManualInterval, ContrastBiasStretch\n'), ((3026, 3044), 'numpy.isscalar', 'np.isscalar', (['array'], {}), '(array)\n', (3037, 3044), True, 'import numpy as np\n'), ((4939, 4957), 'numpy.clip', 'np.clip', (['img', '(0)', '(1)'], {}), '(img, 0, 1)\n', (4946, 4957), True, 'import numpy as np\n'), ((3100, 3120), 'numpy.atleast_2d', 'np.atleast_2d', (['array'], {}), '(array)\n', (3113, 3120), True, 'import numpy as np\n'), ((4433, 4447), 'numpy.isnan', 'np.isnan', (['data'], {}), '(data)\n', (4441, 4447), True, 'import numpy as np\n'), ((4467, 4480), 'numpy.any', 'np.any', (['reset'], {}), '(reset)\n', (4473, 4480), True, 'import numpy as np\n'), ((3365, 3391), 'numpy.ones', 'np.ones', (['(data.shape + (4,))'], {}), '(data.shape + (4,))\n', (3372, 3391), True, 'import numpy as np\n'), ((4046, 4073), 'numpy.zeros', 'np.zeros', (['(data.shape + (4,))'], {}), '(data.shape + (4,))\n', (4054, 4073), True, 'import numpy as np\n'), ((4870, 4898), 'glue.utils.view_shape', 'view_shape', (['self.shape', 'view'], {}), '(self.shape, view)\n', (4880, 4898), False, 'from glue.utils import view_shape\n')] |
# Copyright The PyTorch Lightning team.
#
# 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 logging
import os
import shutil
import signal
import subprocess
import sys
import tempfile
import time
from pathlib import Path
from time import sleep
from typing import Any, Dict, List, Optional, Union
import __main__
import numpy as np
import torch
import torch.distributed
from torch.nn import Module
from torch.nn.parallel.distributed import DistributedDataParallel
import pytorch_lightning as pl
from pytorch_lightning.core.optimizer import _convert_to_lightning_optimizers, LightningOptimizer
from pytorch_lightning.overrides import LightningDistributedModule
from pytorch_lightning.overrides.distributed import prepare_for_backward
from pytorch_lightning.plugins.environments.cluster_environment import ClusterEnvironment
from pytorch_lightning.plugins.io.checkpoint_plugin import CheckpointIO
from pytorch_lightning.plugins.precision import PrecisionPlugin
from pytorch_lightning.strategies.parallel import ParallelStrategy
from pytorch_lightning.trainer.states import TrainerFn
from pytorch_lightning.utilities import (
_FAIRSCALE_AVAILABLE,
_HYDRA_AVAILABLE,
_IS_WINDOWS,
_TORCH_GREATER_EQUAL_1_8,
_TORCH_GREATER_EQUAL_1_9,
_TORCH_GREATER_EQUAL_1_10,
rank_zero_warn,
)
from pytorch_lightning.utilities.distributed import _revert_sync_batchnorm, distributed_available
from pytorch_lightning.utilities.distributed import group as _group
from pytorch_lightning.utilities.distributed import (
init_dist_connection,
rank_zero_only,
ReduceOp,
sync_ddp_if_available,
)
from pytorch_lightning.utilities.enums import _StrategyType
from pytorch_lightning.utilities.exceptions import DeadlockDetectedException, MisconfigurationException
from pytorch_lightning.utilities.seed import reset_seed
from pytorch_lightning.utilities.types import STEP_OUTPUT
if _FAIRSCALE_AVAILABLE:
from fairscale.optim import OSS
if _HYDRA_AVAILABLE:
from hydra.core.hydra_config import HydraConfig
from hydra.utils import get_original_cwd, to_absolute_path
if _TORCH_GREATER_EQUAL_1_8:
from pytorch_lightning.utilities.distributed import register_ddp_comm_hook
log = logging.getLogger(__name__)
class DDPStrategy(ParallelStrategy):
"""Plugin for multi-process single-device training on one or multiple nodes.
The main process in each node spawns N-1 child processes via :func:`subprocess.Popen`, where N is the number of
devices (e.g. GPU) per node. It is very similar to how :mod:`torch.distributed.launch` launches processes.
"""
distributed_backend = _StrategyType.DDP
def __init__(
self,
accelerator: Optional["pl.accelerators.accelerator.Accelerator"] = None,
parallel_devices: Optional[List[torch.device]] = None,
cluster_environment: Optional[ClusterEnvironment] = None,
checkpoint_io: Optional[CheckpointIO] = None,
precision_plugin: Optional[PrecisionPlugin] = None,
ddp_comm_state: Optional[object] = None,
ddp_comm_hook: Optional[callable] = None,
ddp_comm_wrapper: Optional[callable] = None,
model_averaging_period: Optional[int] = None,
**kwargs: Union[Any, Dict[str, Any]],
) -> None:
super().__init__(
accelerator=accelerator,
parallel_devices=parallel_devices,
cluster_environment=cluster_environment,
checkpoint_io=checkpoint_io,
precision_plugin=precision_plugin,
)
log.detail(f"{self.__class__.__name__}: initializing DDP plugin")
self.interactive_ddp_procs = []
self._num_nodes = 1
self.sync_batchnorm = False
self.num_processes = len(self.parallel_devices) if self.parallel_devices is not None else 0
self._ddp_kwargs = kwargs
self._ddp_comm_state = ddp_comm_state
self._ddp_comm_hook = ddp_comm_hook
self._ddp_comm_wrapper = ddp_comm_wrapper
self._model_averaging_period = model_averaging_period
self._pids: Optional[List[int]] = None
self._sync_dir: Optional[str] = None
self._rank_0_has_called_call_children_scripts: bool = False
self.set_world_ranks()
@property
def is_distributed(self) -> bool:
return True
@property
def root_device(self) -> torch.device:
return self.parallel_devices[self.local_rank]
@property
def num_nodes(self) -> int:
return self._num_nodes
@num_nodes.setter
def num_nodes(self, num_nodes: int) -> None:
# note that world ranks is related to num_nodes, when resetting it, need to reset world ranks
self._num_nodes = num_nodes
self.set_world_ranks()
@property
def distributed_sampler_kwargs(self):
distributed_sampler_kwargs = dict(num_replicas=(self.num_nodes * self.num_processes), rank=self.global_rank)
return distributed_sampler_kwargs
@property
def _is_single_process_single_device(self) -> bool:
return True
def setup_environment(self) -> None:
# start the other scripts
if not self.cluster_environment.creates_processes_externally:
self._call_children_scripts()
self.setup_distributed()
super().setup_environment()
def setup(self, trainer: "pl.Trainer") -> None:
super().setup(trainer)
# share ddp pids to all processes
self._rank_0_has_called_call_children_scripts = self.broadcast(self._rank_0_has_called_call_children_scripts)
if self._should_run_deadlock_detection():
self._share_information_to_prevent_deadlock()
# move the model to the correct device
self.model_to_device()
if self.sync_batchnorm:
self.model = self.configure_sync_batchnorm(self.model)
# skip wrapping the model if we are not fitting as no gradients need to be exchanged
trainer_fn = self.lightning_module.trainer.state.fn
if trainer_fn == TrainerFn.FITTING:
self.configure_ddp()
def _setup_model(self, model: Module) -> DistributedDataParallel:
"""Wraps the model into a :class:`~torch.nn.parallel.distributed.DistributedDataParallel` module."""
device_ids = self.determine_ddp_device_ids()
log.detail(f"setting up DDP model with device ids: {device_ids}, kwargs: {self._ddp_kwargs}")
return DistributedDataParallel(module=model, device_ids=device_ids, **self._ddp_kwargs)
def _call_children_scripts(self):
# bookkeeping of spawned processes
self._check_can_spawn_children()
# DDP Environment variables
os.environ["MASTER_ADDR"] = self.cluster_environment.main_address
os.environ["MASTER_PORT"] = str(self.cluster_environment.main_port)
# allow the user to pass the node rank
os.environ["NODE_RANK"] = str(self.cluster_environment.node_rank())
os.environ["LOCAL_RANK"] = str(self.cluster_environment.local_rank())
# Check if the current calling command looked like `python a/b/c.py` or `python -m a.b.c`
# See https://docs.python.org/3/reference/import.html#main-spec
if __main__.__spec__ is None: # pragma: no-cover
# Script called as `python a/b/c.py`
# when user is using hydra find the absolute path
path_lib = os.path.abspath if not _HYDRA_AVAILABLE else to_absolute_path
# pull out the commands used to run the script and resolve the abs file path
command = sys.argv
try:
full_path = path_lib(command[0])
except Exception:
full_path = os.path.abspath(command[0])
command[0] = full_path
# use the same python interpreter and actually running
command = [sys.executable] + command
else: # Script called as `python -m a.b.c`
command = [sys.executable, "-m", __main__.__spec__.name] + sys.argv[1:]
# the visible devices tell us how many GPUs we want to use.
# when the trainer script was called the device has already been scoped by the time
# code reaches this point. so, to call the scripts, we need to leave cuda visible devices alone
# but forward the GPUs selected via environment variables
if self.parallel_devices is None:
raise MisconfigurationException("you selected (distribute_backend = ddp) but did not set Trainer(gpus=?)")
os.environ["WORLD_SIZE"] = f"{self.num_processes * self.num_nodes}"
self.interactive_ddp_procs = []
for local_rank in range(1, self.num_processes):
env_copy = os.environ.copy()
env_copy["LOCAL_RANK"] = f"{local_rank}"
# remove env var if global seed not set
if os.environ.get("PL_GLOBAL_SEED") is None and "PL_GLOBAL_SEED" in env_copy:
del env_copy["PL_GLOBAL_SEED"]
# start process
# if hydra is available and initialized, make sure to set the cwd correctly
cwd: Optional[str] = None
if _HYDRA_AVAILABLE:
if HydraConfig.initialized():
cwd = get_original_cwd()
os_cwd = f'"{os.getcwd()}"'
command += [f"hydra.run.dir={os_cwd}", f"hydra.job.name=train_ddp_process_{local_rank}"]
proc = subprocess.Popen(command, env=env_copy, cwd=cwd)
self.interactive_ddp_procs.append(proc)
# starting all processes at once can cause issues
# with dataloaders delay between 1-10 seconds
delay = np.random.uniform(1, 5, 1)[0]
sleep(delay)
self._rank_0_has_called_call_children_scripts = True
def setup_distributed(self):
log.detail(f"{self.__class__.__name__}: setting up distributed...")
reset_seed()
# determine which process we are and world size
self.set_world_ranks()
# set warning rank
rank_zero_only.rank = self.global_rank
# set up server using proc 0's ip address
# try to init for 20 times at max in case ports are taken
# where to store ip_table
init_dist_connection(self.cluster_environment, self.torch_distributed_backend)
def _check_can_spawn_children(self):
if self.local_rank != 0:
raise RuntimeError(
"Lightning attempted to launch new distributed processes with `local_rank > 0`. This should not happen."
" Possible reasons: 1) LOCAL_RANK environment variable was incorrectly modified by the user,"
" 2) `ClusterEnvironment.creates_processes_externally` incorrectly implemented."
)
def set_world_ranks(self) -> None:
if self.cluster_environment is None:
return
self.cluster_environment.set_global_rank(self.node_rank * self.num_processes + self.local_rank)
self.cluster_environment.set_world_size(self.num_nodes * self.num_processes)
rank_zero_only.rank = self.cluster_environment.global_rank()
def pre_configure_ddp(self):
# if unset, default `find_unused_parameters` `True`
# Many models require setting this parameter to True, as there are corner cases
# when not all parameter backward hooks are fired by the autograd engine even if require_grad is set to True.
# This flag does come with a performance hit, so it is suggested to disable in cases where it is possible.
self._ddp_kwargs["find_unused_parameters"] = self._ddp_kwargs.get("find_unused_parameters", True)
if not self.lightning_module.automatic_optimization and not self._ddp_kwargs.get(
"find_unused_parameters", False
):
# TODO: PyTorch 1.7.0 DDP introduces `self.reducer._rebuild_buckets()` breaking manual_optimization
rank_zero_warn(
"From PyTorch 1.7.0, Lightning `manual_optimization` needs to set `find_unused_parameters=True` to"
" properly work with DDP. Using `find_unused_parameters=True`."
)
self._ddp_kwargs["find_unused_parameters"] = True
def _register_ddp_hooks(self) -> None:
log.detail(f"{self.__class__.__name__}: registering ddp hooks")
# In 1.8, DDP communication hooks only work with NCCL backend and SPSD (single process single device) mode
# Since 1.9, DDP communication hooks can work on all backends.
if _TORCH_GREATER_EQUAL_1_9 or (
_TORCH_GREATER_EQUAL_1_8 and self.on_gpu and self._is_single_process_single_device
):
register_ddp_comm_hook(
model=self.model,
ddp_comm_state=self._ddp_comm_state,
ddp_comm_hook=self._ddp_comm_hook,
ddp_comm_wrapper=self._ddp_comm_wrapper,
)
if _TORCH_GREATER_EQUAL_1_10 and self.lightning_module.trainer.state.fn == TrainerFn.FITTING:
import torch.distributed.algorithms.ddp_comm_hooks.post_localSGD_hook as post_localSGD
if isinstance(self._ddp_comm_state, post_localSGD.PostLocalSGDState):
self._reinit_optimizers_with_post_localSGD(self._ddp_comm_state.start_localSGD_iter)
def _reinit_optimizers_with_post_localSGD(self, warmup_steps: int):
log.detail(f"{self.__class__.__name__}: reinitializing optimizers with post localSGD")
optimizers = self.lightning_module.trainer.optimizers
if self._model_averaging_period is None:
raise ValueError(
"Post-localSGD algorithm is used, but model averaging period is not provided to DDP strategy."
)
if _TORCH_GREATER_EQUAL_1_10:
if not _IS_WINDOWS:
from torch.distributed.optim import DistributedOptimizer
import torch.distributed.algorithms.model_averaging.averagers as averagers
from torch.distributed.optim import PostLocalSGDOptimizer, ZeroRedundancyOptimizer
averager = averagers.PeriodicModelAverager(period=self._model_averaging_period, warmup_steps=warmup_steps)
for x, optimizer in enumerate(optimizers):
if isinstance(optimizer, LightningOptimizer):
optimizer = optimizer._optimizer
is_distributed_optimizer = isinstance(optimizer, DistributedOptimizer) if not _IS_WINDOWS else False
if (
is_distributed_optimizer
or isinstance(optimizer, ZeroRedundancyOptimizer)
or (_FAIRSCALE_AVAILABLE and isinstance(optimizer, OSS))
):
raise ValueError(
f"Cannot wrap a distributed optimizer of type {optimizer.__name__} by PostLocalSGDOptimizer."
)
if isinstance(optimizer, PostLocalSGDOptimizer):
continue
optim_class = type(optimizer)
post_localSGD_optimizer = PostLocalSGDOptimizer(
params=optimizer.param_groups,
optimizer_class=optim_class,
averager=averager,
**optimizer.defaults,
)
optimizers[x] = post_localSGD_optimizer
del optimizer
trainer = self.lightning_module.trainer
trainer.optimizers = optimizers
_convert_to_lightning_optimizers(trainer)
def configure_ddp(self) -> None:
log.detail(f"{self.__class__.__name__}: configuring DistributedDataParallel")
self.pre_configure_ddp()
self.model = self._setup_model(LightningDistributedModule(self.model))
self._register_ddp_hooks()
def determine_ddp_device_ids(self):
if self.root_device.type == "cpu":
return None
return [self.root_device.index]
def barrier(self, *args, **kwargs) -> None:
if not distributed_available():
return
if _TORCH_GREATER_EQUAL_1_8 and torch.distributed.get_backend() == "nccl":
torch.distributed.barrier(device_ids=self.determine_ddp_device_ids())
else:
torch.distributed.barrier()
def broadcast(self, obj: object, src: int = 0) -> object:
obj = [obj]
if self.global_rank != src:
obj = [None]
torch.distributed.broadcast_object_list(obj, src, group=_group.WORLD)
return obj[0]
def pre_backward(self, closure_loss: torch.Tensor) -> None:
"""Run before precision plugin executes backward."""
if not self.lightning_module.automatic_optimization:
prepare_for_backward(self.model, closure_loss)
def model_to_device(self):
log.detail(f"{self.__class__.__name__}: moving model to device [{self.root_device}]...")
self.model.to(self.root_device)
def reduce(self, tensor, group: Optional[Any] = None, reduce_op: Union[ReduceOp, str] = "mean") -> torch.Tensor:
"""Reduces a tensor from several distributed processes to one aggregated tensor.
Args:
tensor: the tensor to sync and reduce
group: the process group to gather results from. Defaults to all processes (world)
reduce_op: the reduction operation. Defaults to 'mean'/'avg'.
Can also be a string 'sum' to calculate the sum during reduction.
Return:
reduced value, except when the input was not a tensor the output remains is unchanged
"""
if isinstance(tensor, torch.Tensor):
tensor = sync_ddp_if_available(tensor, group, reduce_op=reduce_op)
return tensor
def training_step(self, *args, **kwargs) -> STEP_OUTPUT:
with self.precision_plugin.train_step_context():
return self.model(*args, **kwargs)
def validation_step(self, *args, **kwargs) -> Optional[STEP_OUTPUT]:
with self.precision_plugin.val_step_context():
if isinstance(self.model, DistributedDataParallel):
# used when calling `trainer.fit`
return self.model(*args, **kwargs)
else:
# used when calling `trainer.validate`
return self.lightning_module.validation_step(*args, **kwargs)
def test_step(self, *args, **kwargs) -> Optional[STEP_OUTPUT]:
with self.precision_plugin.test_step_context():
return self.lightning_module.test_step(*args, **kwargs)
def predict_step(self, *args, **kwargs) -> STEP_OUTPUT:
with self.precision_plugin.predict_step_context():
return self.lightning_module.predict_step(*args, **kwargs)
def post_training_step(self):
if not self.lightning_module.automatic_optimization:
self.model.require_backward_grad_sync = True
@classmethod
def register_strategies(cls, strategy_registry: Dict) -> None:
strategy_registry.register(
"ddp_find_unused_parameters_false",
cls,
description="DDP Strategy with `find_unused_parameters` as False",
find_unused_parameters=False,
)
def _should_run_deadlock_detection(self) -> bool:
"""Determines whether the plugin will perform process reconciliation in case of errors.
If the environment variable `PL_RECONCILE_PROCESS` is set, run detection regardless of the cluster environment.
By default this is disabled. Otherwise, if the cluster environment creates the processes, allow the scheduler /
parent process to perform the process termination, external to Lightning.
"""
return os.getenv("PL_RECONCILE_PROCESS", "0") == "1" or self._rank_0_has_called_call_children_scripts
def _share_information_to_prevent_deadlock(self) -> None:
self._share_pids()
# there should be a unique sync_dir per nodes.
if self.local_rank == 0:
# create a temporary directory used to synchronize processes on deadlock.
self._sync_dir = tempfile.mkdtemp()
sync_dirs = []
global_node_rank_zero = 0
for _ in range(self.num_nodes):
sync_dirs.append(self.broadcast(self._sync_dir, global_node_rank_zero))
global_node_rank_zero += self.world_size // self.num_nodes
self._sync_dir = sync_dirs[self.node_rank]
def _share_pids(self) -> None:
"""Make all DDP processes aware of all processes pids."""
self.barrier()
pids = self.all_gather(torch.tensor(os.getpid(), device=self.root_device))
pids = pids.cpu().numpy().tolist()
self._pids = pids if isinstance(pids, list) else [pids]
def reconciliate_processes(self, trace: str) -> None:
if self.world_size < 2:
return
if not self._should_run_deadlock_detection():
return
sync_dir = self._sync_dir
if not sync_dir:
rank_zero_warn("Error handling mechanism for deadlock detection is uninitialized. Skipping check.")
return
# The cluster may be configured to periodically purge the `/tmp`
# directory, in which case `sync_dir` may not exist anymore at this
# point. Idempotently create it to ensure its existence.
Path(sync_dir).mkdir(parents=True, exist_ok=True)
# save a file locally.
torch.save(True, os.path.join(sync_dir, f"{self.global_rank}.pl"))
# sleep for a short time
time.sleep(3)
# return if all processes wrote a file in the `sync_dir`.
# todo (tchaton) Add support for non-shared file-system which will fail.
if len(os.listdir(sync_dir)) == (self.world_size // self.num_nodes):
return
for pid in self._pids:
if pid != os.getpid():
os.kill(pid, signal.SIGKILL)
shutil.rmtree(sync_dir)
raise DeadlockDetectedException(f"DeadLock detected from rank: {self.global_rank} \n {trace}")
def teardown(self) -> None:
log.detail(f"{self.__class__.__name__}: tearing down DDP plugin")
super().teardown()
if isinstance(self.model, DistributedDataParallel):
self.model = self.lightning_module
if self.sync_batchnorm:
self.model = _revert_sync_batchnorm(self.model)
if self.on_gpu:
# GPU teardown
log.detail(f"{self.__class__.__name__}: moving model to CPU")
self.lightning_module.cpu()
# clean up memory
torch.cuda.empty_cache()
| [
"logging.getLogger",
"time.sleep",
"pytorch_lightning.utilities.exceptions.MisconfigurationException",
"pytorch_lightning.utilities.rank_zero_warn",
"pytorch_lightning.overrides.distributed.prepare_for_backward",
"pytorch_lightning.utilities.seed.reset_seed",
"pytorch_lightning.utilities.exceptions.Dead... | [((2703, 2730), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (2720, 2730), False, 'import logging\n'), ((6903, 6988), 'torch.nn.parallel.distributed.DistributedDataParallel', 'DistributedDataParallel', ([], {'module': 'model', 'device_ids': 'device_ids'}), '(module=model, device_ids=device_ids, **self._ddp_kwargs\n )\n', (6926, 6988), False, 'from torch.nn.parallel.distributed import DistributedDataParallel\n'), ((10365, 10377), 'pytorch_lightning.utilities.seed.reset_seed', 'reset_seed', ([], {}), '()\n', (10375, 10377), False, 'from pytorch_lightning.utilities.seed import reset_seed\n'), ((10700, 10778), 'pytorch_lightning.utilities.distributed.init_dist_connection', 'init_dist_connection', (['self.cluster_environment', 'self.torch_distributed_backend'], {}), '(self.cluster_environment, self.torch_distributed_backend)\n', (10720, 10778), False, 'from pytorch_lightning.utilities.distributed import init_dist_connection, rank_zero_only, ReduceOp, sync_ddp_if_available\n'), ((14543, 14642), 'torch.distributed.algorithms.model_averaging.averagers.PeriodicModelAverager', 'averagers.PeriodicModelAverager', ([], {'period': 'self._model_averaging_period', 'warmup_steps': 'warmup_steps'}), '(period=self._model_averaging_period,\n warmup_steps=warmup_steps)\n', (14574, 14642), True, 'import torch.distributed.algorithms.model_averaging.averagers as averagers\n'), ((15833, 15874), 'pytorch_lightning.core.optimizer._convert_to_lightning_optimizers', '_convert_to_lightning_optimizers', (['trainer'], {}), '(trainer)\n', (15865, 15874), False, 'from pytorch_lightning.core.optimizer import _convert_to_lightning_optimizers, LightningOptimizer\n'), ((16773, 16842), 'torch.distributed.broadcast_object_list', 'torch.distributed.broadcast_object_list', (['obj', 'src'], {'group': '_group.WORLD'}), '(obj, src, group=_group.WORLD)\n', (16812, 16842), False, 'import torch\n'), ((21867, 21880), 'time.sleep', 'time.sleep', (['(3)'], {}), '(3)\n', (21877, 21880), False, 'import time\n'), ((22245, 22268), 'shutil.rmtree', 'shutil.rmtree', (['sync_dir'], {}), '(sync_dir)\n', (22258, 22268), False, 'import shutil\n'), ((22283, 22379), 'pytorch_lightning.utilities.exceptions.DeadlockDetectedException', 'DeadlockDetectedException', (['f"""DeadLock detected from rank: {self.global_rank} \n {trace}"""'], {}), '(\n f"""DeadLock detected from rank: {self.global_rank} \n {trace}""")\n', (22308, 22379), False, 'from pytorch_lightning.utilities.exceptions import DeadlockDetectedException, MisconfigurationException\n'), ((8873, 8978), 'pytorch_lightning.utilities.exceptions.MisconfigurationException', 'MisconfigurationException', (['"""you selected (distribute_backend = ddp) but did not set Trainer(gpus=?)"""'], {}), "(\n 'you selected (distribute_backend = ddp) but did not set Trainer(gpus=?)')\n", (8898, 8978), False, 'from pytorch_lightning.utilities.exceptions import DeadlockDetectedException, MisconfigurationException\n'), ((9172, 9189), 'os.environ.copy', 'os.environ.copy', ([], {}), '()\n', (9187, 9189), False, 'import os\n'), ((9888, 9936), 'subprocess.Popen', 'subprocess.Popen', (['command'], {'env': 'env_copy', 'cwd': 'cwd'}), '(command, env=env_copy, cwd=cwd)\n', (9904, 9936), False, 'import subprocess\n'), ((10172, 10184), 'time.sleep', 'sleep', (['delay'], {}), '(delay)\n', (10177, 10184), False, 'from time import sleep\n'), ((12380, 12566), 'pytorch_lightning.utilities.rank_zero_warn', 'rank_zero_warn', (['"""From PyTorch 1.7.0, Lightning `manual_optimization` needs to set `find_unused_parameters=True` to properly work with DDP. Using `find_unused_parameters=True`."""'], {}), "(\n 'From PyTorch 1.7.0, Lightning `manual_optimization` needs to set `find_unused_parameters=True` to properly work with DDP. Using `find_unused_parameters=True`.'\n )\n", (12394, 12566), False, 'from pytorch_lightning.utilities import _FAIRSCALE_AVAILABLE, _HYDRA_AVAILABLE, _IS_WINDOWS, _TORCH_GREATER_EQUAL_1_8, _TORCH_GREATER_EQUAL_1_9, _TORCH_GREATER_EQUAL_1_10, rank_zero_warn\n'), ((13129, 13292), 'pytorch_lightning.utilities.distributed.register_ddp_comm_hook', 'register_ddp_comm_hook', ([], {'model': 'self.model', 'ddp_comm_state': 'self._ddp_comm_state', 'ddp_comm_hook': 'self._ddp_comm_hook', 'ddp_comm_wrapper': 'self._ddp_comm_wrapper'}), '(model=self.model, ddp_comm_state=self.\n _ddp_comm_state, ddp_comm_hook=self._ddp_comm_hook, ddp_comm_wrapper=\n self._ddp_comm_wrapper)\n', (13151, 13292), False, 'from pytorch_lightning.utilities.distributed import register_ddp_comm_hook\n'), ((15457, 15584), 'torch.distributed.optim.PostLocalSGDOptimizer', 'PostLocalSGDOptimizer', ([], {'params': 'optimizer.param_groups', 'optimizer_class': 'optim_class', 'averager': 'averager'}), '(params=optimizer.param_groups, optimizer_class=\n optim_class, averager=averager, **optimizer.defaults)\n', (15478, 15584), False, 'from torch.distributed.optim import PostLocalSGDOptimizer, ZeroRedundancyOptimizer\n'), ((16071, 16109), 'pytorch_lightning.overrides.LightningDistributedModule', 'LightningDistributedModule', (['self.model'], {}), '(self.model)\n', (16097, 16109), False, 'from pytorch_lightning.overrides import LightningDistributedModule\n'), ((16358, 16381), 'pytorch_lightning.utilities.distributed.distributed_available', 'distributed_available', ([], {}), '()\n', (16379, 16381), False, 'from pytorch_lightning.utilities.distributed import _revert_sync_batchnorm, distributed_available\n'), ((16593, 16620), 'torch.distributed.barrier', 'torch.distributed.barrier', ([], {}), '()\n', (16618, 16620), False, 'import torch\n'), ((17064, 17110), 'pytorch_lightning.overrides.distributed.prepare_for_backward', 'prepare_for_backward', (['self.model', 'closure_loss'], {}), '(self.model, closure_loss)\n', (17084, 17110), False, 'from pytorch_lightning.overrides.distributed import prepare_for_backward\n'), ((17996, 18053), 'pytorch_lightning.utilities.distributed.sync_ddp_if_available', 'sync_ddp_if_available', (['tensor', 'group'], {'reduce_op': 'reduce_op'}), '(tensor, group, reduce_op=reduce_op)\n', (18017, 18053), False, 'from pytorch_lightning.utilities.distributed import init_dist_connection, rank_zero_only, ReduceOp, sync_ddp_if_available\n'), ((20430, 20448), 'tempfile.mkdtemp', 'tempfile.mkdtemp', ([], {}), '()\n', (20446, 20448), False, 'import tempfile\n'), ((21326, 21435), 'pytorch_lightning.utilities.rank_zero_warn', 'rank_zero_warn', (['"""Error handling mechanism for deadlock detection is uninitialized. Skipping check."""'], {}), "(\n 'Error handling mechanism for deadlock detection is uninitialized. Skipping check.'\n )\n", (21340, 21435), False, 'from pytorch_lightning.utilities import _FAIRSCALE_AVAILABLE, _HYDRA_AVAILABLE, _IS_WINDOWS, _TORCH_GREATER_EQUAL_1_8, _TORCH_GREATER_EQUAL_1_9, _TORCH_GREATER_EQUAL_1_10, rank_zero_warn\n'), ((21775, 21823), 'os.path.join', 'os.path.join', (['sync_dir', 'f"""{self.global_rank}.pl"""'], {}), "(sync_dir, f'{self.global_rank}.pl')\n", (21787, 21823), False, 'import os\n'), ((22671, 22705), 'pytorch_lightning.utilities.distributed._revert_sync_batchnorm', '_revert_sync_batchnorm', (['self.model'], {}), '(self.model)\n', (22693, 22705), False, 'from pytorch_lightning.utilities.distributed import _revert_sync_batchnorm, distributed_available\n'), ((22914, 22938), 'torch.cuda.empty_cache', 'torch.cuda.empty_cache', ([], {}), '()\n', (22936, 22938), False, 'import torch\n'), ((9640, 9665), 'hydra.core.hydra_config.HydraConfig.initialized', 'HydraConfig.initialized', ([], {}), '()\n', (9663, 9665), False, 'from hydra.core.hydra_config import HydraConfig\n'), ((10130, 10156), 'numpy.random.uniform', 'np.random.uniform', (['(1)', '(5)', '(1)'], {}), '(1, 5, 1)\n', (10147, 10156), True, 'import numpy as np\n'), ((16442, 16473), 'torch.distributed.get_backend', 'torch.distributed.get_backend', ([], {}), '()\n', (16471, 16473), False, 'import torch\n'), ((20041, 20079), 'os.getenv', 'os.getenv', (['"""PL_RECONCILE_PROCESS"""', '"""0"""'], {}), "('PL_RECONCILE_PROCESS', '0')\n", (20050, 20079), False, 'import os\n'), ((20923, 20934), 'os.getpid', 'os.getpid', ([], {}), '()\n', (20932, 20934), False, 'import os\n'), ((21668, 21682), 'pathlib.Path', 'Path', (['sync_dir'], {}), '(sync_dir)\n', (21672, 21682), False, 'from pathlib import Path\n'), ((22044, 22064), 'os.listdir', 'os.listdir', (['sync_dir'], {}), '(sync_dir)\n', (22054, 22064), False, 'import os\n'), ((22179, 22190), 'os.getpid', 'os.getpid', ([], {}), '()\n', (22188, 22190), False, 'import os\n'), ((22208, 22236), 'os.kill', 'os.kill', (['pid', 'signal.SIGKILL'], {}), '(pid, signal.SIGKILL)\n', (22215, 22236), False, 'import os\n'), ((8166, 8193), 'os.path.abspath', 'os.path.abspath', (['command[0]'], {}), '(command[0])\n', (8181, 8193), False, 'import os\n'), ((9311, 9343), 'os.environ.get', 'os.environ.get', (['"""PL_GLOBAL_SEED"""'], {}), "('PL_GLOBAL_SEED')\n", (9325, 9343), False, 'import os\n'), ((9693, 9711), 'hydra.utils.get_original_cwd', 'get_original_cwd', ([], {}), '()\n', (9709, 9711), False, 'from hydra.utils import get_original_cwd, to_absolute_path\n'), ((9745, 9756), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (9754, 9756), False, 'import os\n')] |
# In[]
import cv2
import numpy as np
import os
from operator import eq
import random
import matplotlib.pyplot as plt
BasePath = "D:/[Data]/[Cardiomegaly]/1_ChestPA_Labeled_Baeksongyi/[PNG]_2_Generated_Data(2k)/Generated_Data_20180410_191400_Seg_Base_Expand_20pixel_Cropped_Detected"
ImgPath = BasePath + '/Imgs/test'
MaskPaths = BasePath + "/Masks"
Dstpath = "D:/[Data]/[Cardiomegaly]/1_ChestPA_Labeled_Baeksongyi/[PNG]_2_Generated_Data(2k)/Temp_OverLay"
Classlist = ["Aortic Knob", "Carina"]
os.environ["CUDA_VISIBLE_DEVICES"]= "0"
for file in os.listdir(ImgPath):
img = cv2.imread(ImgPath + "/" + file)
img = np.asarray(img, dtype = "uint8")
fig = plt.figure()
fig.set_size_inches(256/256, 1, forward=False)
ax = plt.Axes(fig, [0., 0., 1., 1.])
ax.set_axis_off()
fig.add_axes(ax)
img = img[:,:,0]
plt.imshow(img, cmap = "gray")
masks = np.zeros(img.shape, dtype = "uint8")
for clss in Classlist :
Maskpath = MaskPaths + "/" + clss + "/test"
if(not os.path.isfile(Maskpath + "/" + file)):
continue
mask = cv2.imread(Maskpath + "/" + file)
mask = np.asarray(mask, dtype = "uint8")
mask = mask // 255
masks = np.bitwise_or(masks, mask[:,:,0])
linewidth = 10
thorax_x = np.zeros(img.shape, dtype = "uint8")
thorax_x = cv2.rectangle(thorax_x, (512 - linewidth //2 ,0), (512 + linewidth //2 ,1024), color = (255,255,255), thickness = -1)
thorax_x = thorax_x // 255
masks = np.bitwise_or(masks, thorax_x)
axis = np.zeros(img.shape, dtype = "uint8")
axis = cv2.rectangle(axis, (256 - linewidth //2 ,0), (256 + linewidth //2 ,1024), color = (255,255,255), thickness = -1)
axis = axis // 255
masks = np.bitwise_or(masks, axis)
masks = masks * 255
ax.imshow(masks, cmap='gray', alpha = 0.15, interpolation = 'nearest')
plt.savefig(Dstpath + "/"+file, dpi = 2048)
plt.show()
| [
"matplotlib.pyplot.imshow",
"cv2.rectangle",
"os.listdir",
"numpy.bitwise_or",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.Axes",
"numpy.asarray",
"os.path.isfile",
"matplotlib.pyplot.figure",
"numpy.zeros",
"cv2.imread",
"matplotlib.pyplot.show"
] | [((554, 573), 'os.listdir', 'os.listdir', (['ImgPath'], {}), '(ImgPath)\n', (564, 573), False, 'import os\n'), ((587, 619), 'cv2.imread', 'cv2.imread', (["(ImgPath + '/' + file)"], {}), "(ImgPath + '/' + file)\n", (597, 619), False, 'import cv2\n'), ((630, 660), 'numpy.asarray', 'np.asarray', (['img'], {'dtype': '"""uint8"""'}), "(img, dtype='uint8')\n", (640, 660), True, 'import numpy as np\n'), ((676, 688), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (686, 688), True, 'import matplotlib.pyplot as plt\n'), ((749, 784), 'matplotlib.pyplot.Axes', 'plt.Axes', (['fig', '[0.0, 0.0, 1.0, 1.0]'], {}), '(fig, [0.0, 0.0, 1.0, 1.0])\n', (757, 784), True, 'import matplotlib.pyplot as plt\n'), ((850, 878), 'matplotlib.pyplot.imshow', 'plt.imshow', (['img'], {'cmap': '"""gray"""'}), "(img, cmap='gray')\n", (860, 878), True, 'import matplotlib.pyplot as plt\n'), ((893, 927), 'numpy.zeros', 'np.zeros', (['img.shape'], {'dtype': '"""uint8"""'}), "(img.shape, dtype='uint8')\n", (901, 927), True, 'import numpy as np\n'), ((1301, 1335), 'numpy.zeros', 'np.zeros', (['img.shape'], {'dtype': '"""uint8"""'}), "(img.shape, dtype='uint8')\n", (1309, 1335), True, 'import numpy as np\n'), ((1353, 1475), 'cv2.rectangle', 'cv2.rectangle', (['thorax_x', '(512 - linewidth // 2, 0)', '(512 + linewidth // 2, 1024)'], {'color': '(255, 255, 255)', 'thickness': '(-1)'}), '(thorax_x, (512 - linewidth // 2, 0), (512 + linewidth // 2, \n 1024), color=(255, 255, 255), thickness=-1)\n', (1366, 1475), False, 'import cv2\n'), ((1514, 1544), 'numpy.bitwise_or', 'np.bitwise_or', (['masks', 'thorax_x'], {}), '(masks, thorax_x)\n', (1527, 1544), True, 'import numpy as np\n'), ((1560, 1594), 'numpy.zeros', 'np.zeros', (['img.shape'], {'dtype': '"""uint8"""'}), "(img.shape, dtype='uint8')\n", (1568, 1594), True, 'import numpy as np\n'), ((1608, 1725), 'cv2.rectangle', 'cv2.rectangle', (['axis', '(256 - linewidth // 2, 0)', '(256 + linewidth // 2, 1024)'], {'color': '(255, 255, 255)', 'thickness': '(-1)'}), '(axis, (256 - linewidth // 2, 0), (256 + linewidth // 2, 1024),\n color=(255, 255, 255), thickness=-1)\n', (1621, 1725), False, 'import cv2\n'), ((1757, 1783), 'numpy.bitwise_or', 'np.bitwise_or', (['masks', 'axis'], {}), '(masks, axis)\n', (1770, 1783), True, 'import numpy as np\n'), ((1894, 1937), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(Dstpath + '/' + file)"], {'dpi': '(2048)'}), "(Dstpath + '/' + file, dpi=2048)\n", (1905, 1937), True, 'import matplotlib.pyplot as plt\n'), ((1942, 1952), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1950, 1952), True, 'import matplotlib.pyplot as plt\n'), ((1102, 1135), 'cv2.imread', 'cv2.imread', (["(Maskpath + '/' + file)"], {}), "(Maskpath + '/' + file)\n", (1112, 1135), False, 'import cv2\n'), ((1151, 1182), 'numpy.asarray', 'np.asarray', (['mask'], {'dtype': '"""uint8"""'}), "(mask, dtype='uint8')\n", (1161, 1182), True, 'import numpy as np\n'), ((1228, 1263), 'numpy.bitwise_or', 'np.bitwise_or', (['masks', 'mask[:, :, 0]'], {}), '(masks, mask[:, :, 0])\n', (1241, 1263), True, 'import numpy as np\n'), ((1026, 1063), 'os.path.isfile', 'os.path.isfile', (["(Maskpath + '/' + file)"], {}), "(Maskpath + '/' + file)\n", (1040, 1063), False, 'import os\n')] |
import tensorflow as tf
import numpy as np
import time
def constfn(val):
def f(frac):
return val * frac
return f
class Model(object):
def __init__(self, env, world, policies, ncommtime=20, nminibatches=4, noptepochs=4):
self.env = env
self.world = world
self.policies = policies
self.nsteps = policies[0].nsteps
self.nminibatches = nminibatches
self.noptepochs = noptepochs
self.ncommtime = ncommtime
def step(self, obs_n):
action_n, value_n, neglogp_n = [], [], []
for i in range(self.env.n):
action, value, _, neglogp = self.policies[i].step(obs_n[i])
action_n.append(np.diag(action._numpy()))
value_n.append(value)
neglogp_n.append(neglogp)
return action_n, value_n, neglogp_n
def value(self, obs_n):
return [self.policies[i].value(obs_n[i]) for i in range(self.env.n)]
def share_actions(self, actions_n):
shared_actions_n = list(actions_n)
if hasattr(self.env.agents[0], 'adversary'):
n_a = self.env.world.num_adversaries
n_g = self.env.world.num_good_agents
else:
n_a = len(self.env.agents)
n_g= 0
for i in range(n_a):
shared_actions_n[i] = np.hstack(actions_n[:n_a])
for i in range(n_g):
shared_actions_n[n_a+i] = np.hstack(actions_n[n_a:]).astype(actions_n[n_a+i].dtype).squeeze()
return shared_actions_n
def train(self, lr, cliprange, obs, returns, dones, actions, values, advs, neglogpacs):
# Normalize the advantages
for i in range(self.env.n):
advs[i] = (advs[i] - np.mean(advs[i])) / (np.std(advs[i]) + 1e-8)
lr = constfn(lr)
cliprange = constfn(cliprange)
lrnow = tf.constant(lr(1.0))
cliprangenow = tf.constant(cliprange(1.0))
# Calculate the batch_size
nbatch = self.env.nenvs * self.nsteps if hasattr(self.env, 'nenvs') else self.nsteps
nbatch_train = nbatch // self.nminibatches
assert nbatch % self.nminibatches == 0
# Prepare data
argvs = list(zip(obs, returns, actions, values, advs, neglogpacs))
exgargvs = list(zip(obs, actions, neglogpacs))
# Update value network
for i in range(self.env.n):
# Here what we're going to do is for each minibatch calculate the loss and append it.
mblossvals = []
# Index of each element of batch_size
# Create the indices array
inds = np.arange(nbatch)
for _ in range(self.noptepochs):
# Randomize the indexes
np.random.shuffle(inds)
# 0 to batch_size with batch_train_size step
for start in range(0, nbatch, nbatch_train):
end = start + nbatch_train
mbinds = inds[start:end]
slices = (tf.constant(arr[mbinds]) for arr in argvs[i])
mblossvals.append(self.policies[i].vf_update(lrnow, cliprangenow, *slices))
vf_lossvals = np.mean(mblossvals, axis=0)
print('Agent {}: '.format(i), vf_lossvals)
# reinitialize esitmates
for i in range(self.env.n):
self.policies[i].reinitial_estimates()
# self.policies[i].store_oldpi_var()
# some constants
A = self.world.comm_matrix
adv_edges = A[np.unique(np.nonzero(A[:,:self.world.n_adv])[0])]
agt_edges = A[np.unique(np.nonzero(A[:,self.world.n_adv:])[0])]
argvs_k = [tf.constant(arr) for arr in argvs[0]]
argvs_j = [tf.constant(arr) for arr in argvs[1]]
_, loss_0, pg_loss_0, sync_loss_0, *_ = self.policies[0].get_pi_grad(cliprangenow, 1, *argvs_k)
_, loss_1, pg_loss_1, sync_loss_1, *_ = self.policies[1].get_pi_grad(cliprangenow, 0, *argvs_j)
for _ in range(self.ncommtime):
edge = adv_edges[np.random.choice(range(len(adv_edges)))]
q = np.where(edge != 0)[0]
k, j = q[0], q[-1]
# self.policies[k].assign_new_eq_old()
# self.policies[j].assign_new_eq_old()
argvs_k = [tf.constant(arr) for arr in argvs[k]]
argvs_j = [tf.constant(arr) for arr in argvs[j]]
_, lossbf_k, pg_lossbf_k, *_ = self.policies[k].get_pi_grad(cliprangenow, j, *argvs_k)
_, lossbf_j, pg_lossbf_j, *_ = self.policies[j].get_pi_grad(cliprangenow, k, *argvs_j)
# Update Agent k
imp_old = np.array([0.0])
for itr in range(1, 101):
frac = 1.0 - (itr - 1.0) / 100
lrnow = tf.constant(lr(frac))
loss_k, pg_loss_k, sync_loss_k, *_ = self.policies[k].pi_update(lrnow, cliprangenow, j, *argvs_k)
print('Agent {}: '.format(k), (lossbf_k-loss_k).numpy(), (pg_lossbf_k-pg_loss_k).numpy(), sync_loss_k.numpy())
if sync_loss_k.numpy() < 1e-3:
break
# imp_new = (lossbf_k-loss_k).numpy()
# print(imp_new-imp_old)
# if imp_new-imp_old < -1e-5:
# continue
# elif imp_new!=0 and imp_new-imp_old < 1e-5:
# break
# else:
# imp_old = imp_new.copy()
# Update Agent j
imp_old = np.array([0.0])
for itr in range(1, 101):
frac = 1.0 - (itr - 1.0) / 100
lrnow = tf.constant(lr(frac))
loss_j, pg_loss_j, sync_loss_j, *_ = self.policies[j].pi_update(lrnow, cliprangenow, k, *argvs_j)
print('Agent {}: '.format(j), (lossbf_j-loss_j).numpy(), (pg_lossbf_j-pg_loss_j).numpy(), sync_loss_j.numpy())
if sync_loss_j.numpy() < 1e-3:
break
# imp_new = (lossbf_j-loss_j).numpy()
# print(imp_new-imp_old)
# if imp_new-imp_old < -1e-5:
# continue
# elif imp_new!=0 and imp_new-imp_old < 1e-5:
# break
# else:
# imp_old = imp_new.copy()
ratio_k, multipliers_k = self.policies[k].info_to_exchange(cliprangenow, *exgargvs[k], j)
ratio_j, multipliers_j = self.policies[j].info_to_exchange(cliprangenow, *exgargvs[j], k)
self.policies[k].exchange(cliprangenow, *exgargvs[k], ratio_j, multipliers_j, j)
self.policies[j].exchange(cliprangenow, *exgargvs[j], ratio_k, multipliers_k, k)
print('----------------------------')
print(loss_0.numpy(), pg_loss_0.numpy(), sync_loss_0.numpy())
print(loss_1.numpy(), pg_loss_1.numpy(), sync_loss_1.numpy())
print('----------------------------')
print(loss_k.numpy(), pg_loss_k.numpy(), sync_loss_k.numpy())
print(loss_j.numpy(), pg_loss_j.numpy(), sync_loss_j.numpy())
# print('----------------------------')
# print('Agent 0 estimates: \n', self.policies[0].estimates[1])
# print('Agent 1 estimates: \n', self.policies[1].estimates[0])
print('----------------------------')
print('Agent 0 logits: \n', ratio_k.numpy())
print('Agent 1 logits: \n', ratio_j.numpy())
input()
| [
"numpy.mean",
"numpy.hstack",
"numpy.where",
"numpy.array",
"tensorflow.constant",
"numpy.nonzero",
"numpy.std",
"numpy.arange",
"numpy.random.shuffle"
] | [((1313, 1339), 'numpy.hstack', 'np.hstack', (['actions_n[:n_a]'], {}), '(actions_n[:n_a])\n', (1322, 1339), True, 'import numpy as np\n'), ((2586, 2603), 'numpy.arange', 'np.arange', (['nbatch'], {}), '(nbatch)\n', (2595, 2603), True, 'import numpy as np\n'), ((3141, 3168), 'numpy.mean', 'np.mean', (['mblossvals'], {'axis': '(0)'}), '(mblossvals, axis=0)\n', (3148, 3168), True, 'import numpy as np\n'), ((3621, 3637), 'tensorflow.constant', 'tf.constant', (['arr'], {}), '(arr)\n', (3632, 3637), True, 'import tensorflow as tf\n'), ((3678, 3694), 'tensorflow.constant', 'tf.constant', (['arr'], {}), '(arr)\n', (3689, 3694), True, 'import tensorflow as tf\n'), ((4578, 4593), 'numpy.array', 'np.array', (['[0.0]'], {}), '([0.0])\n', (4586, 4593), True, 'import numpy as np\n'), ((5424, 5439), 'numpy.array', 'np.array', (['[0.0]'], {}), '([0.0])\n', (5432, 5439), True, 'import numpy as np\n'), ((2705, 2728), 'numpy.random.shuffle', 'np.random.shuffle', (['inds'], {}), '(inds)\n', (2722, 2728), True, 'import numpy as np\n'), ((4051, 4070), 'numpy.where', 'np.where', (['(edge != 0)'], {}), '(edge != 0)\n', (4059, 4070), True, 'import numpy as np\n'), ((4230, 4246), 'tensorflow.constant', 'tf.constant', (['arr'], {}), '(arr)\n', (4241, 4246), True, 'import tensorflow as tf\n'), ((4291, 4307), 'tensorflow.constant', 'tf.constant', (['arr'], {}), '(arr)\n', (4302, 4307), True, 'import tensorflow as tf\n'), ((1705, 1721), 'numpy.mean', 'np.mean', (['advs[i]'], {}), '(advs[i])\n', (1712, 1721), True, 'import numpy as np\n'), ((1726, 1741), 'numpy.std', 'np.std', (['advs[i]'], {}), '(advs[i])\n', (1732, 1741), True, 'import numpy as np\n'), ((3487, 3522), 'numpy.nonzero', 'np.nonzero', (['A[:, :self.world.n_adv]'], {}), '(A[:, :self.world.n_adv])\n', (3497, 3522), True, 'import numpy as np\n'), ((3559, 3594), 'numpy.nonzero', 'np.nonzero', (['A[:, self.world.n_adv:]'], {}), '(A[:, self.world.n_adv:])\n', (3569, 3594), True, 'import numpy as np\n'), ((2973, 2997), 'tensorflow.constant', 'tf.constant', (['arr[mbinds]'], {}), '(arr[mbinds])\n', (2984, 2997), True, 'import tensorflow as tf\n'), ((1407, 1433), 'numpy.hstack', 'np.hstack', (['actions_n[n_a:]'], {}), '(actions_n[n_a:])\n', (1416, 1433), True, 'import numpy as np\n')] |
# KNN으로 기술적분석 지표들과 변동성을 Feature로 향후 20일 동안
# 목표 수익률을 달성할 가능성이 있는지를 추정한다.
#
# 2018.08.20, 아마추어퀀트 (조성현)
# --------------------------------------------------------
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from MyUtil import YahooData, TaFeatureSet
stocks = {'005380':'현대차', '000660':'SK하이닉스', '015760':'한국전력', '034220':'LG디스플레이',
'005490':'POSCO', '035420':'NAVER', '017670':'SK텔레콤', '012330':'현대모비스',
'055550':'신한지주', '000270':'기아차', '105560':'KB금융', '051910':'LG화학'}
# Yahoo site로부터 위에 정의된 주가 데이터를 수집하여 ./stockData 폴더에 저장해 둔다.
def getData(stockList=stocks, start='2007-01-01'):
YahooData.getStockDataList(stockList, start=start)
# 데이터 세트를 생성하고, ./dataset/3-6.TaDataset.csv 에 저장해 둔다.
# 시간이 오래 걸린다.
def createDataSet(stockList=stocks, u=0.5, d=-0.5, nFuture=20, binary=True):
n = 1
for code in stockList.keys():
# 저장된 파일을 읽어온다
data = pd.read_csv('stockData/' + code + '.csv', index_col=0, parse_dates=True)
# 과거 20일의 종가 패턴과 변동성이 어느 수준일 때 매수하면 손실인지 아닌지를 class로 부여하여
# 목표 수익률 달성 여부를 학습한다. 목표 수익률을 달성한다는 것은 향후 주가가 상승하는 것을 의미함.
# Binary classification을 위해 class = 0, 1로 구분하였음.
# u = 0.5 : 수익률 표준편차의 0.5 배 이상이면 수익 (class = 1)
# d = -0.5 : 수익률 표준편차의 -0.5배 이하이면 손실 (class = 0)
# 중간이면 주가 횡보 (classs = 0)
if n == 1:
ft = TaFeatureSet.getTaFeatureSet(data, u, d, nFuture, binary)
else:
ft = ft.append(TaFeatureSet.getTaFeatureSet(data, u, d, nFuture, binary))
print("%d) %s (%s)를 처리하였습니다." % (n, stockList[code], code))
n += 1
ft.to_csv('dataset/3-6.TaDataset.csv')
# 데이터 세트를 읽어온다
ds = pd.read_csv('dataset/3-6.TaDataset.csv')
ds = ds.drop(ds.columns[0], 1)
# data set을 행을 기준으로 랜덤하게 섞는다 (shuffling)
ds = ds.sample(frac=1).reset_index(drop=True)
# 학습용 데이터와 시험용 데이터로 나눈다. (8 : 2)
trainRate = 0.8
trainLen = int(len(ds) * trainRate)
trainX = np.array(ds.iloc[0:trainLen, 0:6])
trainY = np.array(ds.iloc[0:trainLen, -1])
trainY = trainY.reshape(trainLen, 1)
testX = np.array(ds.iloc[trainLen:, 0:6])
testY = np.array(ds.iloc[trainLen:, -1])
testY = testY.reshape(len(testY), 1)
# 그래프 모델을 생성한다
tf.reset_default_graph()
x = tf.placeholder(tf.float32, shape=[None, 6], name="X")
y = tf.placeholder(tf.float32, shape=[None, 1], name="Y")
tx = tf.placeholder(tf.float32, shape=[None, 6], name="X")
parK = tf.placeholder(tf.int32, shape=[], name="K")
# test point와 모든 x와의 거리를 측정한다 (Euclidean distance)
distance = tf.sqrt(tf.reduce_sum(tf.square(tf.subtract(x, tx)), 1))
# test point와 모든 x와의 거리중 거리가 짧은 K개의 class (trainY)를 찾는다.
# 이 classes에서 다수결로 test point의 class를 판정한다.
# ex : tf.gather(trainY, indices) = [1, 1, 0, 1, 0, 1, 1] --> class = 1로 판정한다.
# class 들의 평균 = 5/7 = 0.714 --> 0.5 보다 크므로 class = 1로 판정함.
values, indices = tf.nn.top_k(tf.negative(distance), k=parK, sorted=False)
classMean = tf.reduce_mean(tf.cast(tf.gather(trainY, indices), tf.float32))
# 그래프를 실행한다.
sess = tf.Session()
accuracy = [] # K = [1,2,3..]에 따른 정확도를 기록할 list
yHatK = [] # 최적 K일 때 testX의 class를 추정한 list
optK = 0 # 최적 K
optAccuracy = 0.0 # 최적 K일 때의 정확도
minK = 50
maxK = 100 # K = minK ~ maxK 까지 변화시키면서 정확도를 측정한다
for k in range(minK, maxK+1):
yHat = []
for dx in testX:
# testX를 하나씩 읽어가면서 k-개의 가까운 거리를 찾는다
dx = dx.reshape(1, 6)
yHat.append(sess.run(classMean, feed_dict = {x: trainX, tx: dx, parK: k}))
# test data의 class를 추정한다.
yHat = np.array(yHat)
yHat = yHat.reshape(len(yHat), 1)
testYhat = np.where(yHat > 0.5, 1, 0)
# test data의 실제 class와 추정 class를 비교하여 정확도를 측정한다.
accK = 100 * (testY == testYhat).sum() / len(testY)
# 정확도가 가장 높은 최적 K, yHatK, optAccuracy를 기록해 둔다
if accK > optAccuracy:
yHatK = yHat.copy()
optK = k
optAccuracy = accK
# K에 따라 달라지는 정확도를 추적하기위해 history를 기록해 둔다
accuracy.append(accK)
print("k = %d done" % k)
sess.close()
# 결과를 확인한다
fig = plt.figure(figsize=(10, 4))
p1 = fig.add_subplot(1,2,1)
p2 = fig.add_subplot(1,2,2)
xK = np.arange(minK, maxK+1)
p1.plot(xK, accuracy)
p1.set_title("Accuracy (optimal K = " + str(optK) + ")")
p1.set_xlabel("K")
p1.set_ylabel("accuracy")
n, bins, patches = p2.hist(yHatK, 50, facecolor='blue', alpha=0.5)
p2.set_title("yHat distribution")
plt.show()
print("\nAccuracy = %.2f %s" % (optAccuracy, '%'))
# 2개 Feature를 선택하여 2-차원 상에서 각 Feature에 대한 class를 육안으로 확인한다
# 전체 Feature의 6-차원 공간의 확인은 불가하므로 2-차원으로 확인한다
dsX = 0 # x-축은 첫 번째 feature
dsY = 1 # y-축은 두 번째 feature
cnt = 300 # 300개만 그린다
class0 = ds[ds['class'] == 0].iloc[0:cnt, [dsX, dsY]]
colX = class0.columns[0]
colY = class0.columns[1]
plt.figure(figsize=(8, 7))
plt.scatter(class0[colX], class0[colY], color='blue', marker='o', s=50, alpha=0.5, label='class=0')
class1 = ds[ds['class'] == 1].iloc[0:cnt, [dsX, dsY]]
plt.scatter(class1[colX], class1[colY], color='red', marker='x', s=50, alpha=0.7, label='class=1')
plt.xlabel(colX)
plt.ylabel(colY)
plt.legend()
plt.show()
| [
"tensorflow.reset_default_graph",
"pandas.read_csv",
"matplotlib.pyplot.ylabel",
"numpy.where",
"matplotlib.pyplot.legend",
"tensorflow.placeholder",
"tensorflow.Session",
"matplotlib.pyplot.xlabel",
"MyUtil.TaFeatureSet.getTaFeatureSet",
"tensorflow.negative",
"numpy.array",
"matplotlib.pyplo... | [((1701, 1741), 'pandas.read_csv', 'pd.read_csv', (['"""dataset/3-6.TaDataset.csv"""'], {}), "('dataset/3-6.TaDataset.csv')\n", (1712, 1741), True, 'import pandas as pd\n'), ((1956, 1990), 'numpy.array', 'np.array', (['ds.iloc[0:trainLen, 0:6]'], {}), '(ds.iloc[0:trainLen, 0:6])\n', (1964, 1990), True, 'import numpy as np\n'), ((2000, 2033), 'numpy.array', 'np.array', (['ds.iloc[0:trainLen, -1]'], {}), '(ds.iloc[0:trainLen, -1])\n', (2008, 2033), True, 'import numpy as np\n'), ((2080, 2113), 'numpy.array', 'np.array', (['ds.iloc[trainLen:, 0:6]'], {}), '(ds.iloc[trainLen:, 0:6])\n', (2088, 2113), True, 'import numpy as np\n'), ((2122, 2154), 'numpy.array', 'np.array', (['ds.iloc[trainLen:, -1]'], {}), '(ds.iloc[trainLen:, -1])\n', (2130, 2154), True, 'import numpy as np\n'), ((2208, 2232), 'tensorflow.reset_default_graph', 'tf.reset_default_graph', ([], {}), '()\n', (2230, 2232), True, 'import tensorflow as tf\n'), ((2237, 2290), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '[None, 6]', 'name': '"""X"""'}), "(tf.float32, shape=[None, 6], name='X')\n", (2251, 2290), True, 'import tensorflow as tf\n'), ((2295, 2348), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '[None, 1]', 'name': '"""Y"""'}), "(tf.float32, shape=[None, 1], name='Y')\n", (2309, 2348), True, 'import tensorflow as tf\n'), ((2354, 2407), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '[None, 6]', 'name': '"""X"""'}), "(tf.float32, shape=[None, 6], name='X')\n", (2368, 2407), True, 'import tensorflow as tf\n'), ((2415, 2459), 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32'], {'shape': '[]', 'name': '"""K"""'}), "(tf.int32, shape=[], name='K')\n", (2429, 2459), True, 'import tensorflow as tf\n'), ((2997, 3009), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (3007, 3009), True, 'import tensorflow as tf\n'), ((4014, 4041), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(10, 4)'}), '(figsize=(10, 4))\n', (4024, 4041), True, 'import matplotlib.pyplot as plt\n'), ((4104, 4129), 'numpy.arange', 'np.arange', (['minK', '(maxK + 1)'], {}), '(minK, maxK + 1)\n', (4113, 4129), True, 'import numpy as np\n'), ((4354, 4364), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4362, 4364), True, 'import matplotlib.pyplot as plt\n'), ((4715, 4741), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(8, 7)'}), '(figsize=(8, 7))\n', (4725, 4741), True, 'import matplotlib.pyplot as plt\n'), ((4742, 4845), 'matplotlib.pyplot.scatter', 'plt.scatter', (['class0[colX]', 'class0[colY]'], {'color': '"""blue"""', 'marker': '"""o"""', 's': '(50)', 'alpha': '(0.5)', 'label': '"""class=0"""'}), "(class0[colX], class0[colY], color='blue', marker='o', s=50,\n alpha=0.5, label='class=0')\n", (4753, 4845), True, 'import matplotlib.pyplot as plt\n'), ((4897, 4999), 'matplotlib.pyplot.scatter', 'plt.scatter', (['class1[colX]', 'class1[colY]'], {'color': '"""red"""', 'marker': '"""x"""', 's': '(50)', 'alpha': '(0.7)', 'label': '"""class=1"""'}), "(class1[colX], class1[colY], color='red', marker='x', s=50,\n alpha=0.7, label='class=1')\n", (4908, 4999), True, 'import matplotlib.pyplot as plt\n'), ((4997, 5013), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['colX'], {}), '(colX)\n', (5007, 5013), True, 'import matplotlib.pyplot as plt\n'), ((5014, 5030), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['colY'], {}), '(colY)\n', (5024, 5030), True, 'import matplotlib.pyplot as plt\n'), ((5031, 5043), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (5041, 5043), True, 'import matplotlib.pyplot as plt\n'), ((5044, 5054), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (5052, 5054), True, 'import matplotlib.pyplot as plt\n'), ((657, 707), 'MyUtil.YahooData.getStockDataList', 'YahooData.getStockDataList', (['stockList'], {'start': 'start'}), '(stockList, start=start)\n', (683, 707), False, 'from MyUtil import YahooData, TaFeatureSet\n'), ((2855, 2876), 'tensorflow.negative', 'tf.negative', (['distance'], {}), '(distance)\n', (2866, 2876), True, 'import tensorflow as tf\n'), ((3515, 3529), 'numpy.array', 'np.array', (['yHat'], {}), '(yHat)\n', (3523, 3529), True, 'import numpy as np\n'), ((3583, 3609), 'numpy.where', 'np.where', (['(yHat > 0.5)', '(1)', '(0)'], {}), '(yHat > 0.5, 1, 0)\n', (3591, 3609), True, 'import numpy as np\n'), ((936, 1008), 'pandas.read_csv', 'pd.read_csv', (["('stockData/' + code + '.csv')"], {'index_col': '(0)', 'parse_dates': '(True)'}), "('stockData/' + code + '.csv', index_col=0, parse_dates=True)\n", (947, 1008), True, 'import pandas as pd\n'), ((2935, 2961), 'tensorflow.gather', 'tf.gather', (['trainY', 'indices'], {}), '(trainY, indices)\n', (2944, 2961), True, 'import tensorflow as tf\n'), ((1391, 1448), 'MyUtil.TaFeatureSet.getTaFeatureSet', 'TaFeatureSet.getTaFeatureSet', (['data', 'u', 'd', 'nFuture', 'binary'], {}), '(data, u, d, nFuture, binary)\n', (1419, 1448), False, 'from MyUtil import YahooData, TaFeatureSet\n'), ((2555, 2573), 'tensorflow.subtract', 'tf.subtract', (['x', 'tx'], {}), '(x, tx)\n', (2566, 2573), True, 'import tensorflow as tf\n'), ((1490, 1547), 'MyUtil.TaFeatureSet.getTaFeatureSet', 'TaFeatureSet.getTaFeatureSet', (['data', 'u', 'd', 'nFuture', 'binary'], {}), '(data, u, d, nFuture, binary)\n', (1518, 1547), False, 'from MyUtil import YahooData, TaFeatureSet\n')] |
""" Benchmark processing in Dask
This mimics the overall structure and workload of our processing.
<NAME> 8 November 2017
<EMAIL>
"""
import csv
import numpy
from dask import delayed
from distributed import Client, wait, LocalCluster
# Make some randomly located points on 2D plane
def sparse(n, margin=0.1):
numpy.random.seed(8753193)
return numpy.array([numpy.random.uniform(margin, 1.0 - margin, n),
numpy.random.uniform(margin, 1.0 - margin, n)]).reshape([n, 2])
# Put the points onto a grid and FFT
def psf(sparse_data, shape, decimate=1):
grid = numpy.zeros(shape, dtype='complex')
loc = numpy.round(shape * sparse_data).astype('int')
for i in range(0, sparse_data.shape[0], decimate):
grid[loc[i, :]] = 1.0
return numpy.fft.fft(grid).real
def sum_list(arr):
import copy
result=copy.deepcopy(arr[0])
for i, s in enumerate(arr):
if i>0:
result+=s
return result
def write_results(filename, fieldnames, results):
with open(filename, 'a') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=fieldnames, delimiter=',', quotechar='|',
quoting=csv.QUOTE_MINIMAL)
writer.writerow(results)
csvfile.close()
def write_header(filename, fieldnames):
with open(filename, 'w') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=fieldnames, delimiter=',', quotechar='|',
quoting=csv.QUOTE_MINIMAL)
writer.writeheader()
csvfile.close()
if __name__ == '__main__':
import time
import socket
import seqfile
import argparse
# This is scaled so that for npixel=1024, it will take about 200 seconds on a single core of
# a 2017 2.9 GHz Intel Core i7, and the time in data generation (sparse) and imaging (psf) will
# be roughly the same.
parser = argparse.ArgumentParser(description='Benchmark a pseudoinvert in numpy and dask')
parser.add_argument('--scheduler', type=str, default=None,
help='The address of a Dask scheduler e.g. 127.0.0.1:8786. If none given one will be created')
parser.add_argument('--decimate', type=int, default=256, help='Decimation in gridding')
parser.add_argument('--npixel', type=int, default=1024, help='Number of pixels on a side')
parser.add_argument('--nchunks', type=int, default=2048, help='Number of chunks of visibilities')
parser.add_argument('--len_chunk', type=int, default=1024 * 1024,
help='Number of visibilities in a chunk')
parser.add_argument('--reduce', type=int, default=16,
help='Gather this number of images in the first stage of the two stage summing images')
parser.add_argument('--nnodes', type=int, default=1, help='Number of nodes')
parser.add_argument('--nworkers', type=int, default=None,
help='Number of workers if no scheduler passed in')
parser.add_argument('--usebags', type=str, default='False', help='Use bags instead of delayed')
args = parser.parse_args()
results = {}
# Process nchunks each of length len_chunk 2d points, making a psf of size shape
decimate = args.decimate
results['decimate'] = decimate
len_chunk = args.len_chunk
results['len_chunk'] = len_chunk
nchunks = args.nchunks
results['nchunks'] = nchunks
nreduce = args.reduce
results['reduce'] = nreduce
npixel = args.npixel
shape = [npixel, npixel]
results['npixel'] = npixel
nworkers_requested = args.nworkers
usebags = args.usebags=='True'
results['usebags'] = usebags
if args.scheduler is not None:
client = Client(args.scheduler)
else:
if nworkers_requested is None:
client = Client()
else:
cluster = LocalCluster(n_workers=nworkers_requested, threads_per_worker=1)
client = Client(cluster)
nworkers = len(client.scheduler_info()['workers'])
results['nworkers'] = nworkers
results['nnodes'] = args.nnodes
results['hostname'] = socket.gethostname()
results['epoch'] = time.strftime("%Y-%m-%d %H:%M:%S")
import pprint
pp = pprint.PrettyPrinter(indent=4)
print("Initial state")
pp.pprint(results)
fieldnames = ['nnodes', 'nworkers', 'time sum psf', 'npixel', 'max psf', 'len_chunk', 'nchunks', 'reduce',
'decimate', 'hostname', 'epoch', 'usebags']
if usebags:
from dask import bag
print('Using bags to construct graph')
sum_psf_graph = bag.from_sequence(nchunks * [len_chunk]). \
map(sparse). \
map(psf, shape=shape, decimate=decimate). \
fold(numpy.add, split_every=nreduce)
else:
from dask import delayed
print('Using delayed to construct graph')
sparse_graph_list = [delayed(sparse, nout=1)(len_chunk) for i in range(nchunks)]
psf_graph_list = [delayed(psf, nout=1)(s, shape, decimate) for s in sparse_graph_list]
sum_psf_graph_rank1 = [delayed(sum_list, nout=1)(psf_graph_list[i:i + nreduce])
for i in range(0, nchunks, nreduce)]
sum_psf_graph = delayed(sum_list)(sum_psf_graph_rank1)
time.sleep(5)
print("Processing graph")
start = time.time()
future = client.compute(sum_psf_graph)
wait(future)
results['time sum psf'] = time.time() - start
value = future.result()
assert value.shape[0] == shape[0] and value.shape[1] == shape[1], \
"Shape of result %s not as requested %s" % (value.shape, shape)
results['max psf'] = numpy.max(value)
nworkers = len(client.scheduler_info()['workers'])
assert nworkers == nworkers_requested, "Number of workers %d not as requested %d" % (nworkers, nworkers_requested)
results['nworkers'] = nworkers
filename = seqfile.findNextFile(prefix='pseudoinvert_%s_' % results['hostname'], suffix='.csv')
print('Saving results to %s' % filename)
write_header(filename, fieldnames)
write_results(filename, fieldnames, results)
client.shutdown()
print("Final state")
pp.pprint(results)
exit()
| [
"csv.DictWriter",
"time.sleep",
"dask.bag.from_sequence",
"copy.deepcopy",
"distributed.LocalCluster",
"argparse.ArgumentParser",
"seqfile.findNextFile",
"numpy.fft.fft",
"numpy.max",
"numpy.random.seed",
"pprint.PrettyPrinter",
"distributed.Client",
"socket.gethostname",
"numpy.round",
... | [((317, 343), 'numpy.random.seed', 'numpy.random.seed', (['(8753193)'], {}), '(8753193)\n', (334, 343), False, 'import numpy\n'), ((594, 629), 'numpy.zeros', 'numpy.zeros', (['shape'], {'dtype': '"""complex"""'}), "(shape, dtype='complex')\n", (605, 629), False, 'import numpy\n'), ((855, 876), 'copy.deepcopy', 'copy.deepcopy', (['arr[0]'], {}), '(arr[0])\n', (868, 876), False, 'import copy\n'), ((1896, 1982), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Benchmark a pseudoinvert in numpy and dask"""'}), "(description=\n 'Benchmark a pseudoinvert in numpy and dask')\n", (1919, 1982), False, 'import argparse\n'), ((4115, 4135), 'socket.gethostname', 'socket.gethostname', ([], {}), '()\n', (4133, 4135), False, 'import socket\n'), ((4159, 4193), 'time.strftime', 'time.strftime', (['"""%Y-%m-%d %H:%M:%S"""'], {}), "('%Y-%m-%d %H:%M:%S')\n", (4172, 4193), False, 'import time\n'), ((4226, 4256), 'pprint.PrettyPrinter', 'pprint.PrettyPrinter', ([], {'indent': '(4)'}), '(indent=4)\n', (4246, 4256), False, 'import pprint\n'), ((5279, 5292), 'time.sleep', 'time.sleep', (['(5)'], {}), '(5)\n', (5289, 5292), False, 'import time\n'), ((5336, 5347), 'time.time', 'time.time', ([], {}), '()\n', (5345, 5347), False, 'import time\n'), ((5395, 5407), 'distributed.wait', 'wait', (['future'], {}), '(future)\n', (5399, 5407), False, 'from distributed import Client, wait, LocalCluster\n'), ((5660, 5676), 'numpy.max', 'numpy.max', (['value'], {}), '(value)\n', (5669, 5676), False, 'import numpy\n'), ((5912, 6000), 'seqfile.findNextFile', 'seqfile.findNextFile', ([], {'prefix': "('pseudoinvert_%s_' % results['hostname'])", 'suffix': '""".csv"""'}), "(prefix='pseudoinvert_%s_' % results['hostname'],\n suffix='.csv')\n", (5932, 6000), False, 'import seqfile\n'), ((783, 802), 'numpy.fft.fft', 'numpy.fft.fft', (['grid'], {}), '(grid)\n', (796, 802), False, 'import numpy\n'), ((1074, 1181), 'csv.DictWriter', 'csv.DictWriter', (['csvfile'], {'fieldnames': 'fieldnames', 'delimiter': '""","""', 'quotechar': '"""|"""', 'quoting': 'csv.QUOTE_MINIMAL'}), "(csvfile, fieldnames=fieldnames, delimiter=',', quotechar='|',\n quoting=csv.QUOTE_MINIMAL)\n", (1088, 1181), False, 'import csv\n'), ((1367, 1474), 'csv.DictWriter', 'csv.DictWriter', (['csvfile'], {'fieldnames': 'fieldnames', 'delimiter': '""","""', 'quotechar': '"""|"""', 'quoting': 'csv.QUOTE_MINIMAL'}), "(csvfile, fieldnames=fieldnames, delimiter=',', quotechar='|',\n quoting=csv.QUOTE_MINIMAL)\n", (1381, 1474), False, 'import csv\n'), ((3709, 3731), 'distributed.Client', 'Client', (['args.scheduler'], {}), '(args.scheduler)\n', (3715, 3731), False, 'from distributed import Client, wait, LocalCluster\n'), ((5438, 5449), 'time.time', 'time.time', ([], {}), '()\n', (5447, 5449), False, 'import time\n'), ((640, 672), 'numpy.round', 'numpy.round', (['(shape * sparse_data)'], {}), '(shape * sparse_data)\n', (651, 672), False, 'import numpy\n'), ((3802, 3810), 'distributed.Client', 'Client', ([], {}), '()\n', (3808, 3810), False, 'from distributed import Client, wait, LocalCluster\n'), ((3847, 3911), 'distributed.LocalCluster', 'LocalCluster', ([], {'n_workers': 'nworkers_requested', 'threads_per_worker': '(1)'}), '(n_workers=nworkers_requested, threads_per_worker=1)\n', (3859, 3911), False, 'from distributed import Client, wait, LocalCluster\n'), ((3933, 3948), 'distributed.Client', 'Client', (['cluster'], {}), '(cluster)\n', (3939, 3948), False, 'from distributed import Client, wait, LocalCluster\n'), ((5235, 5252), 'dask.delayed', 'delayed', (['sum_list'], {}), '(sum_list)\n', (5242, 5252), False, 'from dask import delayed\n'), ((4900, 4923), 'dask.delayed', 'delayed', (['sparse'], {'nout': '(1)'}), '(sparse, nout=1)\n', (4907, 4923), False, 'from dask import delayed\n'), ((4986, 5006), 'dask.delayed', 'delayed', (['psf'], {'nout': '(1)'}), '(psf, nout=1)\n', (4993, 5006), False, 'from dask import delayed\n'), ((5086, 5111), 'dask.delayed', 'delayed', (['sum_list'], {'nout': '(1)'}), '(sum_list, nout=1)\n', (5093, 5111), False, 'from dask import delayed\n'), ((368, 413), 'numpy.random.uniform', 'numpy.random.uniform', (['margin', '(1.0 - margin)', 'n'], {}), '(margin, 1.0 - margin, n)\n', (388, 413), False, 'import numpy\n'), ((439, 484), 'numpy.random.uniform', 'numpy.random.uniform', (['margin', '(1.0 - margin)', 'n'], {}), '(margin, 1.0 - margin, n)\n', (459, 484), False, 'import numpy\n'), ((4602, 4642), 'dask.bag.from_sequence', 'bag.from_sequence', (['(nchunks * [len_chunk])'], {}), '(nchunks * [len_chunk])\n', (4619, 4642), False, 'from dask import bag\n')] |
import pandas as pd
from scipy.io import wavfile
import numpy as np
import argparse
def stock_to_wav(filename):
prices = pd.read_csv(f"{filename}.csv").Close.values
prices = np.diff(prices)
scale = (2**15) * 0.8 / max(map(abs, [prices.max(), prices.min()]))
prices = (prices * scale)
mx, mn = prices.max(), prices.min()
prices = prices.astype(np.int16)
assert abs(mx - prices.max()) < 2
assert abs(mn - prices.min()) < 2
wavfile.write(f"{filename}.wav", 2_000, prices)
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description='Convert historical stock prices to audio file')
parser.add_argument(
'filename', type=str,
help='stock in {stock}.csv'
)
args = parser.parse_args()
stock_to_wav(args.filename)
| [
"scipy.io.wavfile.write",
"numpy.diff",
"argparse.ArgumentParser",
"pandas.read_csv"
] | [((184, 199), 'numpy.diff', 'np.diff', (['prices'], {}), '(prices)\n', (191, 199), True, 'import numpy as np\n'), ((459, 505), 'scipy.io.wavfile.write', 'wavfile.write', (['f"""{filename}.wav"""', '(2000)', 'prices'], {}), "(f'{filename}.wav', 2000, prices)\n", (472, 505), False, 'from scipy.io import wavfile\n'), ((549, 638), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Convert historical stock prices to audio file"""'}), "(description=\n 'Convert historical stock prices to audio file')\n", (572, 638), False, 'import argparse\n'), ((127, 157), 'pandas.read_csv', 'pd.read_csv', (['f"""{filename}.csv"""'], {}), "(f'{filename}.csv')\n", (138, 157), True, 'import pandas as pd\n')] |
import json
import os
from concurrent import futures
import numpy as np
from elf.io import open_file
from tqdm import tqdm
from ..metadata import read_dataset_metadata
def compute_contrast_limits(
source_prefix, dataset_folder, lower_percentile, upper_percentile, n_threads, cache_path=None
):
if cache_path is not None and os.path.exists(cache_path):
with open(cache_path) as f:
return json.load(f)
sources = read_dataset_metadata(dataset_folder)["sources"]
def compute_clim_im(source_name):
path = os.path.join(
dataset_folder,
sources[source_name]["image"]["imageData"]["ome.zarr"]["relativePath"]
)
with open_file(path, "r") as f:
data = f["s0"][:]
cmin = np.percentile(data, lower_percentile)
cmax = np.percentile(data, upper_percentile)
return cmin, cmax
source_names = [name for name in sources.keys() if name.startswith(source_prefix)]
with futures.ThreadPoolExecutor(n_threads) as tp:
results = list(tqdm(
tp.map(compute_clim_im, source_names),
total=len(source_names),
desc=f"Compute contrast limits for {source_prefix}"
))
cmin = np.median([res[0] for res in results])
cmax = np.median([res[1] for res in results])
clim = [float(cmin), float(cmax)]
if cache_path is not None:
with open(cache_path, "w") as f:
json.dump(clim, f)
return clim
| [
"os.path.exists",
"numpy.median",
"elf.io.open_file",
"concurrent.futures.ThreadPoolExecutor",
"os.path.join",
"json.load",
"numpy.percentile",
"json.dump"
] | [((1239, 1277), 'numpy.median', 'np.median', (['[res[0] for res in results]'], {}), '([res[0] for res in results])\n', (1248, 1277), True, 'import numpy as np\n'), ((1289, 1327), 'numpy.median', 'np.median', (['[res[1] for res in results]'], {}), '([res[1] for res in results])\n', (1298, 1327), True, 'import numpy as np\n'), ((335, 361), 'os.path.exists', 'os.path.exists', (['cache_path'], {}), '(cache_path)\n', (349, 361), False, 'import os\n'), ((548, 653), 'os.path.join', 'os.path.join', (['dataset_folder', "sources[source_name]['image']['imageData']['ome.zarr']['relativePath']"], {}), "(dataset_folder, sources[source_name]['image']['imageData'][\n 'ome.zarr']['relativePath'])\n", (560, 653), False, 'import os\n'), ((990, 1027), 'concurrent.futures.ThreadPoolExecutor', 'futures.ThreadPoolExecutor', (['n_threads'], {}), '(n_threads)\n', (1016, 1027), False, 'from concurrent import futures\n'), ((418, 430), 'json.load', 'json.load', (['f'], {}), '(f)\n', (427, 430), False, 'import json\n'), ((696, 716), 'elf.io.open_file', 'open_file', (['path', '"""r"""'], {}), "(path, 'r')\n", (705, 716), False, 'from elf.io import open_file\n'), ((772, 809), 'numpy.percentile', 'np.percentile', (['data', 'lower_percentile'], {}), '(data, lower_percentile)\n', (785, 809), True, 'import numpy as np\n'), ((829, 866), 'numpy.percentile', 'np.percentile', (['data', 'upper_percentile'], {}), '(data, upper_percentile)\n', (842, 866), True, 'import numpy as np\n'), ((1451, 1469), 'json.dump', 'json.dump', (['clim', 'f'], {}), '(clim, f)\n', (1460, 1469), False, 'import json\n')] |
#/usr/bin/env python
"""
Input/Output classes that are used by 3D-DAOSTORM, sCMOS, Spliner
and Multiplane analysis.
Hazen 09/17
"""
import numpy
import os
import sys
from xml.etree import ElementTree
import storm_analysis.sa_library.datareader as datareader
import storm_analysis.sa_library.parameters as params
import storm_analysis.sa_library.readinsight3 as readinsight3
import storm_analysis.sa_library.sa_h5py as saH5Py
import storm_analysis.sa_library.static_background as static_background
import storm_analysis.sa_library.writeinsight3 as writeinsight3
class AnalysisIOException(Exception):
pass
def isLatestFormat(filename):
"""
Returns True if the calibration file is the latest format. This
is mostly used for testing.
"""
data = numpy.load(filename, allow_pickle = True)
return (len(data) == 5) and (data[4] == 2)
def loadCMOSCalibration(filename, verbose = False):
"""
CMOS calibration file reader. This will return the CMOS calibration
data as a list [offset, variance, gain, rqe].
offset - Pixel offset in units of ADU.
variance - Pixel variance in units of ADU*ADU.
gain - Pixel gain in units of ADU / photo-electron (e-).
rqe - Pixel relative quantum efficiency, dimensionless, it should be around 1.0.
filename - The name of calibration file. This should have been saved
using numpy.save.
"""
data = numpy.load(filename, allow_pickle = True)
# Check for v0 format.
if (len(data) == 3):
if verbose:
print("Version 0 sCMOS calibration file detected! Transposing!")
rqe = numpy.ones_like(data[0])
data = list(data) + [rqe]
return map(numpy.transpose, data)
# Check for v1 format.
elif (len(data) == 4):
if verbose:
print("Version 1 sCMOS calibration file detected! Using 1.0 for relative QE array!")
# v1 format.
if (data[3] == 1):
rqe = numpy.ones_like(data[0])
temp = list(data[:3])
temp.append(rqe)
return temp
# Check for v2 format.
elif (len(data) == 5):
# v2 format.
if (data[4] == 2):
return list(data[:4])
raise AnalysisIOException("Unknown sCMOS data format.")
class DataWriter(object):
"""
Encapsulate saving the output of the peak finder/fitter.
"""
def __init__(self, data_file = None, **kwds):
super(DataWriter, self).__init__(**kwds)
self.filename = data_file
self.n_added = 0
self.start_frame = -1
self.total_peaks = 0
def addPeaks(self, peaks, movie_reader):
self.n_added = peaks["x"].size
self.total_peaks += self.n_added
def getNumberAdded(self):
return self.n_added
def getFilename(self):
return self.filename
def getStartFrame(self):
return self.start_frame
def getTotalPeaks(self):
return self.total_peaks
class DataWriterHDF5(DataWriter):
"""
Encapsulate saving the output of the peak finder/fitter to a HDF5 file.
"""
def __init__(self, parameters = None, sa_type = None, **kwds):
super(DataWriterHDF5, self).__init__(**kwds)
self.movie_info_set = False
if os.path.exists(self.filename):
print("Existing analysis file found. Restarting from last analyzed frame.")
self.h5 = saH5Py.SAH5Py(filename = self.filename)
self.movie_info_set = True
# Find the last frame that we analyzed.
i = self.h5.getMovieLength()
while (i > 0):
if self.h5.isAnalyzed(i):
break
i -= 1
self.start_frame = i
else:
self.h5 = saH5Py.SAH5Py(filename = self.filename,
is_existing = False,
sa_type = sa_type)
# Save analysis parameters.
etree = parameters.toXMLElementTree(False)
if (sys.version_info > (3, 0)):
self.h5.addMetadata(ElementTree.tostring(etree, 'unicode'))
else:
self.h5.addMetadata(ElementTree.tostring(etree, 'ISO-8859-1'))
# Save pixel size.
self.h5.setPixelSize(parameters.getAttr("pixel_size"))
self.h5.setAnalysisFinished(False)
def addPeaks(self, peaks, movie_reader):
super(DataWriterHDF5, self).addPeaks(peaks, movie_reader)
if not self.movie_info_set:
self.h5.addMovieInformation(movie_reader)
self.movie_info_set = True
self.h5.addLocalizations(peaks, movie_reader.getCurrentFrameNumber())
def close(self, finished):
self.h5.setAnalysisFinished(finished)
self.h5.close(verbose = True)
class DataWriterI3(DataWriter):
"""
Encapsulate saving the output of the peak finder/fitter to an Insight3 format file.
Note: This format is deprecated.
"""
def __init__(self, parameters = None, **kwds):
super(DataWriterI3, self).__init__(**kwds)
raise Exception("Using the Insight3 format for analysis is deprecated!")
self.pixel_size = parameters.getAttr("pixel_size")
#
# If the i3 file already exists, read it in, write it
# out to prepare for starting the analysis from the
# end of what currently exists.
#
# FIXME: If the existing file is really large there
# could be problems here as we're going to load
# the whole thing into memory.
#
if(os.path.exists(self.filename)):
print("Found", self.filename)
i3data_in = readinsight3.loadI3File(self.filename)
if (i3data_in is None) or (i3data_in.size == 0):
self.start_frame = 0
else:
self.start_frame = int(numpy.max(i3data_in['fr']))
print(" Starting analysis at frame:", self.start_frame)
self.i3data = writeinsight3.I3Writer(self.filename)
if (self.start_frame > 0):
self.i3data.addMolecules(i3data_in)
self.total_peaks = i3data_in['x'].size
else:
self.start_frame = 0
self.i3data = writeinsight3.I3Writer(self.filename)
def addPeaks(self, peaks, movie_reader):
super(DataWriterI3, self).addPeaks(peaks, movie_reader)
self.i3data.addMultiFitMolecules(peaks,
movie_reader.getMovieX(),
movie_reader.getMovieY(),
movie_reader.getCurrentFrameNumber(),
self.pixel_size)
def close(self, metadata = None):
if metadata is None:
self.i3data.close()
else:
self.i3data.closeWithMetadata(metadata)
class FrameReader(object):
"""
Wraps datareader.Reader, converts frames from ADU to photo-electrons.
"""
def __init__(self, movie_file = None, parameters = None, **kwds):
super(FrameReader, self).__init__(**kwds)
self.gain = None
self.offset = None
self.parameters = parameters
self.rqe = 1.0
self.verbose = 1
if self.parameters is not None:
self.verbose = (self.parameters.getAttr("verbosity") == 1)
self.movie_data = datareader.inferReader(movie_file)
def close(self):
self.movie_data.close()
def filmSize(self):
return self.movie_data.filmSize()
def hashID(self):
return self.movie_data.hashID()
def loadAFrame(self, frame_number):
# Load frame.
frame = self.movie_data.loadAFrame(frame_number)
# Convert from ADU to photo-electrons and correct for RQE.
frame = (frame - self.offset) * (self.gain * self.rqe)
# Set all values less than 1.0 to 1.0 as we are doing MLE fitting which
# has zero tolerance for negative numbers..
#
mask = (frame < 1.0)
if (numpy.sum(mask) > 0):
if self.verbose:
print(" Removing values < 1.0 in frame {0:0d}".format(frame_number))
frame[mask] = 1.0
return frame
class FrameReaderStd(FrameReader):
"""
Read frames from a 'standard' (as opposed to sCMOS) camera.
Note: Gain is in units of ADU / photo-electrons.
"""
def __init__(self, camera_gain = None, camera_offset = None, **kwds):
super(FrameReaderStd, self).__init__(**kwds)
if camera_gain is None:
self.gain = 1.0/self.parameters.getAttr("camera_gain")
self.offset = self.parameters.getAttr("camera_offset")
else:
self.gain = 1.0/camera_gain
self.offset = camera_offset
class FrameReaderSCMOS(FrameReader):
"""
Read frames from a sCMOS camera.
Note: Gain is in units of ADU / photo-electrons.
"""
def __init__(self, calibration_file = None, **kwds):
super(FrameReaderSCMOS, self).__init__(**kwds)
if calibration_file is None:
[self.offset, variance, gain, rqe] = loadCMOSCalibration(self.parameters.getAttr("camera_calibration"),
verbose = True)
else:
[self.offset, variance, gain, rqe] = loadCMOSCalibration(calibration_file,
verbose = True)
self.gain = 1.0/gain
self.rqe = 1.0/rqe
class MovieReader(object):
"""
Encapsulate getting the frames of a movie from a datareader.Reader, handling
static_background, which frame to start on, etc...
The primary reason for using a class like this is to add the flexibility
necessary in order to make the peakFinding() function also work with
multi-channel data / analysis.
"""
def __init__(self, frame_reader = None, parameters = None, **kwds):
super(MovieReader, self).__init__(**kwds)
self.background = None
self.bg_estimator = None
self.cur_frame = -1
self.frame_reader = frame_reader
self.frame = None
self.max_frame = None
[self.movie_x, self.movie_y, self.movie_l] = frame_reader.filmSize()
self.parameters = parameters
def close(self):
self.frame_reader.close()
def getBackground(self):
return self.background
def getCurrentFrameNumber(self):
return self.cur_frame
def getFrame(self):
return self.frame
def getMovieL(self):
return self.movie_l
def getMovieX(self):
return self.movie_x
def getMovieY(self):
return self.movie_y
def hashID(self):
return self.frame_reader.hashID()
def nextFrame(self):
self.cur_frame += 1
if (self.cur_frame < self.max_frame):
# Update background estimate.
if self.bg_estimator is not None:
self.background = self.bg_estimator.estimateBG(self.cur_frame)
# Load frame.
self.frame = self.frame_reader.loadAFrame(self.cur_frame)
return True
else:
return False
def setup(self, start_frame):
# Figure out where to start.
self.cur_frame = start_frame
if self.parameters.hasAttr("start_frame"):
if (self.parameters.getAttr("start_frame") > self.cur_frame):
if (self.parameters.getAttr("start_frame") < self.movie_l):
self.cur_frame = self.parameters.getAttr("start_frame") - 1
# Figure out where to stop.
self.max_frame = self.movie_l
if self.parameters.hasAttr("max_frame"):
if (self.parameters.getAttr("max_frame") > 0):
if (self.parameters.getAttr("max_frame") < self.movie_l):
self.max_frame = self.parameters.getAttr("max_frame")
# Configure background estimator, if any.
if (self.parameters.getAttr("static_background_estimate", 0) > 0):
print("Using static background estimator.")
s_size = self.parameters.getAttr("static_background_estimate")
self.bg_estimator = static_background.StaticBGEstimator(self.frame_reader,
start_frame = self.cur_frame,
sample_size = s_size)
| [
"numpy.ones_like",
"os.path.exists",
"storm_analysis.sa_library.datareader.inferReader",
"storm_analysis.sa_library.sa_h5py.SAH5Py",
"xml.etree.ElementTree.tostring",
"numpy.max",
"numpy.sum",
"storm_analysis.sa_library.static_background.StaticBGEstimator",
"storm_analysis.sa_library.writeinsight3.I... | [((772, 811), 'numpy.load', 'numpy.load', (['filename'], {'allow_pickle': '(True)'}), '(filename, allow_pickle=True)\n', (782, 811), False, 'import numpy\n'), ((1416, 1455), 'numpy.load', 'numpy.load', (['filename'], {'allow_pickle': '(True)'}), '(filename, allow_pickle=True)\n', (1426, 1455), False, 'import numpy\n'), ((1631, 1655), 'numpy.ones_like', 'numpy.ones_like', (['data[0]'], {}), '(data[0])\n', (1646, 1655), False, 'import numpy\n'), ((3320, 3349), 'os.path.exists', 'os.path.exists', (['self.filename'], {}), '(self.filename)\n', (3334, 3349), False, 'import os\n'), ((5725, 5754), 'os.path.exists', 'os.path.exists', (['self.filename'], {}), '(self.filename)\n', (5739, 5754), False, 'import os\n'), ((7544, 7578), 'storm_analysis.sa_library.datareader.inferReader', 'datareader.inferReader', (['movie_file'], {}), '(movie_file)\n', (7566, 7578), True, 'import storm_analysis.sa_library.datareader as datareader\n'), ((3461, 3498), 'storm_analysis.sa_library.sa_h5py.SAH5Py', 'saH5Py.SAH5Py', ([], {'filename': 'self.filename'}), '(filename=self.filename)\n', (3474, 3498), True, 'import storm_analysis.sa_library.sa_h5py as saH5Py\n'), ((3835, 3908), 'storm_analysis.sa_library.sa_h5py.SAH5Py', 'saH5Py.SAH5Py', ([], {'filename': 'self.filename', 'is_existing': '(False)', 'sa_type': 'sa_type'}), '(filename=self.filename, is_existing=False, sa_type=sa_type)\n', (3848, 3908), True, 'import storm_analysis.sa_library.sa_h5py as saH5Py\n'), ((5823, 5861), 'storm_analysis.sa_library.readinsight3.loadI3File', 'readinsight3.loadI3File', (['self.filename'], {}), '(self.filename)\n', (5846, 5861), True, 'import storm_analysis.sa_library.readinsight3 as readinsight3\n'), ((6140, 6177), 'storm_analysis.sa_library.writeinsight3.I3Writer', 'writeinsight3.I3Writer', (['self.filename'], {}), '(self.filename)\n', (6162, 6177), True, 'import storm_analysis.sa_library.writeinsight3 as writeinsight3\n'), ((6397, 6434), 'storm_analysis.sa_library.writeinsight3.I3Writer', 'writeinsight3.I3Writer', (['self.filename'], {}), '(self.filename)\n', (6419, 6434), True, 'import storm_analysis.sa_library.writeinsight3 as writeinsight3\n'), ((8199, 8214), 'numpy.sum', 'numpy.sum', (['mask'], {}), '(mask)\n', (8208, 8214), False, 'import numpy\n'), ((12433, 12540), 'storm_analysis.sa_library.static_background.StaticBGEstimator', 'static_background.StaticBGEstimator', (['self.frame_reader'], {'start_frame': 'self.cur_frame', 'sample_size': 's_size'}), '(self.frame_reader, start_frame=self.\n cur_frame, sample_size=s_size)\n', (12468, 12540), True, 'import storm_analysis.sa_library.static_background as static_background\n'), ((1983, 2007), 'numpy.ones_like', 'numpy.ones_like', (['data[0]'], {}), '(data[0])\n', (1998, 2007), False, 'import numpy\n'), ((4175, 4213), 'xml.etree.ElementTree.tostring', 'ElementTree.tostring', (['etree', '"""unicode"""'], {}), "(etree, 'unicode')\n", (4195, 4213), False, 'from xml.etree import ElementTree\n'), ((4269, 4310), 'xml.etree.ElementTree.tostring', 'ElementTree.tostring', (['etree', '"""ISO-8859-1"""'], {}), "(etree, 'ISO-8859-1')\n", (4289, 4310), False, 'from xml.etree import ElementTree\n'), ((6017, 6043), 'numpy.max', 'numpy.max', (["i3data_in['fr']"], {}), "(i3data_in['fr'])\n", (6026, 6043), False, 'import numpy\n')] |
"""
Credits:
Copyright (c) 2017-2022 <NAME>, <NAME>, <NAME>, <NAME>, <NAME> (Sinergise)
Copyright (c) 2017-2022 <NAME>, <NAME>, <NAME>, <NAME>, <NAME> (Sinergise)
Copyright (c) 2019-2020 <NAME>, <NAME> (Sinergise)
Copyright (c) 2017-2019 <NAME>, <NAME>, <NAME> (Sinergise)
This source code is licensed under the MIT license found in the LICENSE
file in the root directory of this source tree.
"""
import pytest
import numpy as np
from eolearn.core import FeatureType
from eolearn.mask import SnowMaskTask, TheiaSnowMaskTask
@pytest.mark.parametrize("params", [{"dem_params": (100, 100, 100)}, {"red_params": 45}, {"ndsi_params": (0.2, 3)}])
def test_raises_errors(params, test_eopatch):
with pytest.raises(ValueError):
theia_mask = TheiaSnowMaskTask(
(FeatureType.DATA, "BANDS-S2-L1C"),
[2, 3, 11],
(FeatureType.MASK, "CLM"),
(FeatureType.DATA_TIMELESS, "DEM"),
**params
)
theia_mask(test_eopatch)
@pytest.mark.parametrize(
"task, result",
[
(SnowMaskTask((FeatureType.DATA, "BANDS-S2-L1C"), [2, 3, 7, 11], mask_name="TEST_SNOW_MASK"), (50468, 1405)),
(
TheiaSnowMaskTask(
(FeatureType.DATA, "BANDS-S2-L1C"),
[2, 3, 11],
(FeatureType.MASK, "CLM"),
(FeatureType.DATA_TIMELESS, "DEM"),
b10_index=10,
mask_name="TEST_THEIA_SNOW_MASK",
),
(60682, 10088),
),
],
)
def test_snow_coverage(task, result, test_eopatch):
resulting_eopatch = task(test_eopatch)
output = resulting_eopatch[task.mask_feature]
assert output.ndim == 4
assert output.shape[:-1] == test_eopatch.data["BANDS-S2-L1C"].shape[:-1]
assert output.shape[-1] == 1
assert output.dtype == bool
snow_pixels = np.sum(output, axis=(1, 2, 3))
assert np.sum(snow_pixels) == result[0], "Sum of snowy pixels does not match"
assert snow_pixels[-4] == result[1], "Snowy pixels on specified frame do not match"
| [
"eolearn.mask.SnowMaskTask",
"pytest.mark.parametrize",
"numpy.sum",
"pytest.raises",
"eolearn.mask.TheiaSnowMaskTask"
] | [((529, 649), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""params"""', "[{'dem_params': (100, 100, 100)}, {'red_params': 45}, {'ndsi_params': (0.2, 3)}\n ]"], {}), "('params', [{'dem_params': (100, 100, 100)}, {\n 'red_params': 45}, {'ndsi_params': (0.2, 3)}])\n", (552, 649), False, 'import pytest\n'), ((1857, 1887), 'numpy.sum', 'np.sum', (['output'], {'axis': '(1, 2, 3)'}), '(output, axis=(1, 2, 3))\n', (1863, 1887), True, 'import numpy as np\n'), ((700, 725), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (713, 725), False, 'import pytest\n'), ((748, 891), 'eolearn.mask.TheiaSnowMaskTask', 'TheiaSnowMaskTask', (["(FeatureType.DATA, 'BANDS-S2-L1C')", '[2, 3, 11]', "(FeatureType.MASK, 'CLM')", "(FeatureType.DATA_TIMELESS, 'DEM')"], {}), "((FeatureType.DATA, 'BANDS-S2-L1C'), [2, 3, 11], (\n FeatureType.MASK, 'CLM'), (FeatureType.DATA_TIMELESS, 'DEM'), **params)\n", (765, 891), False, 'from eolearn.mask import SnowMaskTask, TheiaSnowMaskTask\n'), ((1899, 1918), 'numpy.sum', 'np.sum', (['snow_pixels'], {}), '(snow_pixels)\n', (1905, 1918), True, 'import numpy as np\n'), ((1053, 1149), 'eolearn.mask.SnowMaskTask', 'SnowMaskTask', (["(FeatureType.DATA, 'BANDS-S2-L1C')", '[2, 3, 7, 11]'], {'mask_name': '"""TEST_SNOW_MASK"""'}), "((FeatureType.DATA, 'BANDS-S2-L1C'), [2, 3, 7, 11], mask_name=\n 'TEST_SNOW_MASK')\n", (1065, 1149), False, 'from eolearn.mask import SnowMaskTask, TheiaSnowMaskTask\n'), ((1184, 1370), 'eolearn.mask.TheiaSnowMaskTask', 'TheiaSnowMaskTask', (["(FeatureType.DATA, 'BANDS-S2-L1C')", '[2, 3, 11]', "(FeatureType.MASK, 'CLM')", "(FeatureType.DATA_TIMELESS, 'DEM')"], {'b10_index': '(10)', 'mask_name': '"""TEST_THEIA_SNOW_MASK"""'}), "((FeatureType.DATA, 'BANDS-S2-L1C'), [2, 3, 11], (\n FeatureType.MASK, 'CLM'), (FeatureType.DATA_TIMELESS, 'DEM'), b10_index\n =10, mask_name='TEST_THEIA_SNOW_MASK')\n", (1201, 1370), False, 'from eolearn.mask import SnowMaskTask, TheiaSnowMaskTask\n')] |
"""
MS COCO object detection dataset.
"""
import os
import cv2
import logging
import mxnet as mx
import numpy as np
from PIL import Image
import torch.utils.data as data
from .dataset_metainfo import DatasetMetaInfo
__all__ = ['CocoDetMetaInfo']
class CocoDetDataset(data.Dataset):
"""
MS COCO detection dataset.
Parameters
----------
root : str
Path to folder storing the dataset.
mode : string, default 'train'
'train', 'val', 'test', or 'demo'.
transform : callable, optional
A function that transforms the image.
splits : list of str, default ['instances_val2017']
Json annotations name.
Candidates can be: instances_val2017, instances_train2017.
min_object_area : float
Minimum accepted ground-truth area, if an object's area is smaller than this value,
it will be ignored.
skip_empty : bool, default is True
Whether skip images with no valid object. This should be `True` in training, otherwise
it will cause undefined behavior.
use_crowd : bool, default is True
Whether use boxes labeled as crowd instance.
"""
CLASSES = ['person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train',
'truck', 'boat', 'traffic light', 'fire hydrant', 'stop sign',
'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep',
'cow', 'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella',
'handbag', 'tie', 'suitcase', 'frisbee', 'skis', 'snowboard',
'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard',
'surfboard', 'tennis racket', 'bottle', 'wine glass', 'cup', 'fork',
'knife', 'spoon', 'bowl', 'banana', 'apple', 'sandwich', 'orange',
'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair',
'couch', 'potted plant', 'bed', 'dining table', 'toilet', 'tv',
'laptop', 'mouse', 'remote', 'keyboard', 'cell phone', 'microwave',
'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase',
'scissors', 'teddy bear', 'hair drier', 'toothbrush']
def __init__(self,
root,
mode="train",
transform=None,
splits=('instances_val2017',),
min_object_area=0,
skip_empty=True,
use_crowd=True):
super(CocoDetDataset, self).__init__()
self._root = os.path.expanduser(root)
self.mode = mode
self._transform = transform
self.num_class = len(self.CLASSES)
self._min_object_area = min_object_area
self._skip_empty = skip_empty
self._use_crowd = use_crowd
if isinstance(splits, mx.base.string_types):
splits = [splits]
self._splits = splits
self.index_map = dict(zip(type(self).CLASSES, range(self.num_class)))
self.json_id_to_contiguous = None
self.contiguous_id_to_json = None
self._coco = []
self._items, self._labels, self._im_aspect_ratios = self._load_jsons()
mode_name = "train" if mode == "train" else "val"
annotations_dir_path = os.path.join(root, "annotations")
annotations_file_path = os.path.join(annotations_dir_path, "instances_" + mode_name + "2017.json")
self.annotations_file_path = annotations_file_path
def __str__(self):
detail = ','.join([str(s) for s in self._splits])
return self.__class__.__name__ + '(' + detail + ')'
@property
def coco(self):
"""
Return pycocotools object for evaluation purposes.
"""
if not self._coco:
raise ValueError("No coco objects found, dataset not initialized.")
if len(self._coco) > 1:
raise NotImplementedError(
"Currently we don't support evaluating {} JSON files. \
Please use single JSON dataset and evaluate one by one".format(len(self._coco)))
return self._coco[0]
@property
def classes(self):
"""
Category names.
"""
return type(self).CLASSES
@property
def annotation_dir(self):
"""
The subdir for annotations. Default is 'annotations'(coco default)
For example, a coco format json file will be searched as
'root/annotation_dir/xxx.json'
You can override if custom dataset don't follow the same pattern
"""
return 'annotations'
def get_im_aspect_ratio(self):
"""Return the aspect ratio of each image in the order of the raw data."""
if self._im_aspect_ratios is not None:
return self._im_aspect_ratios
self._im_aspect_ratios = [None] * len(self._items)
for i, img_path in enumerate(self._items):
with Image.open(img_path) as im:
w, h = im.size
self._im_aspect_ratios[i] = 1.0 * w / h
return self._im_aspect_ratios
def _parse_image_path(self, entry):
"""How to parse image dir and path from entry.
Parameters
----------
entry : dict
COCO entry, e.g. including width, height, image path, etc..
Returns
-------
abs_path : str
Absolute path for corresponding image.
"""
dirname, filename = entry["coco_url"].split("/")[-2:]
abs_path = os.path.join(self._root, dirname, filename)
return abs_path
def __len__(self):
return len(self._items)
def __getitem__(self, idx):
img_path = self._items[idx]
label = self._labels[idx]
# img = mx.image.imread(img_path, 1)
img = cv2.imread(img_path, flags=cv2.IMREAD_COLOR)
label = np.array(label).copy()
if self._transform is not None:
img, label = self._transform(img, label)
return img, label
def _load_jsons(self):
"""
Load all image paths and labels from JSON annotation files into buffer.
"""
items = []
labels = []
im_aspect_ratios = []
from pycocotools.coco import COCO
for split in self._splits:
anno = os.path.join(self._root, self.annotation_dir, split) + ".json"
_coco = COCO(anno)
self._coco.append(_coco)
classes = [c["name"] for c in _coco.loadCats(_coco.getCatIds())]
if not classes == self.classes:
raise ValueError("Incompatible category names with COCO: ")
assert classes == self.classes
json_id_to_contiguous = {
v: k for k, v in enumerate(_coco.getCatIds())}
if self.json_id_to_contiguous is None:
self.json_id_to_contiguous = json_id_to_contiguous
self.contiguous_id_to_json = {
v: k for k, v in self.json_id_to_contiguous.items()}
else:
assert self.json_id_to_contiguous == json_id_to_contiguous
# iterate through the annotations
image_ids = sorted(_coco.getImgIds())
for entry in _coco.loadImgs(image_ids):
abs_path = self._parse_image_path(entry)
if not os.path.exists(abs_path):
raise IOError("Image: {} not exists.".format(abs_path))
label = self._check_load_bbox(_coco, entry)
if not label:
continue
im_aspect_ratios.append(float(entry["width"]) / entry["height"])
items.append(abs_path)
labels.append(label)
return items, labels, im_aspect_ratios
def _check_load_bbox(self, coco, entry):
"""
Check and load ground-truth labels.
"""
entry_id = entry['id']
# fix pycocotools _isArrayLike which don't work for str in python3
entry_id = [entry_id] if not isinstance(entry_id, (list, tuple)) else entry_id
ann_ids = coco.getAnnIds(imgIds=entry_id, iscrowd=None)
objs = coco.loadAnns(ann_ids)
# check valid bboxes
valid_objs = []
width = entry["width"]
height = entry["height"]
for obj in objs:
if obj["area"] < self._min_object_area:
continue
if obj.get("ignore", 0) == 1:
continue
if not self._use_crowd and obj.get("iscrowd", 0):
continue
# convert from (x, y, w, h) to (xmin, ymin, xmax, ymax) and clip bound
xmin, ymin, xmax, ymax = self.bbox_clip_xyxy(self.bbox_xywh_to_xyxy(obj["bbox"]), width, height)
# require non-zero box area
if obj["area"] > 0 and xmax > xmin and ymax > ymin:
contiguous_cid = self.json_id_to_contiguous[obj["category_id"]]
valid_objs.append([xmin, ymin, xmax, ymax, contiguous_cid])
if not valid_objs:
if not self._skip_empty:
# dummy invalid labels if no valid objects are found
valid_objs.append([-1, -1, -1, -1, -1])
return valid_objs
@staticmethod
def bbox_clip_xyxy(xyxy, width, height):
"""
Clip bounding box with format (xmin, ymin, xmax, ymax) to specified boundary.
All bounding boxes will be clipped to the new region `(0, 0, width, height)`.
Parameters
----------
xyxy : list, tuple or numpy.ndarray
The bbox in format (xmin, ymin, xmax, ymax).
If numpy.ndarray is provided, we expect multiple bounding boxes with
shape `(N, 4)`.
width : int or float
Boundary width.
height : int or float
Boundary height.
Returns
-------
tuple or np.array
Description of returned object.
"""
if isinstance(xyxy, (tuple, list)):
if not len(xyxy) == 4:
raise IndexError("Bounding boxes must have 4 elements, given {}".format(len(xyxy)))
x1 = np.minimum(width - 1, np.maximum(0, xyxy[0]))
y1 = np.minimum(height - 1, np.maximum(0, xyxy[1]))
x2 = np.minimum(width - 1, np.maximum(0, xyxy[2]))
y2 = np.minimum(height - 1, np.maximum(0, xyxy[3]))
return x1, y1, x2, y2
elif isinstance(xyxy, np.ndarray):
if not xyxy.size % 4 == 0:
raise IndexError("Bounding boxes must have n * 4 elements, given {}".format(xyxy.shape))
x1 = np.minimum(width - 1, np.maximum(0, xyxy[:, 0]))
y1 = np.minimum(height - 1, np.maximum(0, xyxy[:, 1]))
x2 = np.minimum(width - 1, np.maximum(0, xyxy[:, 2]))
y2 = np.minimum(height - 1, np.maximum(0, xyxy[:, 3]))
return np.hstack((x1, y1, x2, y2))
else:
raise TypeError("Expect input xywh a list, tuple or numpy.ndarray, given {}".format(type(xyxy)))
@staticmethod
def bbox_xywh_to_xyxy(xywh):
"""
Convert bounding boxes from format (xmin, ymin, w, h) to (xmin, ymin, xmax, ymax)
Parameters
----------
xywh : list, tuple or numpy.ndarray
The bbox in format (x, y, w, h).
If numpy.ndarray is provided, we expect multiple bounding boxes with
shape `(N, 4)`.
Returns
-------
tuple or np.ndarray
The converted bboxes in format (xmin, ymin, xmax, ymax).
If input is numpy.ndarray, return is numpy.ndarray correspondingly.
"""
if isinstance(xywh, (tuple, list)):
if not len(xywh) == 4:
raise IndexError("Bounding boxes must have 4 elements, given {}".format(len(xywh)))
w, h = np.maximum(xywh[2] - 1, 0), np.maximum(xywh[3] - 1, 0)
return xywh[0], xywh[1], xywh[0] + w, xywh[1] + h
elif isinstance(xywh, np.ndarray):
if not xywh.size % 4 == 0:
raise IndexError("Bounding boxes must have n * 4 elements, given {}".format(xywh.shape))
xyxy = np.hstack((xywh[:, :2], xywh[:, :2] + np.maximum(0, xywh[:, 2:4] - 1)))
return xyxy
else:
raise TypeError("Expect input xywh a list, tuple or numpy.ndarray, given {}".format(type(xywh)))
# ---------------------------------------------------------------------------------------------------------------------
class CocoDetValTransform(object):
def __init__(self,
ds_metainfo):
self.ds_metainfo = ds_metainfo
self.image_size = self.ds_metainfo.input_image_size
self._height = self.image_size[0]
self._width = self.image_size[1]
self._mean = np.array(ds_metainfo.mean_rgb, dtype=np.float32).reshape(1, 1, 3)
self._std = np.array(ds_metainfo.std_rgb, dtype=np.float32).reshape(1, 1, 3)
def __call__(self, src, label):
# resize
img, bbox = src, label
input_h, input_w = self._height, self._width
h, w, _ = src.shape
s = max(h, w) * 1.0
c = np.array([w / 2., h / 2.], dtype=np.float32)
trans_input = self.get_affine_transform(c, s, 0, [input_w, input_h])
inp = cv2.warpAffine(img, trans_input, (input_w, input_h), flags=cv2.INTER_LINEAR)
output_w = input_w
output_h = input_h
trans_output = self.get_affine_transform(c, s, 0, [output_w, output_h])
for i in range(bbox.shape[0]):
bbox[i, :2] = self.affine_transform(bbox[i, :2], trans_output)
bbox[i, 2:4] = self.affine_transform(bbox[i, 2:4], trans_output)
bbox[:, :2] = np.clip(bbox[:, :2], 0, output_w - 1)
bbox[:, 2:4] = np.clip(bbox[:, 2:4], 0, output_h - 1)
img = inp
# to tensor
img = img.astype(np.float32) / 255.0
img = (img - self._mean) / self._std
img = img.transpose(2, 0, 1).astype(np.float32)
img = img
return img, bbox.astype(img.dtype)
@staticmethod
def get_affine_transform(center,
scale,
rot,
output_size,
shift=np.array([0, 0], dtype=np.float32),
inv=0):
"""
Get affine transform matrix given center, scale and rotation.
Parameters
----------
center : tuple of float
Center point.
scale : float
Scaling factor.
rot : float
Rotation degree.
output_size : tuple of int
(width, height) of the output size.
shift : float
Shift factor.
inv : bool
Whether inverse the computation.
Returns
-------
numpy.ndarray
Affine matrix.
"""
if not isinstance(scale, np.ndarray) and not isinstance(scale, list):
scale = np.array([scale, scale], dtype=np.float32)
scale_tmp = scale
src_w = scale_tmp[0]
dst_w = output_size[0]
dst_h = output_size[1]
rot_rad = np.pi * rot / 180
src_dir = CocoDetValTransform.get_rot_dir([0, src_w * -0.5], rot_rad)
dst_dir = np.array([0, dst_w * -0.5], np.float32)
src = np.zeros((3, 2), dtype=np.float32)
dst = np.zeros((3, 2), dtype=np.float32)
src[0, :] = center + scale_tmp * shift
src[1, :] = center + src_dir + scale_tmp * shift
dst[0, :] = [dst_w * 0.5, dst_h * 0.5]
dst[1, :] = np.array([dst_w * 0.5, dst_h * 0.5], np.float32) + dst_dir
src[2:, :] = CocoDetValTransform.get_3rd_point(src[0, :], src[1, :])
dst[2:, :] = CocoDetValTransform.get_3rd_point(dst[0, :], dst[1, :])
if inv:
trans = cv2.getAffineTransform(np.float32(dst), np.float32(src))
else:
trans = cv2.getAffineTransform(np.float32(src), np.float32(dst))
return trans
@staticmethod
def get_rot_dir(src_point, rot_rad):
"""
Get rotation direction.
Parameters
----------
src_point : tuple of float
Original point.
rot_rad : float
Rotation radian.
Returns
-------
tuple of float
Rotation.
"""
sn, cs = np.sin(rot_rad), np.cos(rot_rad)
src_result = [0, 0]
src_result[0] = src_point[0] * cs - src_point[1] * sn
src_result[1] = src_point[0] * sn + src_point[1] * cs
return src_result
@staticmethod
def get_3rd_point(a, b):
"""
Get the 3rd point position given first two points.
Parameters
----------
a : tuple of float
First point.
b : tuple of float
Second point.
Returns
-------
tuple of float
Third point.
"""
direct = a - b
return b + np.array([-direct[1], direct[0]], dtype=np.float32)
@staticmethod
def affine_transform(pt, t):
"""
Apply affine transform to a bounding box given transform matrix t.
Parameters
----------
pt : numpy.ndarray
Bounding box with shape (1, 2).
t : numpy.ndarray
Transformation matrix with shape (2, 3).
Returns
-------
numpy.ndarray
New bounding box with shape (1, 2).
"""
new_pt = np.array([pt[0], pt[1], 1.], dtype=np.float32).T
new_pt = np.dot(t, new_pt)
return new_pt[:2]
class Tuple(object):
"""
Wrap multiple batchify functions to form a function apply each input function on each
input fields respectively.
"""
def __init__(self, fn, *args):
if isinstance(fn, (list, tuple)):
self._fn = fn
else:
self._fn = (fn,) + args
def __call__(self, data):
"""
Batchify the input data.
Parameters
----------
data : list
The samples to batchfy. Each sample should contain N attributes.
Returns
-------
tuple
A tuple of length N. Contains the batchified result of each attribute in the input.
"""
ret = []
for i, ele_fn in enumerate(self._fn):
ret.append(ele_fn([ele[i] for ele in data]))
return tuple(ret)
class Stack(object):
"""
Stack the input data samples to construct the batch.
"""
def __call__(self, data):
"""
Batchify the input data.
Parameters
----------
data : list
The input data samples
Returns
-------
NDArray
Result.
"""
return self._stack_arrs(data, True)
@staticmethod
def _stack_arrs(arrs, use_shared_mem=False):
"""
Internal imple for stacking arrays.
"""
if isinstance(arrs[0], mx.nd.NDArray):
if use_shared_mem:
out = mx.nd.empty((len(arrs),) + arrs[0].shape, dtype=arrs[0].dtype,
ctx=mx.Context("cpu_shared", 0))
return mx.nd.stack(*arrs, out=out)
else:
return mx.nd.stack(*arrs)
else:
out = np.asarray(arrs)
if use_shared_mem:
return mx.nd.array(out, ctx=mx.Context("cpu_shared", 0))
else:
return mx.nd.array(out)
class Pad(object):
"""
Pad the input ndarrays along the specific padding axis and stack them to get the output.
"""
def __init__(self, axis=0, pad_val=0, num_shards=1, ret_length=False):
self._axis = axis
self._pad_val = pad_val
self._num_shards = num_shards
self._ret_length = ret_length
def __call__(self, data):
"""
Batchify the input data.
Parameters
----------
data : list
A list of N samples. Each sample can be 1) ndarray or
2) a list/tuple of ndarrays
Returns
-------
NDArray
Data in the minibatch. Shape is (N, ...)
NDArray, optional
The sequences' original lengths at the padded axis. Shape is (N,). This will only be
returned in `ret_length` is True.
"""
if isinstance(data[0], (mx.nd.NDArray, np.ndarray, list)):
padded_arr, original_length = self._pad_arrs_to_max_length(
data, self._axis, self._pad_val, self._num_shards, True)
if self._ret_length:
return padded_arr, original_length
else:
return padded_arr
else:
raise NotImplementedError
@staticmethod
def _pad_arrs_to_max_length(arrs, pad_axis, pad_val, num_shards=1, use_shared_mem=False):
"""
Inner Implementation of the Pad batchify.
"""
if not isinstance(arrs[0], (mx.nd.NDArray, np.ndarray)):
arrs = [np.asarray(ele) for ele in arrs]
if isinstance(pad_axis, tuple):
original_length = []
for axis in pad_axis:
original_length.append(np.array([ele.shape[axis] for ele in arrs]))
original_length = np.stack(original_length).T
else:
original_length = np.array([ele.shape[pad_axis] for ele in arrs])
pad_axis = [pad_axis]
if len(original_length) % num_shards != 0:
logging.warning(
'Batch size cannot be evenly split. Trying to shard %d items into %d shards',
len(original_length), num_shards)
original_length = np.array_split(original_length, num_shards)
max_lengths = [np.max(ll, axis=0, keepdims=len(pad_axis) == 1) for ll in original_length]
# add batch dimension
ret_shape = [[ll.shape[0], ] + list(arrs[0].shape) for ll in original_length]
for i, shape in enumerate(ret_shape):
for j, axis in enumerate(pad_axis):
shape[1 + axis] = max_lengths[i][j]
if use_shared_mem:
ret = [mx.nd.full(shape=tuple(shape), val=pad_val, ctx=mx.Context('cpu_shared', 0),
dtype=arrs[0].dtype) for shape in ret_shape]
original_length = [mx.nd.array(ll, ctx=mx.Context('cpu_shared', 0),
dtype=np.int32) for ll in original_length]
else:
ret = [mx.nd.full(shape=tuple(shape), val=pad_val, dtype=arrs[0].dtype) for shape in
ret_shape]
original_length = [mx.nd.array(ll, dtype=np.int32) for ll in original_length]
for i, arr in enumerate(arrs):
if ret[i // ret[0].shape[0]].shape[1:] == arr.shape:
ret[i // ret[0].shape[0]][i % ret[0].shape[0]] = arr
else:
slices = [slice(0, ll) for ll in arr.shape]
ret[i // ret[0].shape[0]][i % ret[0].shape[0]][tuple(slices)] = arr
if len(ret) == len(original_length) == 1:
return ret[0], original_length[0]
return ret, original_length
def get_post_transform(orig_w, orig_h, out_w, out_h):
"""Get the post prediction affine transforms. This will be used to adjust the prediction results
according to original coco image resolutions.
Parameters
----------
orig_w : int
Original width of the image.
orig_h : int
Original height of the image.
out_w : int
Width of the output image after prediction.
out_h : int
Height of the output image after prediction.
Returns
-------
numpy.ndarray
Affine transform matrix 3x2.
"""
s = max(orig_w, orig_h) * 1.0
c = np.array([orig_w / 2., orig_h / 2.], dtype=np.float32)
trans_output = CocoDetValTransform.get_affine_transform(c, s, 0, [out_w, out_h], inv=True)
return trans_output
class CocoDetMetaInfo(DatasetMetaInfo):
def __init__(self):
super(CocoDetMetaInfo, self).__init__()
self.label = "COCO"
self.short_label = "coco"
self.root_dir_name = "coco"
self.dataset_class = CocoDetDataset
self.num_training_samples = None
self.in_channels = 3
self.num_classes = CocoDetDataset.classes
self.input_image_size = (512, 512)
self.train_metric_capts = None
self.train_metric_names = None
self.train_metric_extra_kwargs = None
self.val_metric_capts = None
self.val_metric_names = None
self.test_metric_capts = ["Val.mAP"]
self.test_metric_names = ["CocoDetMApMetric"]
self.test_metric_extra_kwargs = [
{"name": "mAP",
"img_height": 512,
"coco_annotations_file_path": None,
"contiguous_id_to_json": None,
"data_shape": None,
"post_affine": get_post_transform}]
self.test_dataset_extra_kwargs =\
{"skip_empty": False}
self.saver_acc_ind = 0
self.do_transform = True
self.do_transform_first = False
self.last_batch = "keep"
self.batchify_fn = Tuple(Stack(), Pad(pad_val=-1))
self.val_transform = CocoDetValTransform
self.test_transform = CocoDetValTransform
self.ml_type = "hpe"
self.allow_hybridize = False
self.net_extra_kwargs = {}
self.mean_rgb = (0.485, 0.456, 0.406)
self.std_rgb = (0.229, 0.224, 0.225)
def add_dataset_parser_arguments(self,
parser,
work_dir_path):
"""
Create python script parameters (for ImageNet-1K dataset metainfo).
Parameters:
----------
parser : ArgumentParser
ArgumentParser instance.
work_dir_path : str
Path to working directory.
"""
super(CocoDetMetaInfo, self).add_dataset_parser_arguments(parser, work_dir_path)
parser.add_argument(
"--input-size",
type=int,
nargs=2,
default=self.input_image_size,
help="size of the input for model")
def update(self,
args):
"""
Update ImageNet-1K dataset metainfo after user customizing.
Parameters:
----------
args : ArgumentParser
Main script arguments.
"""
super(CocoDetMetaInfo, self).update(args)
self.input_image_size = args.input_size
self.test_metric_extra_kwargs[0]["img_height"] = self.input_image_size[0]
self.test_metric_extra_kwargs[0]["data_shape"] = self.input_image_size
def update_from_dataset(self,
dataset):
"""
Update dataset metainfo after a dataset class instance creation.
Parameters:
----------
args : obj
A dataset class instance.
"""
self.test_metric_extra_kwargs[0]["coco_annotations_file_path"] = dataset.annotations_file_path
self.test_metric_extra_kwargs[0]["contiguous_id_to_json"] = dataset.contiguous_id_to_json
| [
"numpy.clip",
"mxnet.Context",
"numpy.hstack",
"numpy.array_split",
"numpy.array",
"numpy.sin",
"os.path.exists",
"pycocotools.coco.COCO",
"numpy.asarray",
"numpy.stack",
"numpy.dot",
"mxnet.nd.array",
"numpy.maximum",
"os.path.expanduser",
"mxnet.nd.stack",
"cv2.warpAffine",
"numpy.... | [((23766, 23822), 'numpy.array', 'np.array', (['[orig_w / 2.0, orig_h / 2.0]'], {'dtype': 'np.float32'}), '([orig_w / 2.0, orig_h / 2.0], dtype=np.float32)\n', (23774, 23822), True, 'import numpy as np\n'), ((2537, 2561), 'os.path.expanduser', 'os.path.expanduser', (['root'], {}), '(root)\n', (2555, 2561), False, 'import os\n'), ((3257, 3290), 'os.path.join', 'os.path.join', (['root', '"""annotations"""'], {}), "(root, 'annotations')\n", (3269, 3290), False, 'import os\n'), ((3323, 3397), 'os.path.join', 'os.path.join', (['annotations_dir_path', "('instances_' + mode_name + '2017.json')"], {}), "(annotations_dir_path, 'instances_' + mode_name + '2017.json')\n", (3335, 3397), False, 'import os\n'), ((5480, 5523), 'os.path.join', 'os.path.join', (['self._root', 'dirname', 'filename'], {}), '(self._root, dirname, filename)\n', (5492, 5523), False, 'import os\n'), ((5766, 5810), 'cv2.imread', 'cv2.imread', (['img_path'], {'flags': 'cv2.IMREAD_COLOR'}), '(img_path, flags=cv2.IMREAD_COLOR)\n', (5776, 5810), False, 'import cv2\n'), ((13118, 13164), 'numpy.array', 'np.array', (['[w / 2.0, h / 2.0]'], {'dtype': 'np.float32'}), '([w / 2.0, h / 2.0], dtype=np.float32)\n', (13126, 13164), True, 'import numpy as np\n'), ((13254, 13330), 'cv2.warpAffine', 'cv2.warpAffine', (['img', 'trans_input', '(input_w, input_h)'], {'flags': 'cv2.INTER_LINEAR'}), '(img, trans_input, (input_w, input_h), flags=cv2.INTER_LINEAR)\n', (13268, 13330), False, 'import cv2\n'), ((13678, 13715), 'numpy.clip', 'np.clip', (['bbox[:, :2]', '(0)', '(output_w - 1)'], {}), '(bbox[:, :2], 0, output_w - 1)\n', (13685, 13715), True, 'import numpy as np\n'), ((13739, 13777), 'numpy.clip', 'np.clip', (['bbox[:, 2:4]', '(0)', '(output_h - 1)'], {}), '(bbox[:, 2:4], 0, output_h - 1)\n', (13746, 13777), True, 'import numpy as np\n'), ((14227, 14261), 'numpy.array', 'np.array', (['[0, 0]'], {'dtype': 'np.float32'}), '([0, 0], dtype=np.float32)\n', (14235, 14261), True, 'import numpy as np\n'), ((15259, 15298), 'numpy.array', 'np.array', (['[0, dst_w * -0.5]', 'np.float32'], {}), '([0, dst_w * -0.5], np.float32)\n', (15267, 15298), True, 'import numpy as np\n'), ((15314, 15348), 'numpy.zeros', 'np.zeros', (['(3, 2)'], {'dtype': 'np.float32'}), '((3, 2), dtype=np.float32)\n', (15322, 15348), True, 'import numpy as np\n'), ((15363, 15397), 'numpy.zeros', 'np.zeros', (['(3, 2)'], {'dtype': 'np.float32'}), '((3, 2), dtype=np.float32)\n', (15371, 15397), True, 'import numpy as np\n'), ((17544, 17561), 'numpy.dot', 'np.dot', (['t', 'new_pt'], {}), '(t, new_pt)\n', (17550, 17561), True, 'import numpy as np\n'), ((21685, 21728), 'numpy.array_split', 'np.array_split', (['original_length', 'num_shards'], {}), '(original_length, num_shards)\n', (21699, 21728), True, 'import numpy as np\n'), ((6350, 6360), 'pycocotools.coco.COCO', 'COCO', (['anno'], {}), '(anno)\n', (6354, 6360), False, 'from pycocotools.coco import COCO\n'), ((14965, 15007), 'numpy.array', 'np.array', (['[scale, scale]'], {'dtype': 'np.float32'}), '([scale, scale], dtype=np.float32)\n', (14973, 15007), True, 'import numpy as np\n'), ((15569, 15617), 'numpy.array', 'np.array', (['[dst_w * 0.5, dst_h * 0.5]', 'np.float32'], {}), '([dst_w * 0.5, dst_h * 0.5], np.float32)\n', (15577, 15617), True, 'import numpy as np\n'), ((16355, 16370), 'numpy.sin', 'np.sin', (['rot_rad'], {}), '(rot_rad)\n', (16361, 16370), True, 'import numpy as np\n'), ((16372, 16387), 'numpy.cos', 'np.cos', (['rot_rad'], {}), '(rot_rad)\n', (16378, 16387), True, 'import numpy as np\n'), ((16966, 17017), 'numpy.array', 'np.array', (['[-direct[1], direct[0]]'], {'dtype': 'np.float32'}), '([-direct[1], direct[0]], dtype=np.float32)\n', (16974, 17017), True, 'import numpy as np\n'), ((17478, 17525), 'numpy.array', 'np.array', (['[pt[0], pt[1], 1.0]'], {'dtype': 'np.float32'}), '([pt[0], pt[1], 1.0], dtype=np.float32)\n', (17486, 17525), True, 'import numpy as np\n'), ((19312, 19328), 'numpy.asarray', 'np.asarray', (['arrs'], {}), '(arrs)\n', (19322, 19328), True, 'import numpy as np\n'), ((21353, 21400), 'numpy.array', 'np.array', (['[ele.shape[pad_axis] for ele in arrs]'], {}), '([ele.shape[pad_axis] for ele in arrs])\n', (21361, 21400), True, 'import numpy as np\n'), ((4897, 4917), 'PIL.Image.open', 'Image.open', (['img_path'], {}), '(img_path)\n', (4907, 4917), False, 'from PIL import Image\n'), ((5827, 5842), 'numpy.array', 'np.array', (['label'], {}), '(label)\n', (5835, 5842), True, 'import numpy as np\n'), ((6267, 6319), 'os.path.join', 'os.path.join', (['self._root', 'self.annotation_dir', 'split'], {}), '(self._root, self.annotation_dir, split)\n', (6279, 6319), False, 'import os\n'), ((10120, 10142), 'numpy.maximum', 'np.maximum', (['(0)', 'xyxy[0]'], {}), '(0, xyxy[0])\n', (10130, 10142), True, 'import numpy as np\n'), ((10184, 10206), 'numpy.maximum', 'np.maximum', (['(0)', 'xyxy[1]'], {}), '(0, xyxy[1])\n', (10194, 10206), True, 'import numpy as np\n'), ((10247, 10269), 'numpy.maximum', 'np.maximum', (['(0)', 'xyxy[2]'], {}), '(0, xyxy[2])\n', (10257, 10269), True, 'import numpy as np\n'), ((10311, 10333), 'numpy.maximum', 'np.maximum', (['(0)', 'xyxy[3]'], {}), '(0, xyxy[3])\n', (10321, 10333), True, 'import numpy as np\n'), ((10841, 10868), 'numpy.hstack', 'np.hstack', (['(x1, y1, x2, y2)'], {}), '((x1, y1, x2, y2))\n', (10850, 10868), True, 'import numpy as np\n'), ((11804, 11830), 'numpy.maximum', 'np.maximum', (['(xywh[2] - 1)', '(0)'], {}), '(xywh[2] - 1, 0)\n', (11814, 11830), True, 'import numpy as np\n'), ((11832, 11858), 'numpy.maximum', 'np.maximum', (['(xywh[3] - 1)', '(0)'], {}), '(xywh[3] - 1, 0)\n', (11842, 11858), True, 'import numpy as np\n'), ((12761, 12809), 'numpy.array', 'np.array', (['ds_metainfo.mean_rgb'], {'dtype': 'np.float32'}), '(ds_metainfo.mean_rgb, dtype=np.float32)\n', (12769, 12809), True, 'import numpy as np\n'), ((12847, 12894), 'numpy.array', 'np.array', (['ds_metainfo.std_rgb'], {'dtype': 'np.float32'}), '(ds_metainfo.std_rgb, dtype=np.float32)\n', (12855, 12894), True, 'import numpy as np\n'), ((15843, 15858), 'numpy.float32', 'np.float32', (['dst'], {}), '(dst)\n', (15853, 15858), True, 'import numpy as np\n'), ((15860, 15875), 'numpy.float32', 'np.float32', (['src'], {}), '(src)\n', (15870, 15875), True, 'import numpy as np\n'), ((15934, 15949), 'numpy.float32', 'np.float32', (['src'], {}), '(src)\n', (15944, 15949), True, 'import numpy as np\n'), ((15951, 15966), 'numpy.float32', 'np.float32', (['dst'], {}), '(dst)\n', (15961, 15966), True, 'import numpy as np\n'), ((19192, 19219), 'mxnet.nd.stack', 'mx.nd.stack', (['*arrs'], {'out': 'out'}), '(*arrs, out=out)\n', (19203, 19219), True, 'import mxnet as mx\n'), ((19261, 19279), 'mxnet.nd.stack', 'mx.nd.stack', (['*arrs'], {}), '(*arrs)\n', (19272, 19279), True, 'import mxnet as mx\n'), ((19474, 19490), 'mxnet.nd.array', 'mx.nd.array', (['out'], {}), '(out)\n', (19485, 19490), True, 'import mxnet as mx\n'), ((21027, 21042), 'numpy.asarray', 'np.asarray', (['ele'], {}), '(ele)\n', (21037, 21042), True, 'import numpy as np\n'), ((21281, 21306), 'numpy.stack', 'np.stack', (['original_length'], {}), '(original_length)\n', (21289, 21306), True, 'import numpy as np\n'), ((22625, 22656), 'mxnet.nd.array', 'mx.nd.array', (['ll'], {'dtype': 'np.int32'}), '(ll, dtype=np.int32)\n', (22636, 22656), True, 'import mxnet as mx\n'), ((7299, 7323), 'os.path.exists', 'os.path.exists', (['abs_path'], {}), '(abs_path)\n', (7313, 7323), False, 'import os\n'), ((10595, 10620), 'numpy.maximum', 'np.maximum', (['(0)', 'xyxy[:, 0]'], {}), '(0, xyxy[:, 0])\n', (10605, 10620), True, 'import numpy as np\n'), ((10662, 10687), 'numpy.maximum', 'np.maximum', (['(0)', 'xyxy[:, 1]'], {}), '(0, xyxy[:, 1])\n', (10672, 10687), True, 'import numpy as np\n'), ((10728, 10753), 'numpy.maximum', 'np.maximum', (['(0)', 'xyxy[:, 2]'], {}), '(0, xyxy[:, 2])\n', (10738, 10753), True, 'import numpy as np\n'), ((10795, 10820), 'numpy.maximum', 'np.maximum', (['(0)', 'xyxy[:, 3]'], {}), '(0, xyxy[:, 3])\n', (10805, 10820), True, 'import numpy as np\n'), ((21206, 21249), 'numpy.array', 'np.array', (['[ele.shape[axis] for ele in arrs]'], {}), '([ele.shape[axis] for ele in arrs])\n', (21214, 21249), True, 'import numpy as np\n'), ((19140, 19167), 'mxnet.Context', 'mx.Context', (['"""cpu_shared"""', '(0)'], {}), "('cpu_shared', 0)\n", (19150, 19167), True, 'import mxnet as mx\n'), ((19404, 19431), 'mxnet.Context', 'mx.Context', (['"""cpu_shared"""', '(0)'], {}), "('cpu_shared', 0)\n", (19414, 19431), True, 'import mxnet as mx\n'), ((22183, 22210), 'mxnet.Context', 'mx.Context', (['"""cpu_shared"""', '(0)'], {}), "('cpu_shared', 0)\n", (22193, 22210), True, 'import mxnet as mx\n'), ((22338, 22365), 'mxnet.Context', 'mx.Context', (['"""cpu_shared"""', '(0)'], {}), "('cpu_shared', 0)\n", (22348, 22365), True, 'import mxnet as mx\n'), ((12165, 12196), 'numpy.maximum', 'np.maximum', (['(0)', '(xywh[:, 2:4] - 1)'], {}), '(0, xywh[:, 2:4] - 1)\n', (12175, 12196), True, 'import numpy as np\n')] |
# ref: https://github.com/Cysu/open-reid/blob/master/reid/evaluation_metrics/ranking.py
from collections import defaultdict
from .utils import *
import numpy as np
from sklearn.metrics import average_precision_score
def _unique_sample(ids_dict, num):
mask = np.zeros(num, dtype=np.bool)
for _, indices in ids_dict.items():
i = np.random.choice(indices)
mask[i] = True
return mask
def cmc(distmat, query_ids=None, gallery_ids=None,
query_cams=None, gallery_cams=None, topk=100,
separate_camera_set=False,
single_gallery_shot=False,
first_match_break=False):
distmat = to_numpy(distmat)
m, n = distmat.shape
# Fill up default values
if query_ids is None:
query_ids = np.arange(m)
if gallery_ids is None:
gallery_ids = np.arange(n)
if query_cams is None:
query_cams = np.zeros(m).astype(np.int32)
if gallery_cams is None:
gallery_cams = np.ones(n).astype(np.int32)
# Ensure numpy array
query_ids = np.asarray(query_ids)
gallery_ids = np.asarray(gallery_ids)
query_cams = np.asarray(query_cams)
gallery_cams = np.asarray(gallery_cams)
# Sort and find correct matches
indices = np.argsort(distmat, axis=1)
matches = (gallery_ids[indices] == query_ids[:, np.newaxis])
# Compute CMC for each query
ret = np.zeros(topk)
num_valid_queries = 0
for i in range(m):
# Filter out the same id and same camera
valid = ((gallery_ids[indices[i]] != query_ids[i]) |
(gallery_cams[indices[i]] != query_cams[i]))
if separate_camera_set:
# Filter out samples from same camera
valid &= (gallery_cams[indices[i]] != query_cams[i])
if not np.any(matches[i, valid]): continue
if single_gallery_shot:
repeat = 10
gids = gallery_ids[indices[i][valid]]
inds = np.where(valid)[0]
ids_dict = defaultdict(list)
for j, x in zip(inds, gids):
ids_dict[x].append(j)
else:
repeat = 1
for _ in range(repeat):
if single_gallery_shot:
# Randomly choose one instance for each id
sampled = (valid & _unique_sample(ids_dict, len(valid)))
index = np.nonzero(matches[i, sampled])[0]
else:
index = np.nonzero(matches[i, valid])[0]
delta = 1. / (len(index) * repeat)
for j, k in enumerate(index):
if k - j >= topk: break
if first_match_break:
ret[k - j] += 1
break
ret[k - j] += delta
num_valid_queries += 1
if num_valid_queries == 0:
raise RuntimeError("No valid query")
return ret.cumsum() / num_valid_queries
def mean_ap(distmat, query_ids=None, gallery_ids=None,
query_cams=None, gallery_cams=None):
distmat = to_numpy(distmat)
m, n = distmat.shape
# Fill up default values
if query_ids is None:
query_ids = np.arange(m)
if gallery_ids is None:
gallery_ids = np.arange(n)
if query_cams is None:
query_cams = np.zeros(m).astype(np.int32)
if gallery_cams is None:
gallery_cams = np.ones(n).astype(np.int32)
# Ensure numpy array
query_ids = np.asarray(query_ids)
gallery_ids = np.asarray(gallery_ids)
query_cams = np.asarray(query_cams)
gallery_cams = np.asarray(gallery_cams)
# Sort and find correct matches
indices = np.argsort(distmat, axis=1)
matches = (gallery_ids[indices] == query_ids[:, np.newaxis])
# Compute AP for each query
aps = []
for i in range(m):
# Filter out the same id and same camera
valid = ((gallery_ids[indices[i]] != query_ids[i]) |
(gallery_cams[indices[i]] != query_cams[i]))
y_true = matches[i, valid]
y_score = -distmat[i][indices[i]][valid]
if not np.any(y_true): continue
aps.append(average_precision_score(y_true, y_score))
if len(aps) == 0:
raise RuntimeError("No valid query")
return np.mean(aps) | [
"numpy.mean",
"numpy.ones",
"numpy.random.choice",
"sklearn.metrics.average_precision_score",
"numpy.where",
"numpy.asarray",
"numpy.any",
"numpy.argsort",
"numpy.zeros",
"collections.defaultdict",
"numpy.nonzero",
"numpy.arange"
] | [((265, 293), 'numpy.zeros', 'np.zeros', (['num'], {'dtype': 'np.bool'}), '(num, dtype=np.bool)\n', (273, 293), True, 'import numpy as np\n'), ((1028, 1049), 'numpy.asarray', 'np.asarray', (['query_ids'], {}), '(query_ids)\n', (1038, 1049), True, 'import numpy as np\n'), ((1068, 1091), 'numpy.asarray', 'np.asarray', (['gallery_ids'], {}), '(gallery_ids)\n', (1078, 1091), True, 'import numpy as np\n'), ((1109, 1131), 'numpy.asarray', 'np.asarray', (['query_cams'], {}), '(query_cams)\n', (1119, 1131), True, 'import numpy as np\n'), ((1151, 1175), 'numpy.asarray', 'np.asarray', (['gallery_cams'], {}), '(gallery_cams)\n', (1161, 1175), True, 'import numpy as np\n'), ((1226, 1253), 'numpy.argsort', 'np.argsort', (['distmat'], {'axis': '(1)'}), '(distmat, axis=1)\n', (1236, 1253), True, 'import numpy as np\n'), ((1362, 1376), 'numpy.zeros', 'np.zeros', (['topk'], {}), '(topk)\n', (1370, 1376), True, 'import numpy as np\n'), ((3359, 3380), 'numpy.asarray', 'np.asarray', (['query_ids'], {}), '(query_ids)\n', (3369, 3380), True, 'import numpy as np\n'), ((3399, 3422), 'numpy.asarray', 'np.asarray', (['gallery_ids'], {}), '(gallery_ids)\n', (3409, 3422), True, 'import numpy as np\n'), ((3440, 3462), 'numpy.asarray', 'np.asarray', (['query_cams'], {}), '(query_cams)\n', (3450, 3462), True, 'import numpy as np\n'), ((3482, 3506), 'numpy.asarray', 'np.asarray', (['gallery_cams'], {}), '(gallery_cams)\n', (3492, 3506), True, 'import numpy as np\n'), ((3557, 3584), 'numpy.argsort', 'np.argsort', (['distmat'], {'axis': '(1)'}), '(distmat, axis=1)\n', (3567, 3584), True, 'import numpy as np\n'), ((4153, 4165), 'numpy.mean', 'np.mean', (['aps'], {}), '(aps)\n', (4160, 4165), True, 'import numpy as np\n'), ((346, 371), 'numpy.random.choice', 'np.random.choice', (['indices'], {}), '(indices)\n', (362, 371), True, 'import numpy as np\n'), ((754, 766), 'numpy.arange', 'np.arange', (['m'], {}), '(m)\n', (763, 766), True, 'import numpy as np\n'), ((817, 829), 'numpy.arange', 'np.arange', (['n'], {}), '(n)\n', (826, 829), True, 'import numpy as np\n'), ((3085, 3097), 'numpy.arange', 'np.arange', (['m'], {}), '(m)\n', (3094, 3097), True, 'import numpy as np\n'), ((3148, 3160), 'numpy.arange', 'np.arange', (['n'], {}), '(n)\n', (3157, 3160), True, 'import numpy as np\n'), ((1760, 1785), 'numpy.any', 'np.any', (['matches[i, valid]'], {}), '(matches[i, valid])\n', (1766, 1785), True, 'import numpy as np\n'), ((1963, 1980), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (1974, 1980), False, 'from collections import defaultdict\n'), ((3989, 4003), 'numpy.any', 'np.any', (['y_true'], {}), '(y_true)\n', (3995, 4003), True, 'import numpy as np\n'), ((4033, 4073), 'sklearn.metrics.average_precision_score', 'average_precision_score', (['y_true', 'y_score'], {}), '(y_true, y_score)\n', (4056, 4073), False, 'from sklearn.metrics import average_precision_score\n'), ((878, 889), 'numpy.zeros', 'np.zeros', (['m'], {}), '(m)\n', (886, 889), True, 'import numpy as np\n'), ((959, 969), 'numpy.ones', 'np.ones', (['n'], {}), '(n)\n', (966, 969), True, 'import numpy as np\n'), ((1921, 1936), 'numpy.where', 'np.where', (['valid'], {}), '(valid)\n', (1929, 1936), True, 'import numpy as np\n'), ((3209, 3220), 'numpy.zeros', 'np.zeros', (['m'], {}), '(m)\n', (3217, 3220), True, 'import numpy as np\n'), ((3290, 3300), 'numpy.ones', 'np.ones', (['n'], {}), '(n)\n', (3297, 3300), True, 'import numpy as np\n'), ((2321, 2352), 'numpy.nonzero', 'np.nonzero', (['matches[i, sampled]'], {}), '(matches[i, sampled])\n', (2331, 2352), True, 'import numpy as np\n'), ((2398, 2427), 'numpy.nonzero', 'np.nonzero', (['matches[i, valid]'], {}), '(matches[i, valid])\n', (2408, 2427), True, 'import numpy as np\n')] |
from __future__ import print_function, absolute_import
from timeit import default_timer as time
import numpy as np
import numpy.core.umath_tests as ut
from numba import void, float32, float64
from numba import guvectorize
from numba import cuda
from numba import unittest_support as unittest
from numba.cuda.testing import skip_on_cudasim
non_stream_speedups = []
stream_speedups = []
@skip_on_cudasim('ufunc API unsupported in the simulator')
class TestCUDAGufunc(unittest.TestCase):
def test_gufunc_small(self):
@guvectorize([void(float32[:, :], float32[:, :], float32[:, :])],
'(m,n),(n,p)->(m,p)',
target='cuda')
def matmulcore(A, B, C):
m, n = A.shape
n, p = B.shape
for i in range(m):
for j in range(p):
C[i, j] = 0
for k in range(n):
C[i, j] += A[i, k] * B[k, j]
gufunc = matmulcore
gufunc.max_blocksize = 512
matrix_ct = 2
A = np.arange(matrix_ct * 2 * 4, dtype=np.float32).reshape(matrix_ct, 2,
4)
B = np.arange(matrix_ct * 4 * 5, dtype=np.float32).reshape(matrix_ct, 4,
5)
ts = time()
C = gufunc(A, B)
tcuda = time() - ts
ts = time()
Gold = ut.matrix_multiply(A, B)
tcpu = time() - ts
non_stream_speedups.append(tcpu / tcuda)
print(C, Gold)
self.assertTrue(np.allclose(C, Gold))
def test_gufunc_auto_transfer(self):
@guvectorize([void(float32[:, :], float32[:, :], float32[:, :])],
'(m,n),(n,p)->(m,p)',
target='cuda')
def matmulcore(A, B, C):
m, n = A.shape
n, p = B.shape
for i in range(m):
for j in range(p):
C[i, j] = 0
for k in range(n):
C[i, j] += A[i, k] * B[k, j]
gufunc = matmulcore
gufunc.max_blocksize = 512
matrix_ct = 2
A = np.arange(matrix_ct * 2 * 4, dtype=np.float32).reshape(matrix_ct, 2,
4)
B = np.arange(matrix_ct * 4 * 5, dtype=np.float32).reshape(matrix_ct, 4,
5)
dB = cuda.to_device(B)
ts = time()
C = gufunc(A, dB).copy_to_host()
tcuda = time() - ts
ts = time()
Gold = ut.matrix_multiply(A, B)
tcpu = time() - ts
non_stream_speedups.append(tcpu / tcuda)
print(C, Gold)
self.assertTrue(np.allclose(C, Gold))
def test_gufunc(self):
@guvectorize([void(float32[:, :], float32[:, :], float32[:, :])],
'(m,n),(n,p)->(m,p)',
target='cuda')
def matmulcore(A, B, C):
m, n = A.shape
n, p = B.shape
for i in range(m):
for j in range(p):
C[i, j] = 0
for k in range(n):
C[i, j] += A[i, k] * B[k, j]
gufunc = matmulcore
gufunc.max_blocksize = 512
matrix_ct = 1001 # an odd number to test thread/block division in CUDA
A = np.arange(matrix_ct * 2 * 4, dtype=np.float32).reshape(matrix_ct, 2,
4)
B = np.arange(matrix_ct * 4 * 5, dtype=np.float32).reshape(matrix_ct, 4,
5)
ts = time()
C = gufunc(A, B)
tcuda = time() - ts
ts = time()
Gold = ut.matrix_multiply(A, B)
tcpu = time() - ts
non_stream_speedups.append(tcpu / tcuda)
self.assertTrue(np.allclose(C, Gold))
def test_gufunc_hidim(self):
@guvectorize([void(float32[:, :], float32[:, :], float32[:, :])],
'(m,n),(n,p)->(m,p)',
target='cuda')
def matmulcore(A, B, C):
m, n = A.shape
n, p = B.shape
for i in range(m):
for j in range(p):
C[i, j] = 0
for k in range(n):
C[i, j] += A[i, k] * B[k, j]
gufunc = matmulcore
gufunc.max_blocksize = 512
matrix_ct = 100 # an odd number to test thread/block division in CUDA
A = np.arange(matrix_ct * 2 * 4, dtype=np.float32).reshape(4, 25, 2, 4)
B = np.arange(matrix_ct * 4 * 5, dtype=np.float32).reshape(4, 25, 4, 5)
ts = time()
C = gufunc(A, B)
tcuda = time() - ts
ts = time()
Gold = ut.matrix_multiply(A, B)
tcpu = time() - ts
non_stream_speedups.append(tcpu / tcuda)
self.assertTrue(np.allclose(C, Gold))
def test_gufunc_new_axis(self):
@guvectorize([void(float64[:, :], float64[:, :], float64[:, :])],
'(m,n),(n,p)->(m,p)',
target='cuda')
def matmulcore(A, B, C):
m, n = A.shape
n, p = B.shape
for i in range(m):
for j in range(p):
C[i, j] = 0
for k in range(n):
C[i, j] += A[i, k] * B[k, j]
gufunc = matmulcore
X = np.random.randn(10, 3, 3)
Y = np.random.randn(3, 3)
gold = ut.matrix_multiply(X, Y)
res1 = gufunc(X, Y)
np.testing.assert_allclose(gold, res1)
res2 = gufunc(X, np.tile(Y, (10, 1, 1)))
np.testing.assert_allclose(gold, res2)
def test_gufunc_adjust_blocksize(self):
@guvectorize([void(float32[:, :], float32[:, :], float32[:, :])],
'(m,n),(n,p)->(m,p)',
target='cuda')
def matmulcore(A, B, C):
m, n = A.shape
n, p = B.shape
for i in range(m):
for j in range(p):
C[i, j] = 0
for k in range(n):
C[i, j] += A[i, k] * B[k, j]
gufunc = matmulcore
gufunc.max_blocksize = 512
matrix_ct = 1001 # an odd number to test thread/block division in CUDA
A = np.arange(matrix_ct * 2 * 4, dtype=np.float32).reshape(matrix_ct, 2,
4)
B = np.arange(matrix_ct * 4 * 5, dtype=np.float32).reshape(matrix_ct, 4,
5)
gufunc.max_blocksize = 32
C = gufunc(A, B)
Gold = ut.matrix_multiply(A, B)
self.assertTrue(np.allclose(C, Gold))
def test_gufunc_stream(self):
@guvectorize([void(float32[:, :], float32[:, :], float32[:, :])],
'(m,n),(n,p)->(m,p)',
target='cuda')
def matmulcore(A, B, C):
m, n = A.shape
n, p = B.shape
for i in range(m):
for j in range(p):
C[i, j] = 0
for k in range(n):
C[i, j] += A[i, k] * B[k, j]
gufunc = matmulcore
gufunc.max_blocksize = 512
#cuda.driver.flush_pending_free()
matrix_ct = 1001 # an odd number to test thread/block division in CUDA
A = np.arange(matrix_ct * 2 * 4, dtype=np.float32).reshape(matrix_ct, 2,
4)
B = np.arange(matrix_ct * 4 * 5, dtype=np.float32).reshape(matrix_ct, 4,
5)
ts = time()
stream = cuda.stream()
dA = cuda.to_device(A, stream)
dB = cuda.to_device(B, stream)
dC = cuda.device_array(shape=(1001, 2, 5), dtype=A.dtype, stream=stream)
dC = gufunc(dA, dB, out=dC, stream=stream)
C = dC.copy_to_host(stream=stream)
stream.synchronize()
tcuda = time() - ts
ts = time()
Gold = ut.matrix_multiply(A, B)
tcpu = time() - ts
stream_speedups.append(tcpu / tcuda)
self.assertTrue(np.allclose(C, Gold))
def test_copy(self):
@guvectorize([void(float32[:], float32[:])],
'(x)->(x)',
target='cuda')
def copy(A, B):
for i in range(B.size):
B[i] = A[i]
A = np.arange(10, dtype=np.float32) + 1
B = np.zeros_like(A)
copy(A, out=B)
self.assertTrue(np.allclose(A, B))
def test_copy_odd(self):
@guvectorize([void(float32[:], float32[:])],
'(x)->(x)',
target='cuda')
def copy(A, B):
for i in range(B.size):
B[i] = A[i]
A = np.arange(11, dtype=np.float32) + 1
B = np.zeros_like(A)
copy(A, out=B)
self.assertTrue(np.allclose(A, B))
def test_copy2d(self):
@guvectorize([void(float32[:, :], float32[:, :])],
'(x, y)->(x, y)',
target='cuda')
def copy2d(A, B):
for x in range(B.shape[0]):
for y in range(B.shape[1]):
B[x, y] = A[x, y]
A = np.arange(30, dtype=np.float32).reshape(5, 6) + 1
B = np.zeros_like(A)
copy2d(A, out=B)
self.assertTrue(np.allclose(A, B))
def test_nopython_flag(self):
def foo(A, B):
pass
# nopython = True is fine
guvectorize([void(float32[:], float32[:])], '(x)->(x)', target='cuda',
nopython=True)(foo)
# nopython = False is bad
with self.assertRaises(TypeError) as raises:
guvectorize([void(float32[:], float32[:])], '(x)->(x)',
target='cuda', nopython=False)(foo)
self.assertEqual("nopython flag must be True", str(raises.exception))
def test_invalid_flags(self):
# Check invalid flags
def foo(A, B):
pass
with self.assertRaises(TypeError) as raises:
guvectorize([void(float32[:], float32[:])], '(x)->(x)',
target='cuda', what1=True, ever2=False)(foo)
head = "The following target options are not supported:"
msg = str(raises.exception)
self.assertEqual(msg[:len(head)], head)
items = msg[len(head):].strip().split(',')
items = [i.strip("'\" ") for i in items]
self.assertEqual(set(['what1', 'ever2']), set(items))
if __name__ == '__main__':
unittest.main()
| [
"numba.unittest_support.main",
"numba.cuda.device_array",
"numpy.tile",
"numpy.allclose",
"timeit.default_timer",
"numpy.testing.assert_allclose",
"numpy.zeros_like",
"numba.cuda.stream",
"numba.cuda.to_device",
"numba.void",
"numpy.core.umath_tests.matrix_multiply",
"numba.cuda.testing.skip_o... | [((393, 450), 'numba.cuda.testing.skip_on_cudasim', 'skip_on_cudasim', (['"""ufunc API unsupported in the simulator"""'], {}), "('ufunc API unsupported in the simulator')\n", (408, 450), False, 'from numba.cuda.testing import skip_on_cudasim\n'), ((10766, 10781), 'numba.unittest_support.main', 'unittest.main', ([], {}), '()\n', (10779, 10781), True, 'from numba import unittest_support as unittest\n'), ((1361, 1367), 'timeit.default_timer', 'time', ([], {}), '()\n', (1365, 1367), True, 'from timeit import default_timer as time\n'), ((1435, 1441), 'timeit.default_timer', 'time', ([], {}), '()\n', (1439, 1441), True, 'from timeit import default_timer as time\n'), ((1457, 1481), 'numpy.core.umath_tests.matrix_multiply', 'ut.matrix_multiply', (['A', 'B'], {}), '(A, B)\n', (1475, 1481), True, 'import numpy.core.umath_tests as ut\n'), ((2506, 2523), 'numba.cuda.to_device', 'cuda.to_device', (['B'], {}), '(B)\n', (2520, 2523), False, 'from numba import cuda\n'), ((2538, 2544), 'timeit.default_timer', 'time', ([], {}), '()\n', (2542, 2544), True, 'from timeit import default_timer as time\n'), ((2628, 2634), 'timeit.default_timer', 'time', ([], {}), '()\n', (2632, 2634), True, 'from timeit import default_timer as time\n'), ((2650, 2674), 'numpy.core.umath_tests.matrix_multiply', 'ut.matrix_multiply', (['A', 'B'], {}), '(A, B)\n', (2668, 2674), True, 'import numpy.core.umath_tests as ut\n'), ((3742, 3748), 'timeit.default_timer', 'time', ([], {}), '()\n', (3746, 3748), True, 'from timeit import default_timer as time\n'), ((3816, 3822), 'timeit.default_timer', 'time', ([], {}), '()\n', (3820, 3822), True, 'from timeit import default_timer as time\n'), ((3838, 3862), 'numpy.core.umath_tests.matrix_multiply', 'ut.matrix_multiply', (['A', 'B'], {}), '(A, B)\n', (3856, 3862), True, 'import numpy.core.umath_tests as ut\n'), ((4769, 4775), 'timeit.default_timer', 'time', ([], {}), '()\n', (4773, 4775), True, 'from timeit import default_timer as time\n'), ((4843, 4849), 'timeit.default_timer', 'time', ([], {}), '()\n', (4847, 4849), True, 'from timeit import default_timer as time\n'), ((4865, 4889), 'numpy.core.umath_tests.matrix_multiply', 'ut.matrix_multiply', (['A', 'B'], {}), '(A, B)\n', (4883, 4889), True, 'import numpy.core.umath_tests as ut\n'), ((5524, 5549), 'numpy.random.randn', 'np.random.randn', (['(10)', '(3)', '(3)'], {}), '(10, 3, 3)\n', (5539, 5549), True, 'import numpy as np\n'), ((5562, 5583), 'numpy.random.randn', 'np.random.randn', (['(3)', '(3)'], {}), '(3, 3)\n', (5577, 5583), True, 'import numpy as np\n'), ((5600, 5624), 'numpy.core.umath_tests.matrix_multiply', 'ut.matrix_multiply', (['X', 'Y'], {}), '(X, Y)\n', (5618, 5624), True, 'import numpy.core.umath_tests as ut\n'), ((5662, 5700), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['gold', 'res1'], {}), '(gold, res1)\n', (5688, 5700), True, 'import numpy as np\n'), ((5759, 5797), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['gold', 'res2'], {}), '(gold, res2)\n', (5785, 5797), True, 'import numpy as np\n'), ((6795, 6819), 'numpy.core.umath_tests.matrix_multiply', 'ut.matrix_multiply', (['A', 'B'], {}), '(A, B)\n', (6813, 6819), True, 'import numpy.core.umath_tests as ut\n'), ((7834, 7840), 'timeit.default_timer', 'time', ([], {}), '()\n', (7838, 7840), True, 'from timeit import default_timer as time\n'), ((7858, 7871), 'numba.cuda.stream', 'cuda.stream', ([], {}), '()\n', (7869, 7871), False, 'from numba import cuda\n'), ((7885, 7910), 'numba.cuda.to_device', 'cuda.to_device', (['A', 'stream'], {}), '(A, stream)\n', (7899, 7910), False, 'from numba import cuda\n'), ((7924, 7949), 'numba.cuda.to_device', 'cuda.to_device', (['B', 'stream'], {}), '(B, stream)\n', (7938, 7949), False, 'from numba import cuda\n'), ((7964, 8031), 'numba.cuda.device_array', 'cuda.device_array', ([], {'shape': '(1001, 2, 5)', 'dtype': 'A.dtype', 'stream': 'stream'}), '(shape=(1001, 2, 5), dtype=A.dtype, stream=stream)\n', (7981, 8031), False, 'from numba import cuda\n'), ((8198, 8204), 'timeit.default_timer', 'time', ([], {}), '()\n', (8202, 8204), True, 'from timeit import default_timer as time\n'), ((8220, 8244), 'numpy.core.umath_tests.matrix_multiply', 'ut.matrix_multiply', (['A', 'B'], {}), '(A, B)\n', (8238, 8244), True, 'import numpy.core.umath_tests as ut\n'), ((8663, 8679), 'numpy.zeros_like', 'np.zeros_like', (['A'], {}), '(A)\n', (8676, 8679), True, 'import numpy as np\n'), ((9048, 9064), 'numpy.zeros_like', 'np.zeros_like', (['A'], {}), '(A)\n', (9061, 9064), True, 'import numpy as np\n'), ((9517, 9533), 'numpy.zeros_like', 'np.zeros_like', (['A'], {}), '(A)\n', (9530, 9533), True, 'import numpy as np\n'), ((1409, 1415), 'timeit.default_timer', 'time', ([], {}), '()\n', (1413, 1415), True, 'from timeit import default_timer as time\n'), ((1497, 1503), 'timeit.default_timer', 'time', ([], {}), '()\n', (1501, 1503), True, 'from timeit import default_timer as time\n'), ((1608, 1628), 'numpy.allclose', 'np.allclose', (['C', 'Gold'], {}), '(C, Gold)\n', (1619, 1628), True, 'import numpy as np\n'), ((2602, 2608), 'timeit.default_timer', 'time', ([], {}), '()\n', (2606, 2608), True, 'from timeit import default_timer as time\n'), ((2690, 2696), 'timeit.default_timer', 'time', ([], {}), '()\n', (2694, 2696), True, 'from timeit import default_timer as time\n'), ((2801, 2821), 'numpy.allclose', 'np.allclose', (['C', 'Gold'], {}), '(C, Gold)\n', (2812, 2821), True, 'import numpy as np\n'), ((3790, 3796), 'timeit.default_timer', 'time', ([], {}), '()\n', (3794, 3796), True, 'from timeit import default_timer as time\n'), ((3878, 3884), 'timeit.default_timer', 'time', ([], {}), '()\n', (3882, 3884), True, 'from timeit import default_timer as time\n'), ((3965, 3985), 'numpy.allclose', 'np.allclose', (['C', 'Gold'], {}), '(C, Gold)\n', (3976, 3985), True, 'import numpy as np\n'), ((4817, 4823), 'timeit.default_timer', 'time', ([], {}), '()\n', (4821, 4823), True, 'from timeit import default_timer as time\n'), ((4905, 4911), 'timeit.default_timer', 'time', ([], {}), '()\n', (4909, 4911), True, 'from timeit import default_timer as time\n'), ((4992, 5012), 'numpy.allclose', 'np.allclose', (['C', 'Gold'], {}), '(C, Gold)\n', (5003, 5012), True, 'import numpy as np\n'), ((5727, 5749), 'numpy.tile', 'np.tile', (['Y', '(10, 1, 1)'], {}), '(Y, (10, 1, 1))\n', (5734, 5749), True, 'import numpy as np\n'), ((6844, 6864), 'numpy.allclose', 'np.allclose', (['C', 'Gold'], {}), '(C, Gold)\n', (6855, 6864), True, 'import numpy as np\n'), ((8172, 8178), 'timeit.default_timer', 'time', ([], {}), '()\n', (8176, 8178), True, 'from timeit import default_timer as time\n'), ((8260, 8266), 'timeit.default_timer', 'time', ([], {}), '()\n', (8264, 8266), True, 'from timeit import default_timer as time\n'), ((8343, 8363), 'numpy.allclose', 'np.allclose', (['C', 'Gold'], {}), '(C, Gold)\n', (8354, 8363), True, 'import numpy as np\n'), ((8615, 8646), 'numpy.arange', 'np.arange', (['(10)'], {'dtype': 'np.float32'}), '(10, dtype=np.float32)\n', (8624, 8646), True, 'import numpy as np\n'), ((8727, 8744), 'numpy.allclose', 'np.allclose', (['A', 'B'], {}), '(A, B)\n', (8738, 8744), True, 'import numpy as np\n'), ((9000, 9031), 'numpy.arange', 'np.arange', (['(11)'], {'dtype': 'np.float32'}), '(11, dtype=np.float32)\n', (9009, 9031), True, 'import numpy as np\n'), ((9112, 9129), 'numpy.allclose', 'np.allclose', (['A', 'B'], {}), '(A, B)\n', (9123, 9129), True, 'import numpy as np\n'), ((9583, 9600), 'numpy.allclose', 'np.allclose', (['A', 'B'], {}), '(A, B)\n', (9594, 9600), True, 'import numpy as np\n'), ((549, 598), 'numba.void', 'void', (['float32[:, :]', 'float32[:, :]', 'float32[:, :]'], {}), '(float32[:, :], float32[:, :], float32[:, :])\n', (553, 598), False, 'from numba import void, float32, float64\n'), ((1057, 1103), 'numpy.arange', 'np.arange', (['(matrix_ct * 2 * 4)'], {'dtype': 'np.float32'}), '(matrix_ct * 2 * 4, dtype=np.float32)\n', (1066, 1103), True, 'import numpy as np\n'), ((1208, 1254), 'numpy.arange', 'np.arange', (['(matrix_ct * 4 * 5)'], {'dtype': 'np.float32'}), '(matrix_ct * 4 * 5, dtype=np.float32)\n', (1217, 1254), True, 'import numpy as np\n'), ((1695, 1744), 'numba.void', 'void', (['float32[:, :]', 'float32[:, :]', 'float32[:, :]'], {}), '(float32[:, :], float32[:, :], float32[:, :])\n', (1699, 1744), False, 'from numba import void, float32, float64\n'), ((2202, 2248), 'numpy.arange', 'np.arange', (['(matrix_ct * 2 * 4)'], {'dtype': 'np.float32'}), '(matrix_ct * 2 * 4, dtype=np.float32)\n', (2211, 2248), True, 'import numpy as np\n'), ((2353, 2399), 'numpy.arange', 'np.arange', (['(matrix_ct * 4 * 5)'], {'dtype': 'np.float32'}), '(matrix_ct * 4 * 5, dtype=np.float32)\n', (2362, 2399), True, 'import numpy as np\n'), ((2874, 2923), 'numba.void', 'void', (['float32[:, :]', 'float32[:, :]', 'float32[:, :]'], {}), '(float32[:, :], float32[:, :], float32[:, :])\n', (2878, 2923), False, 'from numba import void, float32, float64\n'), ((3438, 3484), 'numpy.arange', 'np.arange', (['(matrix_ct * 2 * 4)'], {'dtype': 'np.float32'}), '(matrix_ct * 2 * 4, dtype=np.float32)\n', (3447, 3484), True, 'import numpy as np\n'), ((3589, 3635), 'numpy.arange', 'np.arange', (['(matrix_ct * 4 * 5)'], {'dtype': 'np.float32'}), '(matrix_ct * 4 * 5, dtype=np.float32)\n', (3598, 3635), True, 'import numpy as np\n'), ((4044, 4093), 'numba.void', 'void', (['float32[:, :]', 'float32[:, :]', 'float32[:, :]'], {}), '(float32[:, :], float32[:, :], float32[:, :])\n', (4048, 4093), False, 'from numba import void, float32, float64\n'), ((4607, 4653), 'numpy.arange', 'np.arange', (['(matrix_ct * 2 * 4)'], {'dtype': 'np.float32'}), '(matrix_ct * 2 * 4, dtype=np.float32)\n', (4616, 4653), True, 'import numpy as np\n'), ((4687, 4733), 'numpy.arange', 'np.arange', (['(matrix_ct * 4 * 5)'], {'dtype': 'np.float32'}), '(matrix_ct * 4 * 5, dtype=np.float32)\n', (4696, 4733), True, 'import numpy as np\n'), ((5074, 5123), 'numba.void', 'void', (['float64[:, :]', 'float64[:, :]', 'float64[:, :]'], {}), '(float64[:, :], float64[:, :], float64[:, :])\n', (5078, 5123), False, 'from numba import void, float32, float64\n'), ((5866, 5915), 'numba.void', 'void', (['float32[:, :]', 'float32[:, :]', 'float32[:, :]'], {}), '(float32[:, :], float32[:, :], float32[:, :])\n', (5870, 5915), False, 'from numba import void, float32, float64\n'), ((6430, 6476), 'numpy.arange', 'np.arange', (['(matrix_ct * 2 * 4)'], {'dtype': 'np.float32'}), '(matrix_ct * 2 * 4, dtype=np.float32)\n', (6439, 6476), True, 'import numpy as np\n'), ((6581, 6627), 'numpy.arange', 'np.arange', (['(matrix_ct * 4 * 5)'], {'dtype': 'np.float32'}), '(matrix_ct * 4 * 5, dtype=np.float32)\n', (6590, 6627), True, 'import numpy as np\n'), ((6924, 6973), 'numba.void', 'void', (['float32[:, :]', 'float32[:, :]', 'float32[:, :]'], {}), '(float32[:, :], float32[:, :], float32[:, :])\n', (6928, 6973), False, 'from numba import void, float32, float64\n'), ((7530, 7576), 'numpy.arange', 'np.arange', (['(matrix_ct * 2 * 4)'], {'dtype': 'np.float32'}), '(matrix_ct * 2 * 4, dtype=np.float32)\n', (7539, 7576), True, 'import numpy as np\n'), ((7681, 7727), 'numpy.arange', 'np.arange', (['(matrix_ct * 4 * 5)'], {'dtype': 'np.float32'}), '(matrix_ct * 4 * 5, dtype=np.float32)\n', (7690, 7727), True, 'import numpy as np\n'), ((8414, 8442), 'numba.void', 'void', (['float32[:]', 'float32[:]'], {}), '(float32[:], float32[:])\n', (8418, 8442), False, 'from numba import void, float32, float64\n'), ((8799, 8827), 'numba.void', 'void', (['float32[:]', 'float32[:]'], {}), '(float32[:], float32[:])\n', (8803, 8827), False, 'from numba import void, float32, float64\n'), ((9182, 9216), 'numba.void', 'void', (['float32[:, :]', 'float32[:, :]'], {}), '(float32[:, :], float32[:, :])\n', (9186, 9216), False, 'from numba import void, float32, float64\n'), ((9455, 9486), 'numpy.arange', 'np.arange', (['(30)'], {'dtype': 'np.float32'}), '(30, dtype=np.float32)\n', (9464, 9486), True, 'import numpy as np\n'), ((9734, 9762), 'numba.void', 'void', (['float32[:]', 'float32[:]'], {}), '(float32[:], float32[:])\n', (9738, 9762), False, 'from numba import void, float32, float64\n'), ((9945, 9973), 'numba.void', 'void', (['float32[:]', 'float32[:]'], {}), '(float32[:], float32[:])\n', (9949, 9973), False, 'from numba import void, float32, float64\n'), ((10310, 10338), 'numba.void', 'void', (['float32[:]', 'float32[:]'], {}), '(float32[:], float32[:])\n', (10314, 10338), False, 'from numba import void, float32, float64\n')] |
"""
This module provides the Scan Op
See scan.py for details on scan
"""
from __future__ import print_function
__docformat__ = 'restructedtext en'
__authors__ = ("<NAME> "
"<NAME> "
"<NAME> "
"<NAME> ")
__copyright__ = "(c) 2010, Universite de Montreal"
__contact__ = "<NAME> <<EMAIL>>"
import logging
import numpy
from six import iteritems
from six.moves import xrange
import theano
from theano import compile
from theano.compat import izip
from theano.gof import PureOp, Apply
from theano import gof
from theano.tensor import TensorType
from theano.tensor.opt import Shape_i
# Logging function for sending warning or info
_logger = logging.getLogger('theano.scan_module.scan_op')
class ScanOp(PureOp):
def __init__(self,
inputs,
outputs,
lengths,
switches,
mintaps,
index,
options,
as_repeatUntil):
self.inputs = inputs
self.outputs = outputs
self.index = index
self.switches = switches
self.lengths = lengths
self.mintaps = mintaps
self.as_repeatUntil = as_repeatUntil
self.options = options
self.name = options['name']
self.mode = options['mode']
self.inplace = options['inplace']
self.gpu = options['gpu']
self.profile = options['profile']
self.hash_inner_graph = options['hash_inner_graph']
# --Construct the destroy map--
if self.inplace:
for idx in xrange(len(outputs)):
self.destroy_map[idx] = [idx + 1]
# --Decide on the default mode--
mode_instance = compile.mode.get_mode(self.mode)
# if the default mode is used, and that mode is ProfileMode
# then we need to copy the mode otherwise the time for a given
# op will be counted multiple times
if (self.mode is None and
isinstance(mode_instance, compile.profilemode.ProfileMode)):
mode_instance = compile.profilemode.ProfileMode(
optimizer=mode_instance.provided_optimizer,
linker=mode_instance.provided_linker)
compile.profilemode.prof_mode_instance_to_print.append(
mode_instance)
self.mode_instance = mode_instance
if self.name:
self.mode_instance.message = self.name + " sub profile"
else:
self.mode_instance.message = "Scan sub profile"
else:
self.mode_instance = mode_instance
# --Adding default name--
if not hasattr(self, 'name') or self.name is None:
self.name = 'scan_fn'
def make_node(self, *inputs):
# Checking if arguments are of the right type is done in the scan
# function
out_types = [out.type() for out in self.outputs]
return Apply(self, inputs, out_types)
def __eq__(self, other):
# Check if we are dealing with same type of objects
if not type(self) == type(other):
return False
if self.options != other.options:
return False
if self.mintals != other.mintaps:
return False
# Check if the number of different types of arguments is the same
diff_args = ['inputs', 'outputs', 'lengths', 'mintaps', 'switches']
for arg in diff_args:
if len(getattr(self, arg)) != len(getattr(other, arg)):
return False
for x, y in izip(self.inputs, other.inputs):
if x.type != y.type:
return False
for x, y in izip(self.lengths, other.lengths):
if x.type != y.type:
return False
s_ins = [self.index] + self.inputs + self.lengths + self.switches
o_ins = [other.index] + other.inputs + other.lengths + other.switches
givens = dict(izip(s_ins, o_ins))
# This part might be slow
for x, y in izip(self.outputs, other.outputs):
if not gof.graph.is_same_graph(x, y, givens=givens):
return False
return True
def __str__(self):
if self.gpu:
gpu_str = 'gpu'
else:
gpu_str = 'cpu'
if self.as_repeatUntil is not None:
name = 'repeat/until'
else:
name = 'loop'
if self.inplace:
aux_txt = '%s{inplace,%s,%s}' % (name, gpu_str, str(self.name))
else:
aux_txt = '%s{%s,%s}' % (name, gpu_str, str(self.name))
return aux_txt
def __hash__(self):
rval = hash(type(self)) ^ self.hash_inner_graph
for val in self.options.values():
if isinstance(val, (list, tuple)):
for el in val:
rval = rval ^ el
else:
rval = rval ^ val
return rval
def infer_shape(self, node, input_shapes):
for inp, inp_shp in izip(node.inputs, input_shapes):
assert inp_shp is None or len(inp_shp) == inp.type.ndim
n_outs = len(self.outputs)
if self.as_repeatUntil is not None:
return [(Shape_i(0)(o),) + x[1:] for o, x
in izip(node.outputs, input_shapes[1: n_outs + 1])]
else:
return input_shapes[1: n_outs + 1]
def make_thunk(self, node, storage_map, compute_map, no_recycling):
"""
:param node: the Apply node returned by the ``make_node`` function
of the scan op class
:param storage_map: dict variable -> one-element-list where a computed
value for this variable may be found.
:param compute_map: dict variable -> one-element-list where a boolean
value will be found. The boolean indicates whether the
variable's storage_map container contains a valid value (True)
or if it has not been computed yet (False).
:param no_recycling: list of variables for which it is forbidden to
reuse memory allocated by a previous call.
:note: If the thunk consults the storage_map on every call, it is safe
for it to ignore the no_recycling argument, because elements of the
no_recycling list will have a value of None in the storage map. If
the thunk can potentially cache return values (like CLinker does),
then it must not do so for variables in the no_recycling list.
"""
# 1. Collect all memory buffers
node_input_storage = [storage_map[r] for r in node.inputs]
node_output_storage = [storage_map[r] for r in node.outputs]
node_input_compute = [compute_map[r] for r in node.inputs]
node_output_compute = [compute_map[r] for r in node.outputs]
# 2. Construct fake shared variables around every argument of scan
givens = {}
base_inputs = self.inputs[:len(self.outputs)]
base_buffers = node_input_storage[1: 1 + len(base_inputs)]
aux_inputs = self.inputs[len(self.outputs):]
aux_membuffers = node_input_storage[1 + len(base_inputs):]
# 2.1 First the auxiliary arguments, those that are parameters or
# input
def fake_shared(var):
val = 0
for dim in xrange(var.ndim):
val = [val]
val = numpy.asarray(val, dtype=var.dtype)
return theano.shared(val, name=var.name)
non_tensor_args = []
non_tensor_buffers = []
aux_buffers = []
for mem_buf, var in izip(aux_membuffers, aux_inputs):
if mem_buf[0] is not None:
givens[var] = theano.shared(mem_buf[0], name=var.name,
borrow=True)
elif isinstance(var, TensorType):
givens[var] = fake_shared(var)
aux_buffers.append((givens[var], mem_buf))
else:
givens[var] = var.type()
non_tensor_args.append(givens[var])
non_tensor_buffers.append(mem_buf)
# 2.2. Next the states (numeric) and the outputs
updates = {}
state_buffers = []
n_numeric_values = len(self.lengths)
for pos in xrange(n_numeric_values):
var = base_inputs[pos]
mem_buf = base_buffers[pos]
expr = self.outputs[pos]
givens[var] = fake_shared(var)
state_buffers.append((givens[var], self.lengths[pos], mem_buf))
updates[givens[var]] = expr
# 2.3 Non-numeric states
n_non_numeric = len(self.outputs) - n_numeric_values
fn_outs = self.outputs[n_numeric_values:]
for var in base_inputs[n_numeric_values:]:
givens[var] = var.type()
non_tensor_args.append(givens[var])
non_numeric_states_bufs = base_buffers[n_numeric_values:]
# 2.4 Add the update for the index of scan
updates[self.index] = self.index + numpy.int64(1)
# 3.1 Construct the inner function of scan
if self.as_repeatUntil is not None:
fn_outs = self.as_repeatUntil
self.fn = theano.function(non_tensor_args, fn_outs,
givens=givens,
updates=updates,
mode=self.mode_instance,
name=self.name,
profile=self.profile)
# 3.2 Construct the perform
if self.as_repeatUntil is not None:
# 3.2.1 as a repeat until
def p(node, args, outs):
pos = 0
cont = 1
# copy inputs if not inplace
if not self.inplace:
for _, _, val in state_buffers:
val[0] = val[0].copy()
for buf in non_numeric_states_bufs:
buf[0] = buf[0].copy()
# reset all switches if any
for sw in self.switches:
sw.set_value(numpy.int8(0), borrow=True)
# set aux shared variables
for var, val in aux_buffers:
var.set_value(val[0], borrow=True)
# set state shared variables
for var, length, val in state_buffers:
var.set_value(val[0], borrow=True)
length.set_value(val[0].shape[0], borrow=True)
self.index.set_value(numpy.int64(0))
# grab fixed arguments
fix_args = [x[0] for x in non_tensor_buffers]
while cont and pos < node_input_storage[0][0]:
extra_args = [x[0] for x in non_numeric_states_bufs]
rvals = self.fn(*(fix_args + extra_args))
for buf, rval in izip(non_numeric_states_bufs, rvals):
buf[0] = rval
cont = rvals[-1]
pos = pos + 1
# We need to trim the outputs if they are longer
for pos in xrange(n_numeric_values):
buf = state_buffers[pos][2][0]
mintap = self.mintaps[pos]
if buf.shape[0] > pos + self.mintaps[pos]:
node_output_storage[pos][0] = buf[:pos + mintap]
else:
node_output_storage[pos][0] = buf
for out_buf, in_buf in izip(
node_output_storage[n_numeric_values:],
non_numeric_states_bufs):
out_buf[0] = in_buf[0]
else:
# 3.2.2 as a for
def p(node, args, outs):
# copy inputs if not inplace
if not self.inplace:
for _, _, val in state_buffers:
val[0] = val[0].copy()
for buf in non_numeric_states_bufs:
buf[0] = buf[0].copy()
# reset all switches if any
for sw in self.switches:
sw.set_value(numpy.int8(0), borrow=True)
# set aux shared variables
for var, val in aux_buffers:
var.set_value(val[0], borrow=True)
# set state shared variables
for var, length, val in state_buffers:
var.set_value(val[0], borrow=True)
length.set_value(val[0].shape[0], borrow=True)
self.index.set_value(numpy.int64(0))
# grab fixed arguments
fix_args = [x[0] for x in non_tensor_buffers]
for dx in xrange(node_input_storage[0][0]):
extra_args = [x[0] for x in non_numeric_states_bufs]
rvals = self.fn(*(fix_args + extra_args))
for buf, rval in izip(non_numeric_states_bufs, rvals):
buf[0] = rval
for pos in xrange(n_numeric_values):
buf = state_buffers[pos][0].get_value(borrow=True)
mintap = self.mintaps[pos]
node_output_storage[pos][0] = buf
for out_buf, in_buf in izip(
node_output_storage[n_numeric_values:],
non_numeric_states_bufs):
out_buf[0] = in_buf[0]
# 3.3 construct the rval function
def rval(p=p, i=node_input_storage, o=node_output_storage, n=node):
r = p(n, [x[0] for x in i], o)
for out in node.outputs:
compute_map[out][0] = True
return r
rval.inputs = node_input_storage
rval.outputs = node_output_storage
rval.perform = p
rval.lazy = False
return rval
@theano.compile.profilemode.register_profiler_printer
def profile_printer(fct_name, compile_time, fct_call_time, fct_call,
apply_time, apply_cimpl, message, outputs_size,
other_time):
# Scan overhead profile
if any([isinstance(node.op, Scan) and v > 0 for (_, node), v in
apply_time.items()]):
print()
print('Scan overhead:')
print ('<Scan op time(s)> <sub scan fct time(s)> <sub scan op '
'time(s)> <sub scan fct time(% scan op time)> <sub scan '
'op time(% scan op time)> <node>')
total_super_scan_time = 0
total_scan_fct_time = 0
total_scan_op_time = 0
for (_, node), v in iteritems(apply_time):
if isinstance(node.op, Scan):
if v > 0:
scan_fct_time = node.op.mode_instance.fn_time
scan_op_time = node.op.mode_instance.local_time
total_super_scan_time += v
total_scan_fct_time += scan_fct_time
total_scan_op_time += scan_op_time
print(' %5.1fs %5.1fs %5.1fs %5.1f%% %5.1f%%' % (
v, scan_fct_time, scan_op_time,
scan_fct_time / v * 100, scan_op_time / v * 100), node)
else:
print((' The node took 0s, so we can not compute the '
'overhead'), node)
print(' total %5.1fs %5.1fs %5.1fs %5.1f%% %5.1f%%' % (
total_super_scan_time, total_scan_fct_time, total_scan_op_time,
total_scan_fct_time / total_super_scan_time * 100,
total_scan_op_time / total_super_scan_time * 100))
| [
"logging.getLogger",
"numpy.int8",
"theano.shared",
"numpy.int64",
"theano.function",
"theano.tensor.opt.Shape_i",
"theano.compile.profilemode.ProfileMode",
"numpy.asarray",
"theano.compile.mode.get_mode",
"theano.gof.Apply",
"six.moves.xrange",
"theano.compat.izip",
"theano.gof.graph.is_sam... | [((686, 733), 'logging.getLogger', 'logging.getLogger', (['"""theano.scan_module.scan_op"""'], {}), "('theano.scan_module.scan_op')\n", (703, 733), False, 'import logging\n'), ((1729, 1761), 'theano.compile.mode.get_mode', 'compile.mode.get_mode', (['self.mode'], {}), '(self.mode)\n', (1750, 1761), False, 'from theano import compile\n'), ((2977, 3007), 'theano.gof.Apply', 'Apply', (['self', 'inputs', 'out_types'], {}), '(self, inputs, out_types)\n', (2982, 3007), False, 'from theano.gof import PureOp, Apply\n'), ((3596, 3627), 'theano.compat.izip', 'izip', (['self.inputs', 'other.inputs'], {}), '(self.inputs, other.inputs)\n', (3600, 3627), False, 'from theano.compat import izip\n'), ((3711, 3744), 'theano.compat.izip', 'izip', (['self.lengths', 'other.lengths'], {}), '(self.lengths, other.lengths)\n', (3715, 3744), False, 'from theano.compat import izip\n'), ((4057, 4090), 'theano.compat.izip', 'izip', (['self.outputs', 'other.outputs'], {}), '(self.outputs, other.outputs)\n', (4061, 4090), False, 'from theano.compat import izip\n'), ((5032, 5063), 'theano.compat.izip', 'izip', (['node.inputs', 'input_shapes'], {}), '(node.inputs, input_shapes)\n', (5036, 5063), False, 'from theano.compat import izip\n'), ((7647, 7679), 'theano.compat.izip', 'izip', (['aux_membuffers', 'aux_inputs'], {}), '(aux_membuffers, aux_inputs)\n', (7651, 7679), False, 'from theano.compat import izip\n'), ((8328, 8352), 'six.moves.xrange', 'xrange', (['n_numeric_values'], {}), '(n_numeric_values)\n', (8334, 8352), False, 'from six.moves import xrange\n'), ((9238, 9378), 'theano.function', 'theano.function', (['non_tensor_args', 'fn_outs'], {'givens': 'givens', 'updates': 'updates', 'mode': 'self.mode_instance', 'name': 'self.name', 'profile': 'self.profile'}), '(non_tensor_args, fn_outs, givens=givens, updates=updates,\n mode=self.mode_instance, name=self.name, profile=self.profile)\n', (9253, 9378), False, 'import theano\n'), ((14630, 14651), 'six.iteritems', 'iteritems', (['apply_time'], {}), '(apply_time)\n', (14639, 14651), False, 'from six import iteritems\n'), ((2080, 2197), 'theano.compile.profilemode.ProfileMode', 'compile.profilemode.ProfileMode', ([], {'optimizer': 'mode_instance.provided_optimizer', 'linker': 'mode_instance.provided_linker'}), '(optimizer=mode_instance.provided_optimizer,\n linker=mode_instance.provided_linker)\n', (2111, 2197), False, 'from theano import compile\n'), ((2239, 2308), 'theano.compile.profilemode.prof_mode_instance_to_print.append', 'compile.profilemode.prof_mode_instance_to_print.append', (['mode_instance'], {}), '(mode_instance)\n', (2293, 2308), False, 'from theano import compile\n'), ((3983, 4001), 'theano.compat.izip', 'izip', (['s_ins', 'o_ins'], {}), '(s_ins, o_ins)\n', (3987, 4001), False, 'from theano.compat import izip\n'), ((7379, 7395), 'six.moves.xrange', 'xrange', (['var.ndim'], {}), '(var.ndim)\n', (7385, 7395), False, 'from six.moves import xrange\n'), ((7443, 7478), 'numpy.asarray', 'numpy.asarray', (['val'], {'dtype': 'var.dtype'}), '(val, dtype=var.dtype)\n', (7456, 7478), False, 'import numpy\n'), ((7498, 7531), 'theano.shared', 'theano.shared', (['val'], {'name': 'var.name'}), '(val, name=var.name)\n', (7511, 7531), False, 'import theano\n'), ((9067, 9081), 'numpy.int64', 'numpy.int64', (['(1)'], {}), '(1)\n', (9078, 9081), False, 'import numpy\n'), ((4111, 4155), 'theano.gof.graph.is_same_graph', 'gof.graph.is_same_graph', (['x', 'y'], {'givens': 'givens'}), '(x, y, givens=givens)\n', (4134, 4155), False, 'from theano import gof\n'), ((7750, 7803), 'theano.shared', 'theano.shared', (['mem_buf[0]'], {'name': 'var.name', 'borrow': '(True)'}), '(mem_buf[0], name=var.name, borrow=True)\n', (7763, 7803), False, 'import theano\n'), ((11175, 11199), 'six.moves.xrange', 'xrange', (['n_numeric_values'], {}), '(n_numeric_values)\n', (11181, 11199), False, 'from six.moves import xrange\n'), ((11558, 11627), 'theano.compat.izip', 'izip', (['node_output_storage[n_numeric_values:]', 'non_numeric_states_bufs'], {}), '(node_output_storage[n_numeric_values:], non_numeric_states_bufs)\n', (11562, 11627), False, 'from theano.compat import izip\n'), ((12779, 12811), 'six.moves.xrange', 'xrange', (['node_input_storage[0][0]'], {}), '(node_input_storage[0][0])\n', (12785, 12811), False, 'from six.moves import xrange\n'), ((13088, 13112), 'six.moves.xrange', 'xrange', (['n_numeric_values'], {}), '(n_numeric_values)\n', (13094, 13112), False, 'from six.moves import xrange\n'), ((13325, 13394), 'theano.compat.izip', 'izip', (['node_output_storage[n_numeric_values:]', 'non_numeric_states_bufs'], {}), '(node_output_storage[n_numeric_values:], non_numeric_states_bufs)\n', (13329, 13394), False, 'from theano.compat import izip\n'), ((5289, 5335), 'theano.compat.izip', 'izip', (['node.outputs', 'input_shapes[1:n_outs + 1]'], {}), '(node.outputs, input_shapes[1:n_outs + 1])\n', (5293, 5335), False, 'from theano.compat import izip\n'), ((10584, 10598), 'numpy.int64', 'numpy.int64', (['(0)'], {}), '(0)\n', (10595, 10598), False, 'import numpy\n'), ((10936, 10972), 'theano.compat.izip', 'izip', (['non_numeric_states_bufs', 'rvals'], {}), '(non_numeric_states_bufs, rvals)\n', (10940, 10972), False, 'from theano.compat import izip\n'), ((12636, 12650), 'numpy.int64', 'numpy.int64', (['(0)'], {}), '(0)\n', (12647, 12650), False, 'import numpy\n'), ((12985, 13021), 'theano.compat.izip', 'izip', (['non_numeric_states_bufs', 'rvals'], {}), '(non_numeric_states_bufs, rvals)\n', (12989, 13021), False, 'from theano.compat import izip\n'), ((10154, 10167), 'numpy.int8', 'numpy.int8', (['(0)'], {}), '(0)\n', (10164, 10167), False, 'import numpy\n'), ((12206, 12219), 'numpy.int8', 'numpy.int8', (['(0)'], {}), '(0)\n', (12216, 12219), False, 'import numpy\n'), ((5233, 5243), 'theano.tensor.opt.Shape_i', 'Shape_i', (['(0)'], {}), '(0)\n', (5240, 5243), False, 'from theano.tensor.opt import Shape_i\n')] |
#
# Hello World client in Python
# Connects REQ socket to tcp://localhost:5555
# Sends "Hello" to server, expects "World" back
#
import zmq
import cv2
import json
import numpy as np
from zeromq.SerializingContext import SerializingContext
print("Connecting to hello world server…")
context = SerializingContext()
socket = context.socket(zmq.PUB)
socket.connect("tcp://localhost:5555")
def main():
# Socket to talk to server
# # Do 10 requests, waiting each time for a response
# for request in range(10):
# print("Sending request %s …" % request)
# socket.send(b"Hello")
#
# # Get the reply.
# message = socket.recv()
# print("Received reply %s [ %s ]" % (request, message))
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
frame = cv2.flip(frame, 1)
frame = cv2.resize(frame, (0,0), fx=0.5, fy=0.5)
data={
'id': 2,
'data1': 1.2,
'data2': 1.4
}
publish(frame, data)
# print("Sending request …")
# data = {
# 'frame': frame
# }
# socket.send(json.dumps(data))
cv2.imshow('client1', cv2.cvtColor(frame, cv2.COLOR_RGB2BGR))
# message = socket.recv()
# print("Received reply [ %s ]" % (message))
if cv2.waitKey(1) & 0xFF == ord('q'):
break
def publish(image, data):
if image.flags['C_CONTIGUOUS']:
# if image is already contiguous in memory just send it
socket.send_array(image, data, copy=False)
else:
# else make it contiguous before sending
image = np.ascontiguousarray(image)
socket.send_array(image, data, copy=False)
if __name__ == '__main__':
main() | [
"cv2.flip",
"numpy.ascontiguousarray",
"cv2.VideoCapture",
"cv2.cvtColor",
"cv2.resize",
"cv2.waitKey",
"zeromq.SerializingContext.SerializingContext"
] | [((300, 320), 'zeromq.SerializingContext.SerializingContext', 'SerializingContext', ([], {}), '()\n', (318, 320), False, 'from zeromq.SerializingContext import SerializingContext\n'), ((756, 775), 'cv2.VideoCapture', 'cv2.VideoCapture', (['(0)'], {}), '(0)\n', (772, 775), False, 'import cv2\n'), ((841, 879), 'cv2.cvtColor', 'cv2.cvtColor', (['frame', 'cv2.COLOR_BGR2RGB'], {}), '(frame, cv2.COLOR_BGR2RGB)\n', (853, 879), False, 'import cv2\n'), ((896, 914), 'cv2.flip', 'cv2.flip', (['frame', '(1)'], {}), '(frame, 1)\n', (904, 914), False, 'import cv2\n'), ((931, 972), 'cv2.resize', 'cv2.resize', (['frame', '(0, 0)'], {'fx': '(0.5)', 'fy': '(0.5)'}), '(frame, (0, 0), fx=0.5, fy=0.5)\n', (941, 972), False, 'import cv2\n'), ((1714, 1741), 'numpy.ascontiguousarray', 'np.ascontiguousarray', (['image'], {}), '(image)\n', (1734, 1741), True, 'import numpy as np\n'), ((1267, 1305), 'cv2.cvtColor', 'cv2.cvtColor', (['frame', 'cv2.COLOR_RGB2BGR'], {}), '(frame, cv2.COLOR_RGB2BGR)\n', (1279, 1305), False, 'import cv2\n'), ((1408, 1422), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (1419, 1422), False, 'import cv2\n')] |
from __future__ import print_function, division
import sys,os
qspin_path = os.path.join(os.getcwd(),"../")
sys.path.insert(0,qspin_path)
from quspin.basis import spinless_fermion_basis_1d
from quspin.basis import spinless_fermion_basis_general
import numpy as np
from itertools import product
def check_ME(b1,b2,opstr,indx,dtype,err_msg):
if b1.Ns != b2.Ns:
print(b1._basis)
print(b2._basis)
raise Exception("number of states do not match.")
ME1,row1,col1=b1.Op(opstr,indx,1.0,dtype)
ME2,row2,col2=b2.Op(opstr,indx,1.0,dtype)
if len(ME1) != len(ME2):
print(ME1)
print(row1)
print(col1)
print()
print(ME2)
print(row2)
print(col2)
raise Exception("number of matrix elements do not match.")
if len(ME1)>0 and len(ME2)>0:
try:
np.testing.assert_allclose(row1-row2,0,atol=1e-6,err_msg=err_msg)
np.testing.assert_allclose(col1-col2,0,atol=1e-6,err_msg=err_msg)
np.testing.assert_allclose(ME1-ME2,0,atol=1e-6,err_msg=err_msg)
except:
print(ME1)
print(row1)
print(col1)
print()
print(ME2)
print(row2)
print(col2)
raise Exception
def test_gen_basis_spinless_fermion(l_max,N=4):
L=6
kblocks = [None]
kblocks.extend(range(L))
pblocks = [None,0,1]
ops = ["n","z","+","-","I"]
Nfs = [None,N]
t = np.array([(i+1)%L for i in range(L)])
p = np.array([L-i-1 for i in range(L)])
for Nf,kblock,pblock in product(Nfs,kblocks,pblocks):
gen_blocks = {}
basis_blocks = {}
if kblock==0 or kblock==L//2:
if pblock is not None:
basis_blocks["pblock"] = (-1)**pblock
gen_blocks["pblock"] = (p,pblock)
else:
basis_blocks["pblock"] = None
gen_blocks["pblock"] = None
else:
basis_blocks["pblock"] = None
gen_blocks["pblock"] = None
if kblock is not None:
basis_blocks["kblock"] = kblock
gen_blocks["kblock"] = (t,kblock)
else:
basis_blocks["kblock"] = None
gen_blocks["kblock"] = None
basis_1d = spinless_fermion_basis_1d(L,Nf=Nf,**basis_blocks)
gen_basis = spinless_fermion_basis_general(L,Nf=Nf,**gen_blocks)
n = basis_1d._get_norms(np.float64)**2
n_gen = (gen_basis._n.astype(np.float64))*gen_basis._pers.prod()
if basis_1d.Ns != gen_basis.Ns:
print(L,basis_blocks)
print(basis_1d)
print(gen_basis)
raise ValueError("basis size mismatch")
np.testing.assert_allclose(basis_1d._basis-gen_basis._basis,0,atol=1e-6)
np.testing.assert_allclose(n-n_gen ,0,atol=1e-6)
for l in range(1,l_max+1):
for i0 in range(0,L-l+1,1):
indx = range(i0,i0+l,1)
for opstr in product(*[ops for i in range(l)]):
opstr = "".join(list(opstr))
printing = dict(basis_blocks)
printing["opstr"]=opstr
printing["indx"]=indx
printing["Nf"]=Nf
err_msg="testing: {opstr:} {indx:} Nf={Nf:} kblock={kblock:} pblock={pblock:}".format(**printing)
check_ME(basis_1d,gen_basis,opstr,indx,np.complex128,err_msg)
print("testing Nf=4")
test_gen_basis_spinless_fermion(3,N=4)
print("testing Nf=5")
test_gen_basis_spinless_fermion(3,N=5)
print("testing Nf=6")
test_gen_basis_spinless_fermion(3,N=6)
| [
"sys.path.insert",
"quspin.basis.spinless_fermion_basis_1d",
"numpy.testing.assert_allclose",
"itertools.product",
"os.getcwd",
"quspin.basis.spinless_fermion_basis_general"
] | [((108, 138), 'sys.path.insert', 'sys.path.insert', (['(0)', 'qspin_path'], {}), '(0, qspin_path)\n', (123, 138), False, 'import sys, os\n'), ((89, 100), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (98, 100), False, 'import sys, os\n'), ((1373, 1403), 'itertools.product', 'product', (['Nfs', 'kblocks', 'pblocks'], {}), '(Nfs, kblocks, pblocks)\n', (1380, 1403), False, 'from itertools import product\n'), ((1911, 1962), 'quspin.basis.spinless_fermion_basis_1d', 'spinless_fermion_basis_1d', (['L'], {'Nf': 'Nf'}), '(L, Nf=Nf, **basis_blocks)\n', (1936, 1962), False, 'from quspin.basis import spinless_fermion_basis_1d\n'), ((1975, 2029), 'quspin.basis.spinless_fermion_basis_general', 'spinless_fermion_basis_general', (['L'], {'Nf': 'Nf'}), '(L, Nf=Nf, **gen_blocks)\n', (2005, 2029), False, 'from quspin.basis import spinless_fermion_basis_general\n'), ((2280, 2357), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['(basis_1d._basis - gen_basis._basis)', '(0)'], {'atol': '(1e-06)'}), '(basis_1d._basis - gen_basis._basis, 0, atol=1e-06)\n', (2306, 2357), True, 'import numpy as np\n'), ((2355, 2407), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['(n - n_gen)', '(0)'], {'atol': '(1e-06)'}), '(n - n_gen, 0, atol=1e-06)\n', (2381, 2407), True, 'import numpy as np\n'), ((762, 833), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['(row1 - row2)', '(0)'], {'atol': '(1e-06)', 'err_msg': 'err_msg'}), '(row1 - row2, 0, atol=1e-06, err_msg=err_msg)\n', (788, 833), True, 'import numpy as np\n'), ((831, 902), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['(col1 - col2)', '(0)'], {'atol': '(1e-06)', 'err_msg': 'err_msg'}), '(col1 - col2, 0, atol=1e-06, err_msg=err_msg)\n', (857, 902), True, 'import numpy as np\n'), ((900, 969), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['(ME1 - ME2)', '(0)'], {'atol': '(1e-06)', 'err_msg': 'err_msg'}), '(ME1 - ME2, 0, atol=1e-06, err_msg=err_msg)\n', (926, 969), True, 'import numpy as np\n')] |
"""
Mask, padding and batching.
"""
import numpy as np
def pad_batch_data(insts,
pad_idx=0,
return_pos=False,
return_input_mask=False,
return_max_len=False,
return_num_token=False,
return_seq_lens=False):
"""
Pad the instances to the max sequence length in batch, and generate the
corresponding position data and input mask.
"""
return_list = []
max_len = max(len(inst) for inst in insts)
# Any token included in dict can be used to pad, since the paddings' loss
# will be masked out by weights and make no effect on parameter gradients.
inst_data = np.array(
[inst + list([pad_idx] * (max_len - len(inst))) for inst in insts])
return_list += [inst_data.astype("int64").reshape([-1, max_len, 1])]
# position data
if return_pos:
inst_pos = np.array([
list(range(0, len(inst))) + [pad_idx] * (max_len - len(inst))
for inst in insts
])
return_list += [inst_pos.astype("int64").reshape([-1, max_len, 1])]
if return_input_mask:
# This is used to avoid attention on paddings.
input_mask_data = np.array([[1] * len(inst) + [0] *
(max_len - len(inst)) for inst in insts])
input_mask_data = np.expand_dims(input_mask_data, axis=-1)
return_list += [input_mask_data.astype("float32")]
if return_max_len:
return_list += [max_len]
if return_num_token:
num_token = 0
for inst in insts:
num_token += len(inst)
return_list += [num_token]
if return_seq_lens:
seq_lens = np.array([len(inst) for inst in insts])
return_list += [seq_lens.astype("int64").reshape([-1, 1])]
return return_list if len(return_list) > 1 else return_list[0]
| [
"numpy.expand_dims"
] | [((1371, 1411), 'numpy.expand_dims', 'np.expand_dims', (['input_mask_data'], {'axis': '(-1)'}), '(input_mask_data, axis=-1)\n', (1385, 1411), True, 'import numpy as np\n')] |
# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Benchmark JAX implementation vs. NumPy implementation of proximal gradient."""
import time
from typing import NamedTuple
from typing import Sequence
from absl import app
from absl import flags
from sklearn import datasets
from sklearn import preprocessing
import numpy as onp
import jax
import jax.numpy as jnp
from jaxopt import base
from jaxopt import proximal_gradient2 as pg
from jaxopt.prox import prox_lasso
FLAGS = flags.FLAGS
flags.DEFINE_string("dataset", default="boston", help=("Dataset to use."))
flags.DEFINE_bool("float64", default=False, help=("Enable double precision."))
flags.DEFINE_float("lam", default=1.0, help=("Regularization value."))
flags.DEFINE_integer("maxiter", default=200, help=("Max # of iterations."))
flags.DEFINE_integer("n_samples", default=100000, help=("Number of samples."))
flags.DEFINE_integer("n_features", default=200, help=("Number of features."))
flags.DEFINE_bool("verbose", default=False, help=("Enable verbose output."))
def _make_linesearch(fun, prox, maxls):
def linesearch(curr_x, curr_x_fun_val, curr_x_fun_grad, curr_stepsize):
"""A pure NumPy re-implementation of linesearch for benchmarking reasons."""
for _ in range(maxls):
next_x = prox(curr_x - curr_stepsize * curr_x_fun_grad, curr_stepsize)
diff = next_x - curr_x
sqdist = onp.vdot(diff, diff)
value_F = fun(next_x)
value_Q = (curr_x_fun_val + onp.vdot(diff, curr_x_fun_grad) +
0.5 * sqdist / curr_stepsize)
if value_F <= value_Q:
return next_x, curr_stepsize
curr_stepsize *= 0.5
# Undo the last decrase when `maxls` is reached.
curr_stepsize *= 2
return next_x, curr_stepsize
return linesearch
def proximal_gradient_onp(fun, init, prox, stepsize, maxiter=200, maxls=15,
tol=1e-3, verbose=0):
"""A pure NumPy re-implementation of proximal gradient for benchmarking."""
curr_x = init
curr_stepsize = 1.0
linesearch = _make_linesearch(fun, prox, maxls)
for iter_num in range(1, maxiter + 1):
# Convergence monitoring.
curr_x_fun_val, curr_x_fun_grad = fun(curr_x, grad=True)
diff_x = curr_x - prox(curr_x - curr_x_fun_grad)
curr_error = onp.sqrt(onp.sum(diff_x ** 2))
if verbose: print(iter_num, curr_error)
if curr_error <= tol: break
if stepsize <= 0:
# With line search.
curr_x, curr_stepsize = linesearch(curr_x, curr_x_fun_val,
curr_x_fun_grad, curr_stepsize)
if curr_stepsize <= 1e-6:
# Reset step size.
curr_stepsize = 1.0
else:
curr_stepsize *= 2
else:
# Without line search.
curr_x = prox(curr_x - stepsize * curr_x_fun_grad, stepsize)
state = pg.ProxGradState(iter_num=iter_num, error=curr_error,
stepsize=curr_stepsize)
return base.OptStep(params=curr_x, state=state)
def proximal_gradient_accel_onp(fun, init, prox, stepsize, maxiter=200,
maxls=15, tol=1e-3, verbose=0):
"""A pure NumPy re-implementation of proximal gradient with acceleration."""
curr_x = init
curr_y = init
curr_t = 1.0
curr_stepsize = 1.0
linesearch = _make_linesearch(fun, prox, maxls)
for iter_num in range(1, maxiter + 1):
# Convergence monitoring
curr_x_fun_grad = fun(curr_x, grad=True)[1]
diff_x = curr_x - prox(curr_x - curr_x_fun_grad)
curr_error = onp.sqrt(onp.sum(diff_x ** 2))
if verbose: print(iter_num, curr_error)
if curr_error <= tol: break
# Iteration.
curr_y_fun_val, curr_y_fun_grad = fun(curr_y, grad=True)
if stepsize <= 0:
# With line search.
next_x, curr_stepsize = linesearch(curr_y, curr_y_fun_val,
curr_y_fun_grad, curr_stepsize)
if curr_stepsize <= 1e-6:
# Reset step size.
curr_stepsize = 1.0
else:
curr_stepsize *= 2
else:
# Without line search.
next_x = prox(curr_y - stepsize * curr_y_fun_grad, stepsize)
next_t = 0.5 * (1 + onp.sqrt(1 + 4 * curr_t ** 2))
diff_x = next_x - curr_x
next_y = next_x + (curr_t - 1) / next_t * diff_x
curr_x = next_x
curr_y = next_y
curr_t = next_t
state = pg.ProxGradState(iter_num=iter_num, error=curr_error,
stepsize=curr_stepsize)
return base.OptStep(params=curr_x, state=state)
def lasso_onp(X, y, lam, stepsize, tol, maxiter, acceleration, verbose):
def fun(w, grad=False):
y_pred = onp.dot(X, w)
diff = y_pred - y
obj = 0.5 * onp.dot(diff, diff)
if not grad: return obj
g = onp.dot(X.T, diff)
return obj, g
def prox(w, stepsize=1.0):
return onp.sign(w) * onp.maximum(onp.abs(w) - lam * stepsize, 0)
init = onp.zeros(X.shape[1], dtype=X.dtype)
solver_fun = proximal_gradient_accel_onp if acceleration else proximal_gradient_onp
return solver_fun(fun=fun, init=init, prox=prox, stepsize=stepsize,
maxiter=maxiter, tol=tol, verbose=verbose)
def lasso_jnp(X, y, lam, stepsize, tol, maxiter, acceleration, verbose):
def fun(w, data):
X, y = data
y_pred = jnp.dot(X, w)
diff = y_pred - y
return 0.5 * jnp.dot(diff, diff)
init = jnp.zeros(X.shape[1], dtype=X.dtype)
solver = pg.ProximalGradient(fun=fun, prox=prox_lasso,
tol=tol, stepsize=stepsize, maxiter=maxiter,
acceleration=acceleration, verbose=verbose)
return solver.run(init, lam, (X, y))
def run_proximal_gradient(X, y, lam, stepsize, maxiter, verbose):
if stepsize <= 0:
print("proximal gradient (line search)")
else:
print("proximal gradient (constant step size)")
print("-" * 50)
start = time.time()
res_onp = lasso_onp(X=X, y=y, lam=lam, stepsize=stepsize, tol=1e-3,
maxiter=maxiter, acceleration=False,
verbose=verbose).state
print("error onp:", res_onp.error)
print("iter_num onp:", res_onp.iter_num)
print("time onp", time.time() - start)
print(flush=True)
start = time.time()
res_jnp = lasso_jnp(X=X, y=y, lam=lam, stepsize=stepsize, tol=1e-3,
maxiter=maxiter, acceleration=False,
verbose=verbose).state
print("error jnp:", res_jnp.error)
print("iter_num jnp:", res_jnp.iter_num)
print("time jnp", time.time() - start)
print(flush=True)
def run_accelerated_proximal_gradient(X, y, lam, stepsize, maxiter, verbose):
if stepsize <= 0:
print("accelerated proximal gradient descent (line search)")
else:
print("accelerated proximal gradient descent (constant step size)")
print("-" * 50)
start = time.time()
res_onp = lasso_onp(X=X, y=y, lam=lam, stepsize=stepsize, tol=1e-3,
maxiter=maxiter, acceleration=True,
verbose=verbose).state
print("error onp:", res_onp.error)
print("iter_num onp:", res_onp.iter_num)
print("time onp", time.time() - start)
print(flush=True)
start = time.time()
res_jnp = lasso_jnp(X=X, y=y, lam=lam, stepsize=stepsize, tol=1e-3,
maxiter=maxiter, acceleration=True, verbose=verbose).state
print("error jnp:", res_jnp.error)
print("iter_num jnp:", res_jnp.iter_num)
print("time jnp", time.time() - start)
print(flush=True)
def load_dataset(dataset, float64=False):
if dataset == "boston":
X, y = datasets.load_boston(return_X_y=True)
elif dataset == "synth":
X, y = datasets.make_classification(n_samples=FLAGS.n_samples,
n_features=FLAGS.n_features,
n_classes=2,
random_state=0)
else:
raise ValueError("Invalid dataset.")
X = preprocessing.Normalizer().fit_transform(X)
if not float64:
X = X.astype(onp.float32)
y = y.astype(onp.float32)
return X, y
def main(argv: Sequence[str]) -> None:
if len(argv) > 1:
raise app.UsageError("Too many command-line arguments.")
if FLAGS.float64:
jax.config.update("jax_enable_x64", True)
X, y = load_dataset(FLAGS.dataset, FLAGS.float64)
print("Dataset:", FLAGS.dataset)
print("n_samples:", X.shape[0])
print("n_features:", X.shape[1])
print("lambda:", FLAGS.lam)
print("maxiter:", FLAGS.maxiter)
print("float64:", FLAGS.float64)
print()
kw = dict(lam=FLAGS.lam, maxiter=FLAGS.maxiter, verbose=FLAGS.verbose)
run_proximal_gradient(X, y, stepsize=1e-3, **kw)
run_proximal_gradient(X, y, stepsize=0, **kw)
run_accelerated_proximal_gradient(X, y, stepsize=1e-3, **kw)
run_accelerated_proximal_gradient(X, y, stepsize=0, **kw)
if __name__ == '__main__':
app.run(main)
| [
"absl.app.UsageError",
"numpy.sqrt",
"absl.flags.DEFINE_float",
"sklearn.datasets.load_boston",
"absl.app.run",
"numpy.dot",
"jax.numpy.dot",
"jaxopt.proximal_gradient2.ProximalGradient",
"sklearn.preprocessing.Normalizer",
"numpy.abs",
"numpy.vdot",
"numpy.sign",
"time.time",
"absl.flags.... | [((1023, 1095), 'absl.flags.DEFINE_string', 'flags.DEFINE_string', (['"""dataset"""'], {'default': '"""boston"""', 'help': '"""Dataset to use."""'}), "('dataset', default='boston', help='Dataset to use.')\n", (1042, 1095), False, 'from absl import flags\n'), ((1098, 1174), 'absl.flags.DEFINE_bool', 'flags.DEFINE_bool', (['"""float64"""'], {'default': '(False)', 'help': '"""Enable double precision."""'}), "('float64', default=False, help='Enable double precision.')\n", (1115, 1174), False, 'from absl import flags\n'), ((1177, 1245), 'absl.flags.DEFINE_float', 'flags.DEFINE_float', (['"""lam"""'], {'default': '(1.0)', 'help': '"""Regularization value."""'}), "('lam', default=1.0, help='Regularization value.')\n", (1195, 1245), False, 'from absl import flags\n'), ((1248, 1321), 'absl.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""maxiter"""'], {'default': '(200)', 'help': '"""Max # of iterations."""'}), "('maxiter', default=200, help='Max # of iterations.')\n", (1268, 1321), False, 'from absl import flags\n'), ((1324, 1400), 'absl.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""n_samples"""'], {'default': '(100000)', 'help': '"""Number of samples."""'}), "('n_samples', default=100000, help='Number of samples.')\n", (1344, 1400), False, 'from absl import flags\n'), ((1403, 1478), 'absl.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""n_features"""'], {'default': '(200)', 'help': '"""Number of features."""'}), "('n_features', default=200, help='Number of features.')\n", (1423, 1478), False, 'from absl import flags\n'), ((1481, 1555), 'absl.flags.DEFINE_bool', 'flags.DEFINE_bool', (['"""verbose"""'], {'default': '(False)', 'help': '"""Enable verbose output."""'}), "('verbose', default=False, help='Enable verbose output.')\n", (1498, 1555), False, 'from absl import flags\n'), ((3323, 3400), 'jaxopt.proximal_gradient2.ProxGradState', 'pg.ProxGradState', ([], {'iter_num': 'iter_num', 'error': 'curr_error', 'stepsize': 'curr_stepsize'}), '(iter_num=iter_num, error=curr_error, stepsize=curr_stepsize)\n', (3339, 3400), True, 'from jaxopt import proximal_gradient2 as pg\n'), ((3438, 3478), 'jaxopt.base.OptStep', 'base.OptStep', ([], {'params': 'curr_x', 'state': 'state'}), '(params=curr_x, state=state)\n', (3450, 3478), False, 'from jaxopt import base\n'), ((4818, 4895), 'jaxopt.proximal_gradient2.ProxGradState', 'pg.ProxGradState', ([], {'iter_num': 'iter_num', 'error': 'curr_error', 'stepsize': 'curr_stepsize'}), '(iter_num=iter_num, error=curr_error, stepsize=curr_stepsize)\n', (4834, 4895), True, 'from jaxopt import proximal_gradient2 as pg\n'), ((4933, 4973), 'jaxopt.base.OptStep', 'base.OptStep', ([], {'params': 'curr_x', 'state': 'state'}), '(params=curr_x, state=state)\n', (4945, 4973), False, 'from jaxopt import base\n'), ((5342, 5378), 'numpy.zeros', 'onp.zeros', (['X.shape[1]'], {'dtype': 'X.dtype'}), '(X.shape[1], dtype=X.dtype)\n', (5351, 5378), True, 'import numpy as onp\n'), ((5805, 5841), 'jax.numpy.zeros', 'jnp.zeros', (['X.shape[1]'], {'dtype': 'X.dtype'}), '(X.shape[1], dtype=X.dtype)\n', (5814, 5841), True, 'import jax.numpy as jnp\n'), ((5853, 5991), 'jaxopt.proximal_gradient2.ProximalGradient', 'pg.ProximalGradient', ([], {'fun': 'fun', 'prox': 'prox_lasso', 'tol': 'tol', 'stepsize': 'stepsize', 'maxiter': 'maxiter', 'acceleration': 'acceleration', 'verbose': 'verbose'}), '(fun=fun, prox=prox_lasso, tol=tol, stepsize=stepsize,\n maxiter=maxiter, acceleration=acceleration, verbose=verbose)\n', (5872, 5991), True, 'from jaxopt import proximal_gradient2 as pg\n'), ((6310, 6321), 'time.time', 'time.time', ([], {}), '()\n', (6319, 6321), False, 'import time\n'), ((6648, 6659), 'time.time', 'time.time', ([], {}), '()\n', (6657, 6659), False, 'import time\n'), ((7248, 7259), 'time.time', 'time.time', ([], {}), '()\n', (7257, 7259), False, 'import time\n'), ((7585, 7596), 'time.time', 'time.time', ([], {}), '()\n', (7594, 7596), False, 'import time\n'), ((9258, 9271), 'absl.app.run', 'app.run', (['main'], {}), '(main)\n', (9265, 9271), False, 'from absl import app\n'), ((5088, 5101), 'numpy.dot', 'onp.dot', (['X', 'w'], {}), '(X, w)\n', (5095, 5101), True, 'import numpy as onp\n'), ((5196, 5214), 'numpy.dot', 'onp.dot', (['X.T', 'diff'], {}), '(X.T, diff)\n', (5203, 5214), True, 'import numpy as onp\n'), ((5722, 5735), 'jax.numpy.dot', 'jnp.dot', (['X', 'w'], {}), '(X, w)\n', (5729, 5735), True, 'import jax.numpy as jnp\n'), ((7970, 8007), 'sklearn.datasets.load_boston', 'datasets.load_boston', ([], {'return_X_y': '(True)'}), '(return_X_y=True)\n', (7990, 8007), False, 'from sklearn import datasets\n'), ((8545, 8595), 'absl.app.UsageError', 'app.UsageError', (['"""Too many command-line arguments."""'], {}), "('Too many command-line arguments.')\n", (8559, 8595), False, 'from absl import app\n'), ((8621, 8662), 'jax.config.update', 'jax.config.update', (['"""jax_enable_x64"""', '(True)'], {}), "('jax_enable_x64', True)\n", (8638, 8662), False, 'import jax\n'), ((1903, 1923), 'numpy.vdot', 'onp.vdot', (['diff', 'diff'], {}), '(diff, diff)\n', (1911, 1923), True, 'import numpy as onp\n'), ((2795, 2815), 'numpy.sum', 'onp.sum', (['(diff_x ** 2)'], {}), '(diff_x ** 2)\n', (2802, 2815), True, 'import numpy as onp\n'), ((4013, 4033), 'numpy.sum', 'onp.sum', (['(diff_x ** 2)'], {}), '(diff_x ** 2)\n', (4020, 4033), True, 'import numpy as onp\n'), ((5140, 5159), 'numpy.dot', 'onp.dot', (['diff', 'diff'], {}), '(diff, diff)\n', (5147, 5159), True, 'import numpy as onp\n'), ((5274, 5285), 'numpy.sign', 'onp.sign', (['w'], {}), '(w)\n', (5282, 5285), True, 'import numpy as onp\n'), ((5775, 5794), 'jax.numpy.dot', 'jnp.dot', (['diff', 'diff'], {}), '(diff, diff)\n', (5782, 5794), True, 'import jax.numpy as jnp\n'), ((6596, 6607), 'time.time', 'time.time', ([], {}), '()\n', (6605, 6607), False, 'import time\n'), ((6934, 6945), 'time.time', 'time.time', ([], {}), '()\n', (6943, 6945), False, 'import time\n'), ((7533, 7544), 'time.time', 'time.time', ([], {}), '()\n', (7542, 7544), False, 'import time\n'), ((7848, 7859), 'time.time', 'time.time', ([], {}), '()\n', (7857, 7859), False, 'import time\n'), ((8046, 8164), 'sklearn.datasets.make_classification', 'datasets.make_classification', ([], {'n_samples': 'FLAGS.n_samples', 'n_features': 'FLAGS.n_features', 'n_classes': '(2)', 'random_state': '(0)'}), '(n_samples=FLAGS.n_samples, n_features=FLAGS.\n n_features, n_classes=2, random_state=0)\n', (8074, 8164), False, 'from sklearn import datasets\n'), ((8336, 8362), 'sklearn.preprocessing.Normalizer', 'preprocessing.Normalizer', ([], {}), '()\n', (8360, 8362), False, 'from sklearn import preprocessing\n'), ((4634, 4663), 'numpy.sqrt', 'onp.sqrt', (['(1 + 4 * curr_t ** 2)'], {}), '(1 + 4 * curr_t ** 2)\n', (4642, 4663), True, 'import numpy as onp\n'), ((1986, 2017), 'numpy.vdot', 'onp.vdot', (['diff', 'curr_x_fun_grad'], {}), '(diff, curr_x_fun_grad)\n', (1994, 2017), True, 'import numpy as onp\n'), ((5300, 5310), 'numpy.abs', 'onp.abs', (['w'], {}), '(w)\n', (5307, 5310), True, 'import numpy as onp\n')] |
# -*- coding: utf-8 -*-
# mypy: ignore-errors
import jax.numpy as jnp
import numpy as np
import tinygp
def check_noise_model(noise, dense_rep):
random = np.random.default_rng(6675)
np.testing.assert_allclose(noise.diagonal(), jnp.diag(dense_rep))
np.testing.assert_allclose(noise + np.zeros_like(dense_rep), dense_rep)
y1 = random.normal(size=dense_rep.shape)
np.testing.assert_allclose(noise + y1, dense_rep + y1)
np.testing.assert_allclose(y1 + noise, y1 + dense_rep)
np.testing.assert_allclose(noise @ y1, dense_rep @ y1)
y2 = random.normal(size=(dense_rep.shape[1], 3))
np.testing.assert_allclose(noise @ y2, dense_rep @ y2)
y3 = random.normal(size=dense_rep.shape[1])
np.testing.assert_allclose(noise @ y3, dense_rep @ y3)
try:
qsm = noise.to_qsm()
except NotImplementedError:
pass
else:
np.testing.assert_allclose(qsm @ y1, dense_rep @ y1)
np.testing.assert_allclose(qsm @ y2, dense_rep @ y2)
np.testing.assert_allclose(qsm @ y3, dense_rep @ y3)
def test_diagonal():
N = 50
random = np.random.default_rng(9432)
diag = random.normal(size=N)
noise = tinygp.noise.Diagonal(diag=diag)
check_noise_model(noise, np.diag(diag))
def test_banded():
N, J = 50, 5
random = np.random.default_rng(9432)
# Create a random symmetric banded matrix
R = random.normal(size=(N, N))
R[np.triu_indices(N, J + 1)] = 0
R[np.tril_indices(N)] = R.T[np.tril_indices(N)]
# Extract the diagonal and off-diagonal elements
diag = np.diag(R)
off_diags = np.zeros((N, J))
for j in range(J):
off_diags[: N - j - 1, j] = R[
(np.arange(0, N - j - 1), np.arange(j + 1, N))
]
noise = tinygp.noise.Banded(diag=diag, off_diags=off_diags)
check_noise_model(noise, R)
def test_dense():
N = 50
random = np.random.default_rng(9432)
M = random.normal(size=(N, N))
noise = tinygp.noise.Dense(value=M)
check_noise_model(noise, M)
| [
"tinygp.noise.Diagonal",
"numpy.random.default_rng",
"tinygp.noise.Dense",
"numpy.triu_indices",
"numpy.testing.assert_allclose",
"numpy.zeros_like",
"numpy.diag",
"numpy.zeros",
"tinygp.noise.Banded",
"numpy.tril_indices",
"numpy.arange",
"jax.numpy.diag"
] | [((161, 188), 'numpy.random.default_rng', 'np.random.default_rng', (['(6675)'], {}), '(6675)\n', (182, 188), True, 'import numpy as np\n'), ((386, 440), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['(noise + y1)', '(dense_rep + y1)'], {}), '(noise + y1, dense_rep + y1)\n', (412, 440), True, 'import numpy as np\n'), ((445, 499), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['(y1 + noise)', '(y1 + dense_rep)'], {}), '(y1 + noise, y1 + dense_rep)\n', (471, 499), True, 'import numpy as np\n'), ((504, 558), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['(noise @ y1)', '(dense_rep @ y1)'], {}), '(noise @ y1, dense_rep @ y1)\n', (530, 558), True, 'import numpy as np\n'), ((617, 671), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['(noise @ y2)', '(dense_rep @ y2)'], {}), '(noise @ y2, dense_rep @ y2)\n', (643, 671), True, 'import numpy as np\n'), ((725, 779), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['(noise @ y3)', '(dense_rep @ y3)'], {}), '(noise @ y3, dense_rep @ y3)\n', (751, 779), True, 'import numpy as np\n'), ((1104, 1131), 'numpy.random.default_rng', 'np.random.default_rng', (['(9432)'], {}), '(9432)\n', (1125, 1131), True, 'import numpy as np\n'), ((1177, 1209), 'tinygp.noise.Diagonal', 'tinygp.noise.Diagonal', ([], {'diag': 'diag'}), '(diag=diag)\n', (1198, 1209), False, 'import tinygp\n'), ((1305, 1332), 'numpy.random.default_rng', 'np.random.default_rng', (['(9432)'], {}), '(9432)\n', (1326, 1332), True, 'import numpy as np\n'), ((1569, 1579), 'numpy.diag', 'np.diag', (['R'], {}), '(R)\n', (1576, 1579), True, 'import numpy as np\n'), ((1596, 1612), 'numpy.zeros', 'np.zeros', (['(N, J)'], {}), '((N, J))\n', (1604, 1612), True, 'import numpy as np\n'), ((1757, 1808), 'tinygp.noise.Banded', 'tinygp.noise.Banded', ([], {'diag': 'diag', 'off_diags': 'off_diags'}), '(diag=diag, off_diags=off_diags)\n', (1776, 1808), False, 'import tinygp\n'), ((1885, 1912), 'numpy.random.default_rng', 'np.random.default_rng', (['(9432)'], {}), '(9432)\n', (1906, 1912), True, 'import numpy as np\n'), ((1960, 1987), 'tinygp.noise.Dense', 'tinygp.noise.Dense', ([], {'value': 'M'}), '(value=M)\n', (1978, 1987), False, 'import tinygp\n'), ((239, 258), 'jax.numpy.diag', 'jnp.diag', (['dense_rep'], {}), '(dense_rep)\n', (247, 258), True, 'import jax.numpy as jnp\n'), ((882, 934), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['(qsm @ y1)', '(dense_rep @ y1)'], {}), '(qsm @ y1, dense_rep @ y1)\n', (908, 934), True, 'import numpy as np\n'), ((943, 995), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['(qsm @ y2)', '(dense_rep @ y2)'], {}), '(qsm @ y2, dense_rep @ y2)\n', (969, 995), True, 'import numpy as np\n'), ((1004, 1056), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['(qsm @ y3)', '(dense_rep @ y3)'], {}), '(qsm @ y3, dense_rep @ y3)\n', (1030, 1056), True, 'import numpy as np\n'), ((1239, 1252), 'numpy.diag', 'np.diag', (['diag'], {}), '(diag)\n', (1246, 1252), True, 'import numpy as np\n'), ((1421, 1446), 'numpy.triu_indices', 'np.triu_indices', (['N', '(J + 1)'], {}), '(N, J + 1)\n', (1436, 1446), True, 'import numpy as np\n'), ((1458, 1476), 'numpy.tril_indices', 'np.tril_indices', (['N'], {}), '(N)\n', (1473, 1476), True, 'import numpy as np\n'), ((1484, 1502), 'numpy.tril_indices', 'np.tril_indices', (['N'], {}), '(N)\n', (1499, 1502), True, 'import numpy as np\n'), ((299, 323), 'numpy.zeros_like', 'np.zeros_like', (['dense_rep'], {}), '(dense_rep)\n', (312, 323), True, 'import numpy as np\n'), ((1688, 1711), 'numpy.arange', 'np.arange', (['(0)', '(N - j - 1)'], {}), '(0, N - j - 1)\n', (1697, 1711), True, 'import numpy as np\n'), ((1713, 1732), 'numpy.arange', 'np.arange', (['(j + 1)', 'N'], {}), '(j + 1, N)\n', (1722, 1732), True, 'import numpy as np\n')] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.